id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_3117_0
/* * KLSI KL5KUSB105 chip RS232 converter driver * * Copyright (C) 2010 Johan Hovold <jhovold@gmail.com> * Copyright (C) 2001 Utz-Uwe Haus <haus@uuhaus.de> * * 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 2 of the License, or * (at your option) any later version. * * All information about the device was acquired using SniffUSB ans snoopUSB * on Windows98. * It was written out of frustration with the PalmConnect USB Serial adapter * sold by Palm Inc. * Neither Palm, nor their contractor (MCCI) or their supplier (KLSI) provided * information that was not already available. * * It seems that KLSI bought some silicon-design information from ScanLogic, * whose SL11R processor is at the core of the KL5KUSB chipset from KLSI. * KLSI has firmware available for their devices; it is probable that the * firmware differs from that used by KLSI in their products. If you have an * original KLSI device and can provide some information on it, I would be * most interested in adding support for it here. If you have any information * on the protocol used (or find errors in my reverse-engineered stuff), please * let me know. * * The code was only tested with a PalmConnect USB adapter; if you * are adventurous, try it with any KLSI-based device and let me know how it * breaks so that I can fix it! */ /* TODO: * check modem line signals * implement handshaking or decide that we do not support it */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/uaccess.h> #include <asm/unaligned.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include "kl5kusb105.h" #define DRIVER_AUTHOR "Utz-Uwe Haus <haus@uuhaus.de>, Johan Hovold <jhovold@gmail.com>" #define DRIVER_DESC "KLSI KL5KUSB105 chipset USB->Serial Converter driver" /* * Function prototypes */ static int klsi_105_port_probe(struct usb_serial_port *port); static int klsi_105_port_remove(struct usb_serial_port *port); static int klsi_105_open(struct tty_struct *tty, struct usb_serial_port *port); static void klsi_105_close(struct usb_serial_port *port); static void klsi_105_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old); static int klsi_105_tiocmget(struct tty_struct *tty); static void klsi_105_process_read_urb(struct urb *urb); static int klsi_105_prepare_write_buffer(struct usb_serial_port *port, void *dest, size_t size); /* * All of the device info needed for the KLSI converters. */ static const struct usb_device_id id_table[] = { { USB_DEVICE(PALMCONNECT_VID, PALMCONNECT_PID) }, { USB_DEVICE(KLSI_VID, KLSI_KL5KUSB105D_PID) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, id_table); static struct usb_serial_driver kl5kusb105d_device = { .driver = { .owner = THIS_MODULE, .name = "kl5kusb105d", }, .description = "KL5KUSB105D / PalmConnect", .id_table = id_table, .num_ports = 1, .bulk_out_size = 64, .open = klsi_105_open, .close = klsi_105_close, .set_termios = klsi_105_set_termios, /*.break_ctl = klsi_105_break_ctl,*/ .tiocmget = klsi_105_tiocmget, .port_probe = klsi_105_port_probe, .port_remove = klsi_105_port_remove, .throttle = usb_serial_generic_throttle, .unthrottle = usb_serial_generic_unthrottle, .process_read_urb = klsi_105_process_read_urb, .prepare_write_buffer = klsi_105_prepare_write_buffer, }; static struct usb_serial_driver * const serial_drivers[] = { &kl5kusb105d_device, NULL }; struct klsi_105_port_settings { __u8 pktlen; /* always 5, it seems */ __u8 baudrate; __u8 databits; __u8 unknown1; __u8 unknown2; } __attribute__ ((packed)); struct klsi_105_private { struct klsi_105_port_settings cfg; struct ktermios termios; unsigned long line_state; /* modem line settings */ spinlock_t lock; }; /* * Handle vendor specific USB requests */ #define KLSI_TIMEOUT 5000 /* default urb timeout */ static int klsi_105_chg_port_settings(struct usb_serial_port *port, struct klsi_105_port_settings *settings) { int rc; rc = usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_SET_DATA, USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_INTERFACE, 0, /* value */ 0, /* index */ settings, sizeof(struct klsi_105_port_settings), KLSI_TIMEOUT); if (rc < 0) dev_err(&port->dev, "Change port settings failed (error = %d)\n", rc); dev_info(&port->serial->dev->dev, "%d byte block, baudrate %x, databits %d, u1 %d, u2 %d\n", settings->pktlen, settings->baudrate, settings->databits, settings->unknown1, settings->unknown2); return rc; } /* translate a 16-bit status value from the device to linux's TIO bits */ static unsigned long klsi_105_status2linestate(const __u16 status) { unsigned long res = 0; res = ((status & KL5KUSB105A_DSR) ? TIOCM_DSR : 0) | ((status & KL5KUSB105A_CTS) ? TIOCM_CTS : 0) ; return res; } /* * Read line control via vendor command and return result through * *line_state_p */ /* It seems that the status buffer has always only 2 bytes length */ #define KLSI_STATUSBUF_LEN 2 static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc < 0) dev_err(&port->dev, "Reading line status failed (error = %d)\n", rc); else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; } /* * Driver's tty interface functions */ static int klsi_105_port_probe(struct usb_serial_port *port) { struct klsi_105_private *priv; priv = kmalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; /* set initial values for control structures */ priv->cfg.pktlen = 5; priv->cfg.baudrate = kl5kusb105a_sio_b9600; priv->cfg.databits = kl5kusb105a_dtb_8; priv->cfg.unknown1 = 0; priv->cfg.unknown2 = 1; priv->line_state = 0; spin_lock_init(&priv->lock); /* priv->termios is left uninitialized until port opening */ usb_set_serial_port_data(port, priv); return 0; } static int klsi_105_port_remove(struct usb_serial_port *port) { struct klsi_105_private *priv; priv = usb_get_serial_port_data(port); kfree(priv); return 0; } static int klsi_105_open(struct tty_struct *tty, struct usb_serial_port *port) { struct klsi_105_private *priv = usb_get_serial_port_data(port); int retval = 0; int rc; int i; unsigned long line_state; struct klsi_105_port_settings *cfg; unsigned long flags; /* Do a defined restart: * Set up sane default baud rate and send the 'READ_ON' * vendor command. * FIXME: set modem line control (how?) * Then read the modem line control and store values in * priv->line_state. */ cfg = kmalloc(sizeof(*cfg), GFP_KERNEL); if (!cfg) return -ENOMEM; cfg->pktlen = 5; cfg->baudrate = kl5kusb105a_sio_b9600; cfg->databits = kl5kusb105a_dtb_8; cfg->unknown1 = 0; cfg->unknown2 = 1; klsi_105_chg_port_settings(port, cfg); /* set up termios structure */ spin_lock_irqsave(&priv->lock, flags); priv->termios.c_iflag = tty->termios.c_iflag; priv->termios.c_oflag = tty->termios.c_oflag; priv->termios.c_cflag = tty->termios.c_cflag; priv->termios.c_lflag = tty->termios.c_lflag; for (i = 0; i < NCCS; i++) priv->termios.c_cc[i] = tty->termios.c_cc[i]; priv->cfg.pktlen = cfg->pktlen; priv->cfg.baudrate = cfg->baudrate; priv->cfg.databits = cfg->databits; priv->cfg.unknown1 = cfg->unknown1; priv->cfg.unknown2 = cfg->unknown2; spin_unlock_irqrestore(&priv->lock, flags); /* READ_ON and urb submission */ rc = usb_serial_generic_open(tty, port); if (rc) { retval = rc; goto err_free_cfg; } rc = usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_CONFIGURE, USB_TYPE_VENDOR|USB_DIR_OUT|USB_RECIP_INTERFACE, KL5KUSB105A_SIO_CONFIGURE_READ_ON, 0, /* index */ NULL, 0, KLSI_TIMEOUT); if (rc < 0) { dev_err(&port->dev, "Enabling read failed (error = %d)\n", rc); retval = rc; goto err_generic_close; } else dev_dbg(&port->dev, "%s - enabled reading\n", __func__); rc = klsi_105_get_line_state(port, &line_state); if (rc < 0) { retval = rc; goto err_disable_read; } spin_lock_irqsave(&priv->lock, flags); priv->line_state = line_state; spin_unlock_irqrestore(&priv->lock, flags); dev_dbg(&port->dev, "%s - read line state 0x%lx\n", __func__, line_state); return 0; err_disable_read: usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_CONFIGURE, USB_TYPE_VENDOR | USB_DIR_OUT, KL5KUSB105A_SIO_CONFIGURE_READ_OFF, 0, /* index */ NULL, 0, KLSI_TIMEOUT); err_generic_close: usb_serial_generic_close(port); err_free_cfg: kfree(cfg); return retval; } static void klsi_105_close(struct usb_serial_port *port) { int rc; /* send READ_OFF */ rc = usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_CONFIGURE, USB_TYPE_VENDOR | USB_DIR_OUT, KL5KUSB105A_SIO_CONFIGURE_READ_OFF, 0, /* index */ NULL, 0, KLSI_TIMEOUT); if (rc < 0) dev_err(&port->dev, "failed to disable read: %d\n", rc); /* shutdown our bulk reads and writes */ usb_serial_generic_close(port); } /* We need to write a complete 64-byte data block and encode the * number actually sent in the first double-byte, LSB-order. That * leaves at most 62 bytes of payload. */ #define KLSI_HDR_LEN 2 static int klsi_105_prepare_write_buffer(struct usb_serial_port *port, void *dest, size_t size) { unsigned char *buf = dest; int count; count = kfifo_out_locked(&port->write_fifo, buf + KLSI_HDR_LEN, size, &port->lock); put_unaligned_le16(count, buf); return count + KLSI_HDR_LEN; } /* The data received is preceded by a length double-byte in LSB-first order. */ static void klsi_105_process_read_urb(struct urb *urb) { struct usb_serial_port *port = urb->context; unsigned char *data = urb->transfer_buffer; unsigned len; /* empty urbs seem to happen, we ignore them */ if (!urb->actual_length) return; if (urb->actual_length <= KLSI_HDR_LEN) { dev_dbg(&port->dev, "%s - malformed packet\n", __func__); return; } len = get_unaligned_le16(data); if (len > urb->actual_length - KLSI_HDR_LEN) { dev_dbg(&port->dev, "%s - packet length mismatch\n", __func__); len = urb->actual_length - KLSI_HDR_LEN; } tty_insert_flip_string(&port->port, data + KLSI_HDR_LEN, len); tty_flip_buffer_push(&port->port); } static void klsi_105_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct klsi_105_private *priv = usb_get_serial_port_data(port); struct device *dev = &port->dev; unsigned int iflag = tty->termios.c_iflag; unsigned int old_iflag = old_termios->c_iflag; unsigned int cflag = tty->termios.c_cflag; unsigned int old_cflag = old_termios->c_cflag; struct klsi_105_port_settings *cfg; unsigned long flags; speed_t baud; cfg = kmalloc(sizeof(*cfg), GFP_KERNEL); if (!cfg) return; /* lock while we are modifying the settings */ spin_lock_irqsave(&priv->lock, flags); /* * Update baud rate */ baud = tty_get_baud_rate(tty); if ((cflag & CBAUD) != (old_cflag & CBAUD)) { /* reassert DTR and (maybe) RTS on transition from B0 */ if ((old_cflag & CBAUD) == B0) { dev_dbg(dev, "%s: baud was B0\n", __func__); #if 0 priv->control_state |= TIOCM_DTR; /* don't set RTS if using hardware flow control */ if (!(old_cflag & CRTSCTS)) priv->control_state |= TIOCM_RTS; mct_u232_set_modem_ctrl(serial, priv->control_state); #endif } } switch (baud) { case 0: /* handled below */ break; case 1200: priv->cfg.baudrate = kl5kusb105a_sio_b1200; break; case 2400: priv->cfg.baudrate = kl5kusb105a_sio_b2400; break; case 4800: priv->cfg.baudrate = kl5kusb105a_sio_b4800; break; case 9600: priv->cfg.baudrate = kl5kusb105a_sio_b9600; break; case 19200: priv->cfg.baudrate = kl5kusb105a_sio_b19200; break; case 38400: priv->cfg.baudrate = kl5kusb105a_sio_b38400; break; case 57600: priv->cfg.baudrate = kl5kusb105a_sio_b57600; break; case 115200: priv->cfg.baudrate = kl5kusb105a_sio_b115200; break; default: dev_dbg(dev, "unsupported baudrate, using 9600\n"); priv->cfg.baudrate = kl5kusb105a_sio_b9600; baud = 9600; break; } if ((cflag & CBAUD) == B0) { dev_dbg(dev, "%s: baud is B0\n", __func__); /* Drop RTS and DTR */ /* maybe this should be simulated by sending read * disable and read enable messages? */ #if 0 priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); mct_u232_set_modem_ctrl(serial, priv->control_state); #endif } tty_encode_baud_rate(tty, baud, baud); if ((cflag & CSIZE) != (old_cflag & CSIZE)) { /* set the number of data bits */ switch (cflag & CSIZE) { case CS5: dev_dbg(dev, "%s - 5 bits/byte not supported\n", __func__); spin_unlock_irqrestore(&priv->lock, flags); goto err; case CS6: dev_dbg(dev, "%s - 6 bits/byte not supported\n", __func__); spin_unlock_irqrestore(&priv->lock, flags); goto err; case CS7: priv->cfg.databits = kl5kusb105a_dtb_7; break; case CS8: priv->cfg.databits = kl5kusb105a_dtb_8; break; default: dev_err(dev, "CSIZE was not CS5-CS8, using default of 8\n"); priv->cfg.databits = kl5kusb105a_dtb_8; break; } } /* * Update line control register (LCR) */ if ((cflag & (PARENB|PARODD)) != (old_cflag & (PARENB|PARODD)) || (cflag & CSTOPB) != (old_cflag & CSTOPB)) { /* Not currently supported */ tty->termios.c_cflag &= ~(PARENB|PARODD|CSTOPB); #if 0 priv->last_lcr = 0; /* set the parity */ if (cflag & PARENB) priv->last_lcr |= (cflag & PARODD) ? MCT_U232_PARITY_ODD : MCT_U232_PARITY_EVEN; else priv->last_lcr |= MCT_U232_PARITY_NONE; /* set the number of stop bits */ priv->last_lcr |= (cflag & CSTOPB) ? MCT_U232_STOP_BITS_2 : MCT_U232_STOP_BITS_1; mct_u232_set_line_ctrl(serial, priv->last_lcr); #endif } /* * Set flow control: well, I do not really now how to handle DTR/RTS. * Just do what we have seen with SniffUSB on Win98. */ if ((iflag & IXOFF) != (old_iflag & IXOFF) || (iflag & IXON) != (old_iflag & IXON) || (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) { /* Not currently supported */ tty->termios.c_cflag &= ~CRTSCTS; /* Drop DTR/RTS if no flow control otherwise assert */ #if 0 if ((iflag & IXOFF) || (iflag & IXON) || (cflag & CRTSCTS)) priv->control_state |= TIOCM_DTR | TIOCM_RTS; else priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); mct_u232_set_modem_ctrl(serial, priv->control_state); #endif } memcpy(cfg, &priv->cfg, sizeof(*cfg)); spin_unlock_irqrestore(&priv->lock, flags); /* now commit changes to device */ klsi_105_chg_port_settings(port, cfg); err: kfree(cfg); } #if 0 static void mct_u232_break_ctl(struct tty_struct *tty, int break_state) { struct usb_serial_port *port = tty->driver_data; struct usb_serial *serial = port->serial; struct mct_u232_private *priv = (struct mct_u232_private *)port->private; unsigned char lcr = priv->last_lcr; dev_dbg(&port->dev, "%s - state=%d\n", __func__, break_state); /* LOCKING */ if (break_state) lcr |= MCT_U232_SET_BREAK; mct_u232_set_line_ctrl(serial, lcr); } #endif static int klsi_105_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct klsi_105_private *priv = usb_get_serial_port_data(port); unsigned long flags; int rc; unsigned long line_state; rc = klsi_105_get_line_state(port, &line_state); if (rc < 0) { dev_err(&port->dev, "Reading line control failed (error = %d)\n", rc); /* better return value? EAGAIN? */ return rc; } spin_lock_irqsave(&priv->lock, flags); priv->line_state = line_state; spin_unlock_irqrestore(&priv->lock, flags); dev_dbg(&port->dev, "%s - read line state 0x%lx\n", __func__, line_state); return (int)line_state; } module_usb_serial_driver(serial_drivers, id_table); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-532/c/bad_3117_0
crossvul-cpp_data_good_4043_0
/* support.c - support functions for pam_tacplus.c * * Copyright (C) 2010, Pawel Krawczyk <pawel.krawczyk@hush.com> and * Jeroen Nijhof <jeroen@jeroennijhof.nl> * * 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 2 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 - see the file COPYING. * * See `CHANGES' file for revision history. */ #define PAM_SM_AUTH #define PAM_SM_ACCOUNT #define PAM_SM_SESSION #define PAM_SM_PASSWORD #include "config.h" #include "support.h" #include "pam_tacplus.h" #ifdef HAVE_LIMITS_H #include <limits.h> #endif tacplus_server_t tac_srv[TAC_PLUS_MAXSERVERS]; unsigned int tac_srv_no = 0; char tac_service[64]; char tac_protocol[64]; char tac_prompt[64]; struct addrinfo tac_srv_addr[TAC_PLUS_MAXSERVERS]; struct sockaddr tac_sock_addr[TAC_PLUS_MAXSERVERS]; struct sockaddr_in6 tac_sock6_addr[TAC_PLUS_MAXSERVERS]; char tac_srv_key[TAC_PLUS_MAXSERVERS][TAC_SECRET_MAX_LEN+1]; void _pam_log(int err, const char *format, ...) { char msg[256]; va_list args; va_start(args, format); vsnprintf(msg, sizeof(msg), format, args); syslog(err, "PAM-tacplus: %s", msg); va_end(args); } char *_pam_get_user(pam_handle_t *pamh) { int retval; char *user; retval = pam_get_user(pamh, (void *) &user, "Username: "); if (retval != PAM_SUCCESS || user == NULL || *user == '\0') { _pam_log(LOG_ERR, "unable to obtain username"); user = NULL; } return user; } char *_pam_get_terminal(pam_handle_t *pamh) { int retval; char *tty; retval = pam_get_item(pamh, PAM_TTY, (void *) &tty); if (retval != PAM_SUCCESS || tty == NULL || *tty == '\0') { tty = ttyname(STDIN_FILENO); if (tty == NULL || *tty == '\0') tty = "unknown"; } return tty; } char *_pam_get_rhost(pam_handle_t *pamh) { int retval; char *rhost; retval = pam_get_item(pamh, PAM_RHOST, (void *) &rhost); if (retval != PAM_SUCCESS || rhost == NULL || *rhost == '\0') { rhost = "unknown"; } return rhost; } int converse(pam_handle_t *pamh, int nargs, const struct pam_message *message, struct pam_response **response) { int retval; struct pam_conv *conv; if ((retval = pam_get_item(pamh, PAM_CONV, (const void **) &conv)) == PAM_SUCCESS) { retval = conv->conv(nargs, &message, response, conv->appdata_ptr); if (retval != PAM_SUCCESS) { _pam_log(LOG_ERR, "(pam_tacplus) converse returned %d", retval); _pam_log(LOG_ERR, "that is: %s", pam_strerror(pamh, retval)); } } else { _pam_log(LOG_ERR, "(pam_tacplus) converse failed to get pam_conv"); } return retval; } /* stolen from pam_stress */ int tacacs_get_password(pam_handle_t *pamh, int flags __Unused, int ctrl, char **password) { (void) flags; const void *pam_pass; char *pass = NULL; if (ctrl & PAM_TAC_DEBUG) syslog(LOG_DEBUG, "%s: called", __FUNCTION__); if ((ctrl & (PAM_TAC_TRY_FIRST_PASS | PAM_TAC_USE_FIRST_PASS)) && (pam_get_item(pamh, PAM_AUTHTOK, &pam_pass) == PAM_SUCCESS) && (pam_pass != NULL)) { if ((pass = strdup(pam_pass)) == NULL) return PAM_BUF_ERR; } else if ((ctrl & PAM_TAC_USE_FIRST_PASS)) { _pam_log(LOG_WARNING, "no forwarded password"); return PAM_PERM_DENIED; } else { struct pam_message msg; struct pam_response *resp = NULL; int retval; /* set up conversation call */ msg.msg_style = PAM_PROMPT_ECHO_OFF; if (!tac_prompt[0]) { msg.msg = "Password: "; } else { msg.msg = tac_prompt; } if ((retval = converse(pamh, 1, &msg, &resp)) != PAM_SUCCESS) return retval; if (resp != NULL) { if (resp->resp == NULL && (ctrl & PAM_TAC_DEBUG)) _pam_log(LOG_DEBUG, "pam_sm_authenticate: NULL authtok given"); pass = resp->resp; /* remember this! */ resp->resp = NULL; free(resp); resp = NULL; } else { if (ctrl & PAM_TAC_DEBUG) { _pam_log(LOG_DEBUG, "pam_sm_authenticate: no error reported"); _pam_log(LOG_DEBUG, "getting password, but NULL returned!?"); } return PAM_CONV_ERR; } } /* FIXME *password can still turn out as NULL and it can't be free()d when it's NULL */ *password = pass; /* this *MUST* be free()'d by this module */ if (ctrl & PAM_TAC_DEBUG) syslog(LOG_DEBUG, "%s: obtained password", __FUNCTION__); return PAM_SUCCESS; } void tac_copy_addr_info(struct addrinfo *p_dst, const struct addrinfo *p_src) { if (p_dst && p_src) { p_dst->ai_flags = p_src->ai_flags; p_dst->ai_family = p_src->ai_family; p_dst->ai_socktype = p_src->ai_socktype; p_dst->ai_protocol = p_src->ai_protocol; p_dst->ai_addrlen = p_src->ai_addrlen; /* ipv6 check */ if (p_dst->ai_family == AF_INET6) { memcpy (p_dst->ai_addr, p_src->ai_addr, sizeof(struct sockaddr_in6)); memset ((struct sockaddr_in6*)p_dst->ai_addr, 0 , sizeof(struct sockaddr_in6)); memcpy ((struct sockaddr_in6*)p_dst->ai_addr, (struct sockaddr_in6*)p_src->ai_addr, sizeof(struct sockaddr_in6)); } else { memcpy (p_dst->ai_addr, p_src->ai_addr, sizeof(struct sockaddr)); } p_dst->ai_canonname = NULL; /* we do not care it */ p_dst->ai_next = NULL; /* no more chain */ } } static void set_tac_srv_addr (unsigned int srv_no, const struct addrinfo *addr) { _pam_log(LOG_DEBUG, "%s: server [%s]", __FUNCTION__, tac_ntop(addr->ai_addr)); if (srv_no < TAC_PLUS_MAXSERVERS) { if (addr) { if (addr->ai_family == AF_INET6) { tac_srv_addr[srv_no].ai_addr = (struct sockaddr *)&tac_sock6_addr[srv_no]; } else { tac_srv_addr[srv_no].ai_addr = &tac_sock_addr[srv_no]; } tac_copy_addr_info (&tac_srv_addr[srv_no], addr); tac_srv[srv_no].addr = &tac_srv_addr[srv_no]; /*this code will copy the ipv6 address to a temp variable */ /*and copies to global tac_srv array*/ if (addr->ai_family == AF_INET6) { memset (&tac_sock6_addr[srv_no], 0, sizeof(struct sockaddr_in6)); memcpy (&tac_sock6_addr[srv_no], (struct sockaddr_in6*)addr->ai_addr, sizeof(struct sockaddr_in6)); tac_srv[srv_no].addr->ai_addr = (struct sockaddr *)&tac_sock6_addr[srv_no]; } _pam_log(LOG_DEBUG, "%s: server %d after copy [%s]", __FUNCTION__, srv_no, tac_ntop(tac_srv[srv_no].addr->ai_addr)); } else { tac_srv[srv_no].addr = NULL; } } } static void set_tac_srv_key(unsigned int srv_no, const char *key) { if (srv_no < TAC_PLUS_MAXSERVERS) { if (key) { strncpy(tac_srv_key[srv_no], key, TAC_SECRET_MAX_LEN - 1); tac_srv[srv_no].key = tac_srv_key[srv_no]; } else { _pam_log(LOG_DEBUG, "%s: server %d key is null; address [%s]", __FUNCTION__,srv_no, tac_ntop(tac_srv[srv_no].addr->ai_addr)); tac_srv[srv_no].key = NULL; } } } int _pam_parse(int argc, const char **argv) { int ctrl = 0; const char *current_secret = NULL; /* otherwise the list will grow with each call */ memset(tac_srv, 0, sizeof(tacplus_server_t) * TAC_PLUS_MAXSERVERS); memset(&tac_srv_addr, 0, sizeof(struct addrinfo) * TAC_PLUS_MAXSERVERS); memset(&tac_sock_addr, 0, sizeof(struct sockaddr) * TAC_PLUS_MAXSERVERS); memset(&tac_sock6_addr, 0, sizeof(struct sockaddr_in6) * TAC_PLUS_MAXSERVERS); tac_srv_no = 0; tac_service[0] = 0; tac_protocol[0] = 0; tac_prompt[0] = 0; tac_login[0] = 0; for (ctrl = 0; argc-- > 0; ++argv) { if (!strcmp(*argv, "debug")) { /* all */ ctrl |= PAM_TAC_DEBUG; } else if (!strcmp(*argv, "use_first_pass")) { ctrl |= PAM_TAC_USE_FIRST_PASS; } else if (!strcmp(*argv, "try_first_pass")) { ctrl |= PAM_TAC_TRY_FIRST_PASS; } else if (!strncmp(*argv, "service=", 8)) { /* author & acct */ xstrcpy(tac_service, *argv + 8, sizeof(tac_service)); } else if (!strncmp(*argv, "protocol=", 9)) { /* author & acct */ xstrcpy(tac_protocol, *argv + 9, sizeof(tac_protocol)); } else if (!strncmp(*argv, "prompt=", 7)) { /* authentication */ xstrcpy(tac_prompt, *argv + 7, sizeof(tac_prompt)); /* Replace _ with space */ unsigned long chr; for (chr = 0; chr < strlen(tac_prompt); chr++) { if (tac_prompt[chr] == '_') { tac_prompt[chr] = ' '; } } } else if (!strncmp(*argv, "login=", 6)) { xstrcpy(tac_login, *argv + 6, sizeof(tac_login)); } else if (!strcmp(*argv, "acct_all")) { ctrl |= PAM_TAC_ACCT; } else if (!strncmp(*argv, "server=", 7)) { /* authen & acct */ if (tac_srv_no < TAC_PLUS_MAXSERVERS) { struct addrinfo hints, *servers, *server; int rv; char *close_bracket, *server_name, *port, server_buf[256]; memset(&hints, 0, sizeof hints); memset(&server_buf, 0, sizeof(server_buf)); hints.ai_family = AF_UNSPEC; /* use IPv4 or IPv6, whichever */ hints.ai_socktype = SOCK_STREAM; if (strlen(*argv + 7) >= sizeof(server_buf)) { _pam_log(LOG_ERR, "server address too long, sorry"); continue; } strcpy(server_buf, *argv + 7); if (*server_buf == '[' && (close_bracket = strchr(server_buf, ']')) != NULL) { /* Check for URI syntax */ server_name = server_buf + 1; _pam_log (LOG_ERR, "reading server address as: %s ", server_name); port = strchr(close_bracket, ':'); *close_bracket = '\0'; } else { /* Fall back to traditional syntax */ server_name = server_buf; port = strchr(server_buf, ':'); } if (port != NULL) { *port = '\0'; port++; } _pam_log (LOG_DEBUG, "sending server address to getaddrinfo as: %s ", server_name); if ((rv = getaddrinfo(server_name, (port == NULL) ? "49" : port, &hints, &servers)) == 0) { for (server = servers; server != NULL && tac_srv_no < TAC_PLUS_MAXSERVERS; server = server->ai_next) { set_tac_srv_addr(tac_srv_no, server); set_tac_srv_key(tac_srv_no, current_secret); tac_srv_no++; } _pam_log(LOG_DEBUG, "%s: server index %d ", __FUNCTION__, tac_srv_no); freeaddrinfo (servers); } else { _pam_log(LOG_ERR, "skip invalid server: %s (getaddrinfo: %s)", server_name, gai_strerror(rv)); } } else { _pam_log(LOG_ERR, "maximum number of servers (%d) exceeded, skipping", TAC_PLUS_MAXSERVERS); } } else if (!strncmp(*argv, "secret=", 7)) { current_secret = *argv + 7; /* points right into argv (which is const) */ // this is possible because server structure is initialized only on the server= occurence if (tac_srv_no == 0) { _pam_log(LOG_ERR, "secret set but no servers configured yet"); } else { // set secret for the last server configured set_tac_srv_key(tac_srv_no - 1, current_secret); } } else if (!strncmp(*argv, "timeout=", 8)) { #ifdef HAVE_STRTOL tac_timeout = strtol(*argv + 8, NULL, 10); #else tac_timeout = atoi(*argv + 8); #endif if (tac_timeout == LONG_MAX) { _pam_log(LOG_ERR, "timeout parameter cannot be parsed as integer: %s", *argv); tac_timeout = 0; } else { tac_readtimeout_enable = 1; } } else { _pam_log(LOG_WARNING, "unrecognized option: %s", *argv); } } if (ctrl & PAM_TAC_DEBUG) { unsigned long n; _pam_log(LOG_DEBUG, "%d servers defined", tac_srv_no); for (n = 0; n < tac_srv_no; n++) { _pam_log(LOG_DEBUG, "server[%lu] { addr=%s, key='********' }", n, tac_ntop(tac_srv[n].addr->ai_addr)); } _pam_log(LOG_DEBUG, "tac_service='%s'", tac_service); _pam_log(LOG_DEBUG, "tac_protocol='%s'", tac_protocol); _pam_log(LOG_DEBUG, "tac_prompt='%s'", tac_prompt); _pam_log(LOG_DEBUG, "tac_login='%s'", tac_login); } return ctrl; } /* _pam_parse */
./CrossVul/dataset_final_sorted/CWE-532/c/good_4043_0
crossvul-cpp_data_good_3117_0
/* * KLSI KL5KUSB105 chip RS232 converter driver * * Copyright (C) 2010 Johan Hovold <jhovold@gmail.com> * Copyright (C) 2001 Utz-Uwe Haus <haus@uuhaus.de> * * 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 2 of the License, or * (at your option) any later version. * * All information about the device was acquired using SniffUSB ans snoopUSB * on Windows98. * It was written out of frustration with the PalmConnect USB Serial adapter * sold by Palm Inc. * Neither Palm, nor their contractor (MCCI) or their supplier (KLSI) provided * information that was not already available. * * It seems that KLSI bought some silicon-design information from ScanLogic, * whose SL11R processor is at the core of the KL5KUSB chipset from KLSI. * KLSI has firmware available for their devices; it is probable that the * firmware differs from that used by KLSI in their products. If you have an * original KLSI device and can provide some information on it, I would be * most interested in adding support for it here. If you have any information * on the protocol used (or find errors in my reverse-engineered stuff), please * let me know. * * The code was only tested with a PalmConnect USB adapter; if you * are adventurous, try it with any KLSI-based device and let me know how it * breaks so that I can fix it! */ /* TODO: * check modem line signals * implement handshaking or decide that we do not support it */ #include <linux/kernel.h> #include <linux/errno.h> #include <linux/slab.h> #include <linux/tty.h> #include <linux/tty_driver.h> #include <linux/tty_flip.h> #include <linux/module.h> #include <linux/uaccess.h> #include <asm/unaligned.h> #include <linux/usb.h> #include <linux/usb/serial.h> #include "kl5kusb105.h" #define DRIVER_AUTHOR "Utz-Uwe Haus <haus@uuhaus.de>, Johan Hovold <jhovold@gmail.com>" #define DRIVER_DESC "KLSI KL5KUSB105 chipset USB->Serial Converter driver" /* * Function prototypes */ static int klsi_105_port_probe(struct usb_serial_port *port); static int klsi_105_port_remove(struct usb_serial_port *port); static int klsi_105_open(struct tty_struct *tty, struct usb_serial_port *port); static void klsi_105_close(struct usb_serial_port *port); static void klsi_105_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old); static int klsi_105_tiocmget(struct tty_struct *tty); static void klsi_105_process_read_urb(struct urb *urb); static int klsi_105_prepare_write_buffer(struct usb_serial_port *port, void *dest, size_t size); /* * All of the device info needed for the KLSI converters. */ static const struct usb_device_id id_table[] = { { USB_DEVICE(PALMCONNECT_VID, PALMCONNECT_PID) }, { USB_DEVICE(KLSI_VID, KLSI_KL5KUSB105D_PID) }, { } /* Terminating entry */ }; MODULE_DEVICE_TABLE(usb, id_table); static struct usb_serial_driver kl5kusb105d_device = { .driver = { .owner = THIS_MODULE, .name = "kl5kusb105d", }, .description = "KL5KUSB105D / PalmConnect", .id_table = id_table, .num_ports = 1, .bulk_out_size = 64, .open = klsi_105_open, .close = klsi_105_close, .set_termios = klsi_105_set_termios, /*.break_ctl = klsi_105_break_ctl,*/ .tiocmget = klsi_105_tiocmget, .port_probe = klsi_105_port_probe, .port_remove = klsi_105_port_remove, .throttle = usb_serial_generic_throttle, .unthrottle = usb_serial_generic_unthrottle, .process_read_urb = klsi_105_process_read_urb, .prepare_write_buffer = klsi_105_prepare_write_buffer, }; static struct usb_serial_driver * const serial_drivers[] = { &kl5kusb105d_device, NULL }; struct klsi_105_port_settings { __u8 pktlen; /* always 5, it seems */ __u8 baudrate; __u8 databits; __u8 unknown1; __u8 unknown2; } __attribute__ ((packed)); struct klsi_105_private { struct klsi_105_port_settings cfg; struct ktermios termios; unsigned long line_state; /* modem line settings */ spinlock_t lock; }; /* * Handle vendor specific USB requests */ #define KLSI_TIMEOUT 5000 /* default urb timeout */ static int klsi_105_chg_port_settings(struct usb_serial_port *port, struct klsi_105_port_settings *settings) { int rc; rc = usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_SET_DATA, USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_INTERFACE, 0, /* value */ 0, /* index */ settings, sizeof(struct klsi_105_port_settings), KLSI_TIMEOUT); if (rc < 0) dev_err(&port->dev, "Change port settings failed (error = %d)\n", rc); dev_info(&port->serial->dev->dev, "%d byte block, baudrate %x, databits %d, u1 %d, u2 %d\n", settings->pktlen, settings->baudrate, settings->databits, settings->unknown1, settings->unknown2); return rc; } /* translate a 16-bit status value from the device to linux's TIO bits */ static unsigned long klsi_105_status2linestate(const __u16 status) { unsigned long res = 0; res = ((status & KL5KUSB105A_DSR) ? TIOCM_DSR : 0) | ((status & KL5KUSB105A_CTS) ? TIOCM_CTS : 0) ; return res; } /* * Read line control via vendor command and return result through * *line_state_p */ /* It seems that the status buffer has always only 2 bytes length */ #define KLSI_STATUSBUF_LEN 2 static int klsi_105_get_line_state(struct usb_serial_port *port, unsigned long *line_state_p) { int rc; u8 *status_buf; __u16 status; dev_info(&port->serial->dev->dev, "sending SIO Poll request\n"); status_buf = kmalloc(KLSI_STATUSBUF_LEN, GFP_KERNEL); if (!status_buf) return -ENOMEM; status_buf[0] = 0xff; status_buf[1] = 0xff; rc = usb_control_msg(port->serial->dev, usb_rcvctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_POLL, USB_TYPE_VENDOR | USB_DIR_IN, 0, /* value */ 0, /* index */ status_buf, KLSI_STATUSBUF_LEN, 10000 ); if (rc != KLSI_STATUSBUF_LEN) { dev_err(&port->dev, "reading line status failed: %d\n", rc); if (rc >= 0) rc = -EIO; } else { status = get_unaligned_le16(status_buf); dev_info(&port->serial->dev->dev, "read status %x %x\n", status_buf[0], status_buf[1]); *line_state_p = klsi_105_status2linestate(status); } kfree(status_buf); return rc; } /* * Driver's tty interface functions */ static int klsi_105_port_probe(struct usb_serial_port *port) { struct klsi_105_private *priv; priv = kmalloc(sizeof(*priv), GFP_KERNEL); if (!priv) return -ENOMEM; /* set initial values for control structures */ priv->cfg.pktlen = 5; priv->cfg.baudrate = kl5kusb105a_sio_b9600; priv->cfg.databits = kl5kusb105a_dtb_8; priv->cfg.unknown1 = 0; priv->cfg.unknown2 = 1; priv->line_state = 0; spin_lock_init(&priv->lock); /* priv->termios is left uninitialized until port opening */ usb_set_serial_port_data(port, priv); return 0; } static int klsi_105_port_remove(struct usb_serial_port *port) { struct klsi_105_private *priv; priv = usb_get_serial_port_data(port); kfree(priv); return 0; } static int klsi_105_open(struct tty_struct *tty, struct usb_serial_port *port) { struct klsi_105_private *priv = usb_get_serial_port_data(port); int retval = 0; int rc; int i; unsigned long line_state; struct klsi_105_port_settings *cfg; unsigned long flags; /* Do a defined restart: * Set up sane default baud rate and send the 'READ_ON' * vendor command. * FIXME: set modem line control (how?) * Then read the modem line control and store values in * priv->line_state. */ cfg = kmalloc(sizeof(*cfg), GFP_KERNEL); if (!cfg) return -ENOMEM; cfg->pktlen = 5; cfg->baudrate = kl5kusb105a_sio_b9600; cfg->databits = kl5kusb105a_dtb_8; cfg->unknown1 = 0; cfg->unknown2 = 1; klsi_105_chg_port_settings(port, cfg); /* set up termios structure */ spin_lock_irqsave(&priv->lock, flags); priv->termios.c_iflag = tty->termios.c_iflag; priv->termios.c_oflag = tty->termios.c_oflag; priv->termios.c_cflag = tty->termios.c_cflag; priv->termios.c_lflag = tty->termios.c_lflag; for (i = 0; i < NCCS; i++) priv->termios.c_cc[i] = tty->termios.c_cc[i]; priv->cfg.pktlen = cfg->pktlen; priv->cfg.baudrate = cfg->baudrate; priv->cfg.databits = cfg->databits; priv->cfg.unknown1 = cfg->unknown1; priv->cfg.unknown2 = cfg->unknown2; spin_unlock_irqrestore(&priv->lock, flags); /* READ_ON and urb submission */ rc = usb_serial_generic_open(tty, port); if (rc) { retval = rc; goto err_free_cfg; } rc = usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_CONFIGURE, USB_TYPE_VENDOR|USB_DIR_OUT|USB_RECIP_INTERFACE, KL5KUSB105A_SIO_CONFIGURE_READ_ON, 0, /* index */ NULL, 0, KLSI_TIMEOUT); if (rc < 0) { dev_err(&port->dev, "Enabling read failed (error = %d)\n", rc); retval = rc; goto err_generic_close; } else dev_dbg(&port->dev, "%s - enabled reading\n", __func__); rc = klsi_105_get_line_state(port, &line_state); if (rc < 0) { retval = rc; goto err_disable_read; } spin_lock_irqsave(&priv->lock, flags); priv->line_state = line_state; spin_unlock_irqrestore(&priv->lock, flags); dev_dbg(&port->dev, "%s - read line state 0x%lx\n", __func__, line_state); return 0; err_disable_read: usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_CONFIGURE, USB_TYPE_VENDOR | USB_DIR_OUT, KL5KUSB105A_SIO_CONFIGURE_READ_OFF, 0, /* index */ NULL, 0, KLSI_TIMEOUT); err_generic_close: usb_serial_generic_close(port); err_free_cfg: kfree(cfg); return retval; } static void klsi_105_close(struct usb_serial_port *port) { int rc; /* send READ_OFF */ rc = usb_control_msg(port->serial->dev, usb_sndctrlpipe(port->serial->dev, 0), KL5KUSB105A_SIO_CONFIGURE, USB_TYPE_VENDOR | USB_DIR_OUT, KL5KUSB105A_SIO_CONFIGURE_READ_OFF, 0, /* index */ NULL, 0, KLSI_TIMEOUT); if (rc < 0) dev_err(&port->dev, "failed to disable read: %d\n", rc); /* shutdown our bulk reads and writes */ usb_serial_generic_close(port); } /* We need to write a complete 64-byte data block and encode the * number actually sent in the first double-byte, LSB-order. That * leaves at most 62 bytes of payload. */ #define KLSI_HDR_LEN 2 static int klsi_105_prepare_write_buffer(struct usb_serial_port *port, void *dest, size_t size) { unsigned char *buf = dest; int count; count = kfifo_out_locked(&port->write_fifo, buf + KLSI_HDR_LEN, size, &port->lock); put_unaligned_le16(count, buf); return count + KLSI_HDR_LEN; } /* The data received is preceded by a length double-byte in LSB-first order. */ static void klsi_105_process_read_urb(struct urb *urb) { struct usb_serial_port *port = urb->context; unsigned char *data = urb->transfer_buffer; unsigned len; /* empty urbs seem to happen, we ignore them */ if (!urb->actual_length) return; if (urb->actual_length <= KLSI_HDR_LEN) { dev_dbg(&port->dev, "%s - malformed packet\n", __func__); return; } len = get_unaligned_le16(data); if (len > urb->actual_length - KLSI_HDR_LEN) { dev_dbg(&port->dev, "%s - packet length mismatch\n", __func__); len = urb->actual_length - KLSI_HDR_LEN; } tty_insert_flip_string(&port->port, data + KLSI_HDR_LEN, len); tty_flip_buffer_push(&port->port); } static void klsi_105_set_termios(struct tty_struct *tty, struct usb_serial_port *port, struct ktermios *old_termios) { struct klsi_105_private *priv = usb_get_serial_port_data(port); struct device *dev = &port->dev; unsigned int iflag = tty->termios.c_iflag; unsigned int old_iflag = old_termios->c_iflag; unsigned int cflag = tty->termios.c_cflag; unsigned int old_cflag = old_termios->c_cflag; struct klsi_105_port_settings *cfg; unsigned long flags; speed_t baud; cfg = kmalloc(sizeof(*cfg), GFP_KERNEL); if (!cfg) return; /* lock while we are modifying the settings */ spin_lock_irqsave(&priv->lock, flags); /* * Update baud rate */ baud = tty_get_baud_rate(tty); if ((cflag & CBAUD) != (old_cflag & CBAUD)) { /* reassert DTR and (maybe) RTS on transition from B0 */ if ((old_cflag & CBAUD) == B0) { dev_dbg(dev, "%s: baud was B0\n", __func__); #if 0 priv->control_state |= TIOCM_DTR; /* don't set RTS if using hardware flow control */ if (!(old_cflag & CRTSCTS)) priv->control_state |= TIOCM_RTS; mct_u232_set_modem_ctrl(serial, priv->control_state); #endif } } switch (baud) { case 0: /* handled below */ break; case 1200: priv->cfg.baudrate = kl5kusb105a_sio_b1200; break; case 2400: priv->cfg.baudrate = kl5kusb105a_sio_b2400; break; case 4800: priv->cfg.baudrate = kl5kusb105a_sio_b4800; break; case 9600: priv->cfg.baudrate = kl5kusb105a_sio_b9600; break; case 19200: priv->cfg.baudrate = kl5kusb105a_sio_b19200; break; case 38400: priv->cfg.baudrate = kl5kusb105a_sio_b38400; break; case 57600: priv->cfg.baudrate = kl5kusb105a_sio_b57600; break; case 115200: priv->cfg.baudrate = kl5kusb105a_sio_b115200; break; default: dev_dbg(dev, "unsupported baudrate, using 9600\n"); priv->cfg.baudrate = kl5kusb105a_sio_b9600; baud = 9600; break; } if ((cflag & CBAUD) == B0) { dev_dbg(dev, "%s: baud is B0\n", __func__); /* Drop RTS and DTR */ /* maybe this should be simulated by sending read * disable and read enable messages? */ #if 0 priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); mct_u232_set_modem_ctrl(serial, priv->control_state); #endif } tty_encode_baud_rate(tty, baud, baud); if ((cflag & CSIZE) != (old_cflag & CSIZE)) { /* set the number of data bits */ switch (cflag & CSIZE) { case CS5: dev_dbg(dev, "%s - 5 bits/byte not supported\n", __func__); spin_unlock_irqrestore(&priv->lock, flags); goto err; case CS6: dev_dbg(dev, "%s - 6 bits/byte not supported\n", __func__); spin_unlock_irqrestore(&priv->lock, flags); goto err; case CS7: priv->cfg.databits = kl5kusb105a_dtb_7; break; case CS8: priv->cfg.databits = kl5kusb105a_dtb_8; break; default: dev_err(dev, "CSIZE was not CS5-CS8, using default of 8\n"); priv->cfg.databits = kl5kusb105a_dtb_8; break; } } /* * Update line control register (LCR) */ if ((cflag & (PARENB|PARODD)) != (old_cflag & (PARENB|PARODD)) || (cflag & CSTOPB) != (old_cflag & CSTOPB)) { /* Not currently supported */ tty->termios.c_cflag &= ~(PARENB|PARODD|CSTOPB); #if 0 priv->last_lcr = 0; /* set the parity */ if (cflag & PARENB) priv->last_lcr |= (cflag & PARODD) ? MCT_U232_PARITY_ODD : MCT_U232_PARITY_EVEN; else priv->last_lcr |= MCT_U232_PARITY_NONE; /* set the number of stop bits */ priv->last_lcr |= (cflag & CSTOPB) ? MCT_U232_STOP_BITS_2 : MCT_U232_STOP_BITS_1; mct_u232_set_line_ctrl(serial, priv->last_lcr); #endif } /* * Set flow control: well, I do not really now how to handle DTR/RTS. * Just do what we have seen with SniffUSB on Win98. */ if ((iflag & IXOFF) != (old_iflag & IXOFF) || (iflag & IXON) != (old_iflag & IXON) || (cflag & CRTSCTS) != (old_cflag & CRTSCTS)) { /* Not currently supported */ tty->termios.c_cflag &= ~CRTSCTS; /* Drop DTR/RTS if no flow control otherwise assert */ #if 0 if ((iflag & IXOFF) || (iflag & IXON) || (cflag & CRTSCTS)) priv->control_state |= TIOCM_DTR | TIOCM_RTS; else priv->control_state &= ~(TIOCM_DTR | TIOCM_RTS); mct_u232_set_modem_ctrl(serial, priv->control_state); #endif } memcpy(cfg, &priv->cfg, sizeof(*cfg)); spin_unlock_irqrestore(&priv->lock, flags); /* now commit changes to device */ klsi_105_chg_port_settings(port, cfg); err: kfree(cfg); } #if 0 static void mct_u232_break_ctl(struct tty_struct *tty, int break_state) { struct usb_serial_port *port = tty->driver_data; struct usb_serial *serial = port->serial; struct mct_u232_private *priv = (struct mct_u232_private *)port->private; unsigned char lcr = priv->last_lcr; dev_dbg(&port->dev, "%s - state=%d\n", __func__, break_state); /* LOCKING */ if (break_state) lcr |= MCT_U232_SET_BREAK; mct_u232_set_line_ctrl(serial, lcr); } #endif static int klsi_105_tiocmget(struct tty_struct *tty) { struct usb_serial_port *port = tty->driver_data; struct klsi_105_private *priv = usb_get_serial_port_data(port); unsigned long flags; int rc; unsigned long line_state; rc = klsi_105_get_line_state(port, &line_state); if (rc < 0) { dev_err(&port->dev, "Reading line control failed (error = %d)\n", rc); /* better return value? EAGAIN? */ return rc; } spin_lock_irqsave(&priv->lock, flags); priv->line_state = line_state; spin_unlock_irqrestore(&priv->lock, flags); dev_dbg(&port->dev, "%s - read line state 0x%lx\n", __func__, line_state); return (int)line_state; } module_usb_serial_driver(serial_drivers, id_table); MODULE_AUTHOR(DRIVER_AUTHOR); MODULE_DESCRIPTION(DRIVER_DESC); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-532/c/good_3117_0
crossvul-cpp_data_bad_4043_0
/* support.c - support functions for pam_tacplus.c * * Copyright (C) 2010, Pawel Krawczyk <pawel.krawczyk@hush.com> and * Jeroen Nijhof <jeroen@jeroennijhof.nl> * * 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 2 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 - see the file COPYING. * * See `CHANGES' file for revision history. */ #define PAM_SM_AUTH #define PAM_SM_ACCOUNT #define PAM_SM_SESSION #define PAM_SM_PASSWORD #include "config.h" #include "support.h" #include "pam_tacplus.h" #ifdef HAVE_LIMITS_H #include <limits.h> #endif tacplus_server_t tac_srv[TAC_PLUS_MAXSERVERS]; unsigned int tac_srv_no = 0; char tac_service[64]; char tac_protocol[64]; char tac_prompt[64]; struct addrinfo tac_srv_addr[TAC_PLUS_MAXSERVERS]; struct sockaddr tac_sock_addr[TAC_PLUS_MAXSERVERS]; struct sockaddr_in6 tac_sock6_addr[TAC_PLUS_MAXSERVERS]; char tac_srv_key[TAC_PLUS_MAXSERVERS][TAC_SECRET_MAX_LEN+1]; void _pam_log(int err, const char *format, ...) { char msg[256]; va_list args; va_start(args, format); vsnprintf(msg, sizeof(msg), format, args); syslog(err, "PAM-tacplus: %s", msg); va_end(args); } char *_pam_get_user(pam_handle_t *pamh) { int retval; char *user; retval = pam_get_user(pamh, (void *) &user, "Username: "); if (retval != PAM_SUCCESS || user == NULL || *user == '\0') { _pam_log(LOG_ERR, "unable to obtain username"); user = NULL; } return user; } char *_pam_get_terminal(pam_handle_t *pamh) { int retval; char *tty; retval = pam_get_item(pamh, PAM_TTY, (void *) &tty); if (retval != PAM_SUCCESS || tty == NULL || *tty == '\0') { tty = ttyname(STDIN_FILENO); if (tty == NULL || *tty == '\0') tty = "unknown"; } return tty; } char *_pam_get_rhost(pam_handle_t *pamh) { int retval; char *rhost; retval = pam_get_item(pamh, PAM_RHOST, (void *) &rhost); if (retval != PAM_SUCCESS || rhost == NULL || *rhost == '\0') { rhost = "unknown"; } return rhost; } int converse(pam_handle_t *pamh, int nargs, const struct pam_message *message, struct pam_response **response) { int retval; struct pam_conv *conv; if ((retval = pam_get_item(pamh, PAM_CONV, (const void **) &conv)) == PAM_SUCCESS) { retval = conv->conv(nargs, &message, response, conv->appdata_ptr); if (retval != PAM_SUCCESS) { _pam_log(LOG_ERR, "(pam_tacplus) converse returned %d", retval); _pam_log(LOG_ERR, "that is: %s", pam_strerror(pamh, retval)); } } else { _pam_log(LOG_ERR, "(pam_tacplus) converse failed to get pam_conv"); } return retval; } /* stolen from pam_stress */ int tacacs_get_password(pam_handle_t *pamh, int flags __Unused, int ctrl, char **password) { (void) flags; const void *pam_pass; char *pass = NULL; if (ctrl & PAM_TAC_DEBUG) syslog(LOG_DEBUG, "%s: called", __FUNCTION__); if ((ctrl & (PAM_TAC_TRY_FIRST_PASS | PAM_TAC_USE_FIRST_PASS)) && (pam_get_item(pamh, PAM_AUTHTOK, &pam_pass) == PAM_SUCCESS) && (pam_pass != NULL)) { if ((pass = strdup(pam_pass)) == NULL) return PAM_BUF_ERR; } else if ((ctrl & PAM_TAC_USE_FIRST_PASS)) { _pam_log(LOG_WARNING, "no forwarded password"); return PAM_PERM_DENIED; } else { struct pam_message msg; struct pam_response *resp = NULL; int retval; /* set up conversation call */ msg.msg_style = PAM_PROMPT_ECHO_OFF; if (!tac_prompt[0]) { msg.msg = "Password: "; } else { msg.msg = tac_prompt; } if ((retval = converse(pamh, 1, &msg, &resp)) != PAM_SUCCESS) return retval; if (resp != NULL) { if (resp->resp == NULL && (ctrl & PAM_TAC_DEBUG)) _pam_log(LOG_DEBUG, "pam_sm_authenticate: NULL authtok given"); pass = resp->resp; /* remember this! */ resp->resp = NULL; free(resp); resp = NULL; } else { if (ctrl & PAM_TAC_DEBUG) { _pam_log(LOG_DEBUG, "pam_sm_authenticate: no error reported"); _pam_log(LOG_DEBUG, "getting password, but NULL returned!?"); } return PAM_CONV_ERR; } } /* FIXME *password can still turn out as NULL and it can't be free()d when it's NULL */ *password = pass; /* this *MUST* be free()'d by this module */ if (ctrl & PAM_TAC_DEBUG) syslog(LOG_DEBUG, "%s: obtained password", __FUNCTION__); return PAM_SUCCESS; } void tac_copy_addr_info(struct addrinfo *p_dst, const struct addrinfo *p_src) { if (p_dst && p_src) { p_dst->ai_flags = p_src->ai_flags; p_dst->ai_family = p_src->ai_family; p_dst->ai_socktype = p_src->ai_socktype; p_dst->ai_protocol = p_src->ai_protocol; p_dst->ai_addrlen = p_src->ai_addrlen; /* ipv6 check */ if (p_dst->ai_family == AF_INET6) { memcpy (p_dst->ai_addr, p_src->ai_addr, sizeof(struct sockaddr_in6)); memset ((struct sockaddr_in6*)p_dst->ai_addr, 0 , sizeof(struct sockaddr_in6)); memcpy ((struct sockaddr_in6*)p_dst->ai_addr, (struct sockaddr_in6*)p_src->ai_addr, sizeof(struct sockaddr_in6)); } else { memcpy (p_dst->ai_addr, p_src->ai_addr, sizeof(struct sockaddr)); } p_dst->ai_canonname = NULL; /* we do not care it */ p_dst->ai_next = NULL; /* no more chain */ } } static void set_tac_srv_addr (unsigned int srv_no, const struct addrinfo *addr) { _pam_log(LOG_DEBUG, "%s: server [%s]", __FUNCTION__, tac_ntop(addr->ai_addr)); if (srv_no < TAC_PLUS_MAXSERVERS) { if (addr) { if (addr->ai_family == AF_INET6) { tac_srv_addr[srv_no].ai_addr = (struct sockaddr *)&tac_sock6_addr[srv_no]; } else { tac_srv_addr[srv_no].ai_addr = &tac_sock_addr[srv_no]; } tac_copy_addr_info (&tac_srv_addr[srv_no], addr); tac_srv[srv_no].addr = &tac_srv_addr[srv_no]; /*this code will copy the ipv6 address to a temp variable */ /*and copies to global tac_srv array*/ if (addr->ai_family == AF_INET6) { memset (&tac_sock6_addr[srv_no], 0, sizeof(struct sockaddr_in6)); memcpy (&tac_sock6_addr[srv_no], (struct sockaddr_in6*)addr->ai_addr, sizeof(struct sockaddr_in6)); tac_srv[srv_no].addr->ai_addr = (struct sockaddr *)&tac_sock6_addr[srv_no]; } _pam_log(LOG_DEBUG, "%s: server %d after copy [%s]", __FUNCTION__, srv_no, tac_ntop(tac_srv[srv_no].addr->ai_addr)); } else { tac_srv[srv_no].addr = NULL; } } } static void set_tac_srv_key(unsigned int srv_no, const char *key) { if (srv_no < TAC_PLUS_MAXSERVERS) { if (key) { strncpy(tac_srv_key[srv_no], key, TAC_SECRET_MAX_LEN - 1); tac_srv[srv_no].key = tac_srv_key[srv_no]; } else { _pam_log(LOG_DEBUG, "%s: server %d key is null; address [%s]", __FUNCTION__,srv_no, tac_ntop(tac_srv[srv_no].addr->ai_addr)); tac_srv[srv_no].key = NULL; } } } int _pam_parse(int argc, const char **argv) { int ctrl = 0; const char *current_secret = NULL; /* otherwise the list will grow with each call */ memset(tac_srv, 0, sizeof(tacplus_server_t) * TAC_PLUS_MAXSERVERS); memset(&tac_srv_addr, 0, sizeof(struct addrinfo) * TAC_PLUS_MAXSERVERS); memset(&tac_sock_addr, 0, sizeof(struct sockaddr) * TAC_PLUS_MAXSERVERS); memset(&tac_sock6_addr, 0, sizeof(struct sockaddr_in6) * TAC_PLUS_MAXSERVERS); tac_srv_no = 0; tac_service[0] = 0; tac_protocol[0] = 0; tac_prompt[0] = 0; tac_login[0] = 0; for (ctrl = 0; argc-- > 0; ++argv) { if (!strcmp(*argv, "debug")) { /* all */ ctrl |= PAM_TAC_DEBUG; } else if (!strcmp(*argv, "use_first_pass")) { ctrl |= PAM_TAC_USE_FIRST_PASS; } else if (!strcmp(*argv, "try_first_pass")) { ctrl |= PAM_TAC_TRY_FIRST_PASS; } else if (!strncmp(*argv, "service=", 8)) { /* author & acct */ xstrcpy(tac_service, *argv + 8, sizeof(tac_service)); } else if (!strncmp(*argv, "protocol=", 9)) { /* author & acct */ xstrcpy(tac_protocol, *argv + 9, sizeof(tac_protocol)); } else if (!strncmp(*argv, "prompt=", 7)) { /* authentication */ xstrcpy(tac_prompt, *argv + 7, sizeof(tac_prompt)); /* Replace _ with space */ unsigned long chr; for (chr = 0; chr < strlen(tac_prompt); chr++) { if (tac_prompt[chr] == '_') { tac_prompt[chr] = ' '; } } } else if (!strncmp(*argv, "login=", 6)) { xstrcpy(tac_login, *argv + 6, sizeof(tac_login)); } else if (!strcmp(*argv, "acct_all")) { ctrl |= PAM_TAC_ACCT; } else if (!strncmp(*argv, "server=", 7)) { /* authen & acct */ if (tac_srv_no < TAC_PLUS_MAXSERVERS) { struct addrinfo hints, *servers, *server; int rv; char *close_bracket, *server_name, *port, server_buf[256]; memset(&hints, 0, sizeof hints); memset(&server_buf, 0, sizeof(server_buf)); hints.ai_family = AF_UNSPEC; /* use IPv4 or IPv6, whichever */ hints.ai_socktype = SOCK_STREAM; if (strlen(*argv + 7) >= sizeof(server_buf)) { _pam_log(LOG_ERR, "server address too long, sorry"); continue; } strcpy(server_buf, *argv + 7); if (*server_buf == '[' && (close_bracket = strchr(server_buf, ']')) != NULL) { /* Check for URI syntax */ server_name = server_buf + 1; _pam_log (LOG_ERR, "reading server address as: %s ", server_name); port = strchr(close_bracket, ':'); *close_bracket = '\0'; } else { /* Fall back to traditional syntax */ server_name = server_buf; port = strchr(server_buf, ':'); } if (port != NULL) { *port = '\0'; port++; } _pam_log (LOG_DEBUG, "sending server address to getaddrinfo as: %s ", server_name); if ((rv = getaddrinfo(server_name, (port == NULL) ? "49" : port, &hints, &servers)) == 0) { for (server = servers; server != NULL && tac_srv_no < TAC_PLUS_MAXSERVERS; server = server->ai_next) { set_tac_srv_addr(tac_srv_no, server); set_tac_srv_key(tac_srv_no, current_secret); tac_srv_no++; } _pam_log(LOG_DEBUG, "%s: server index %d ", __FUNCTION__, tac_srv_no); freeaddrinfo (servers); } else { _pam_log(LOG_ERR, "skip invalid server: %s (getaddrinfo: %s)", server_name, gai_strerror(rv)); } } else { _pam_log(LOG_ERR, "maximum number of servers (%d) exceeded, skipping", TAC_PLUS_MAXSERVERS); } } else if (!strncmp(*argv, "secret=", 7)) { current_secret = *argv + 7; /* points right into argv (which is const) */ // this is possible because server structure is initialized only on the server= occurence if (tac_srv_no == 0) { _pam_log(LOG_ERR, "secret set but no servers configured yet"); } else { // set secret for the last server configured set_tac_srv_key(tac_srv_no - 1, current_secret); } } else if (!strncmp(*argv, "timeout=", 8)) { #ifdef HAVE_STRTOL tac_timeout = strtol(*argv + 8, NULL, 10); #else tac_timeout = atoi(*argv + 8); #endif if (tac_timeout == LONG_MAX) { _pam_log(LOG_ERR, "timeout parameter cannot be parsed as integer: %s", *argv); tac_timeout = 0; } else { tac_readtimeout_enable = 1; } } else { _pam_log(LOG_WARNING, "unrecognized option: %s", *argv); } } if (ctrl & PAM_TAC_DEBUG) { unsigned long n; _pam_log(LOG_DEBUG, "%d servers defined", tac_srv_no); for (n = 0; n < tac_srv_no; n++) { _pam_log(LOG_DEBUG, "server[%lu] { addr=%s, key='%s' }", n, tac_ntop(tac_srv[n].addr->ai_addr), tac_srv[n].key); } _pam_log(LOG_DEBUG, "tac_service='%s'", tac_service); _pam_log(LOG_DEBUG, "tac_protocol='%s'", tac_protocol); _pam_log(LOG_DEBUG, "tac_prompt='%s'", tac_prompt); _pam_log(LOG_DEBUG, "tac_login='%s'", tac_login); } return ctrl; } /* _pam_parse */
./CrossVul/dataset_final_sorted/CWE-532/c/bad_4043_0
crossvul-cpp_data_good_2780_0
/* * NSV demuxer * Copyright (c) 2004 The FFmpeg Project * * first version by Francois Revol <revol@free.fr> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/attributes.h" #include "libavutil/mathematics.h" #include "avformat.h" #include "internal.h" #include "libavutil/dict.h" #include "libavutil/intreadwrite.h" /* max bytes to crawl for trying to resync * stupid streaming servers don't start at chunk boundaries... */ #define NSV_MAX_RESYNC (500*1024) #define NSV_MAX_RESYNC_TRIES 300 /* * References: * (1) http://www.multimedia.cx/nsv-format.txt * seems someone came to the same conclusions as me, and updated it: * (2) http://www.stud.ktu.lt/~vitslav/nsv/nsv-format.txt * http://www.stud.ktu.lt/~vitslav/nsv/ * official docs * (3) http://ultravox.aol.com/NSVFormat.rtf * Sample files: * (S1) http://www.nullsoft.com/nsv/samples/ * http://www.nullsoft.com/nsv/samples/faster.nsv * http://streamripper.sourceforge.net/openbb/read.php?TID=492&page=4 */ /* * notes on the header (Francois Revol): * * It is followed by strings, then a table, but nothing tells * where the table begins according to (1). After checking faster.nsv, * I believe NVSf[16-19] gives the size of the strings data * (that is the offset of the data table after the header). * After checking all samples from (S1) all confirms this. * * Then, about NSVf[12-15], faster.nsf has 179700. When viewing it in VLC, * I noticed there was about 1 NVSs chunk/s, so I ran * strings faster.nsv | grep NSVs | wc -l * which gave me 180. That leads me to think that NSVf[12-15] might be the * file length in milliseconds. * Let's try that: * for f in *.nsv; do HTIME="$(od -t x4 "$f" | head -1 | sed 's/.* //')"; echo "'$f' $((0x$HTIME))s = $((0x$HTIME/1000/60)):$((0x$HTIME/1000%60))"; done * except for nsvtrailer (which doesn't have an NSVf header), it reports correct time. * * nsvtrailer.nsv (S1) does not have any NSVf header, only NSVs chunks, * so the header seems to not be mandatory. (for streaming). * * index slice duration check (excepts nsvtrailer.nsv): * for f in [^n]*.nsv; do DUR="$(ffmpeg -i "$f" 2>/dev/null | grep 'NSVf duration' | cut -d ' ' -f 4)"; IC="$(ffmpeg -i "$f" 2>/dev/null | grep 'INDEX ENTRIES' | cut -d ' ' -f 2)"; echo "duration $DUR, slite time $(($DUR/$IC))"; done */ /* * TODO: * - handle timestamps !!! * - use index * - mime-type in probe() * - seek */ #if 0 struct NSVf_header { uint32_t chunk_tag; /* 'NSVf' */ uint32_t chunk_size; uint32_t file_size; /* max 4GB ??? no one learns anything it seems :^) */ uint32_t file_length; //unknown1; /* what about MSB of file_size ? */ uint32_t info_strings_size; /* size of the info strings */ //unknown2; uint32_t table_entries; uint32_t table_entries_used; /* the left ones should be -1 */ }; struct NSVs_header { uint32_t chunk_tag; /* 'NSVs' */ uint32_t v4cc; /* or 'NONE' */ uint32_t a4cc; /* or 'NONE' */ uint16_t vwidth; /* av_assert0(vwidth%16==0) */ uint16_t vheight; /* av_assert0(vheight%16==0) */ uint8_t framerate; /* value = (framerate&0x80)?frtable[frameratex0x7f]:framerate */ uint16_t unknown; }; struct nsv_avchunk_header { uint8_t vchunk_size_lsb; uint16_t vchunk_size_msb; /* value = (vchunk_size_msb << 4) | (vchunk_size_lsb >> 4) */ uint16_t achunk_size; }; struct nsv_pcm_header { uint8_t bits_per_sample; uint8_t channel_count; uint16_t sample_rate; }; #endif /* variation from avi.h */ /*typedef struct CodecTag { int id; unsigned int tag; } CodecTag;*/ /* tags */ #define T_NSVF MKTAG('N', 'S', 'V', 'f') /* file header */ #define T_NSVS MKTAG('N', 'S', 'V', 's') /* chunk header */ #define T_TOC2 MKTAG('T', 'O', 'C', '2') /* extra index marker */ #define T_NONE MKTAG('N', 'O', 'N', 'E') /* null a/v 4CC */ #define T_SUBT MKTAG('S', 'U', 'B', 'T') /* subtitle aux data */ #define T_ASYN MKTAG('A', 'S', 'Y', 'N') /* async a/v aux marker */ #define T_KEYF MKTAG('K', 'E', 'Y', 'F') /* video keyframe aux marker (addition) */ #define TB_NSVF MKBETAG('N', 'S', 'V', 'f') #define TB_NSVS MKBETAG('N', 'S', 'V', 's') /* hardcoded stream indexes */ #define NSV_ST_VIDEO 0 #define NSV_ST_AUDIO 1 #define NSV_ST_SUBT 2 enum NSVStatus { NSV_UNSYNC, NSV_FOUND_NSVF, NSV_HAS_READ_NSVF, NSV_FOUND_NSVS, NSV_HAS_READ_NSVS, NSV_FOUND_BEEF, NSV_GOT_VIDEO, NSV_GOT_AUDIO, }; typedef struct NSVStream { int frame_offset; /* current frame (video) or byte (audio) counter (used to compute the pts) */ int scale; int rate; int sample_size; /* audio only data */ int start; int new_frame_offset; /* temporary storage (used during seek) */ int cum_len; /* temporary storage (used during seek) */ } NSVStream; typedef struct NSVContext { int base_offset; int NSVf_end; uint32_t *nsvs_file_offset; int index_entries; enum NSVStatus state; AVPacket ahead[2]; /* [v, a] if .data is !NULL there is something */ /* cached */ int64_t duration; uint32_t vtag, atag; uint16_t vwidth, vheight; int16_t avsync; AVRational framerate; uint32_t *nsvs_timestamps; } NSVContext; static const AVCodecTag nsv_codec_video_tags[] = { { AV_CODEC_ID_VP3, MKTAG('V', 'P', '3', ' ') }, { AV_CODEC_ID_VP3, MKTAG('V', 'P', '3', '0') }, { AV_CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, { AV_CODEC_ID_VP5, MKTAG('V', 'P', '5', ' ') }, { AV_CODEC_ID_VP5, MKTAG('V', 'P', '5', '0') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', ' ') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', '0') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', '1') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', '2') }, { AV_CODEC_ID_VP8, MKTAG('V', 'P', '8', '0') }, /* { AV_CODEC_ID_VP4, MKTAG('V', 'P', '4', ' ') }, { AV_CODEC_ID_VP4, MKTAG('V', 'P', '4', '0') }, */ { AV_CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') }, /* cf sample xvid decoder from nsv_codec_sdk.zip */ { AV_CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', '3') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag nsv_codec_audio_tags[] = { { AV_CODEC_ID_MP3, MKTAG('M', 'P', '3', ' ') }, { AV_CODEC_ID_AAC, MKTAG('A', 'A', 'C', ' ') }, { AV_CODEC_ID_AAC, MKTAG('A', 'A', 'C', 'P') }, { AV_CODEC_ID_AAC, MKTAG('V', 'L', 'B', ' ') }, { AV_CODEC_ID_SPEEX, MKTAG('S', 'P', 'X', ' ') }, { AV_CODEC_ID_PCM_U16LE, MKTAG('P', 'C', 'M', ' ') }, { AV_CODEC_ID_NONE, 0 }, }; //static int nsv_load_index(AVFormatContext *s); static int nsv_read_chunk(AVFormatContext *s, int fill_header); /* try to find something we recognize, and set the state accordingly */ static int nsv_resync(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; uint32_t v = 0; int i; for (i = 0; i < NSV_MAX_RESYNC; i++) { if (avio_feof(pb)) { av_log(s, AV_LOG_TRACE, "NSV EOF\n"); nsv->state = NSV_UNSYNC; return -1; } v <<= 8; v |= avio_r8(pb); if (i < 8) { av_log(s, AV_LOG_TRACE, "NSV resync: [%d] = %02"PRIx32"\n", i, v & 0x0FF); } if ((v & 0x0000ffff) == 0xefbe) { /* BEEF */ av_log(s, AV_LOG_TRACE, "NSV resynced on BEEF after %d bytes\n", i+1); nsv->state = NSV_FOUND_BEEF; return 0; } /* we read as big-endian, thus the MK*BE* */ if (v == TB_NSVF) { /* NSVf */ av_log(s, AV_LOG_TRACE, "NSV resynced on NSVf after %d bytes\n", i+1); nsv->state = NSV_FOUND_NSVF; return 0; } if (v == MKBETAG('N', 'S', 'V', 's')) { /* NSVs */ av_log(s, AV_LOG_TRACE, "NSV resynced on NSVs after %d bytes\n", i+1); nsv->state = NSV_FOUND_NSVS; return 0; } } av_log(s, AV_LOG_TRACE, "NSV sync lost\n"); return -1; } static int nsv_parse_NSVf_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; unsigned int av_unused file_size; unsigned int size; int64_t duration; int strings_size; int table_entries; int table_entries_used; nsv->state = NSV_UNSYNC; /* in case we fail */ size = avio_rl32(pb); if (size < 28) return -1; nsv->NSVf_end = size; file_size = (uint32_t)avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size); av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size); nsv->duration = duration = avio_rl32(pb); /* in ms */ av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration); // XXX: store it in AVStreams strings_size = avio_rl32(pb); table_entries = avio_rl32(pb); table_entries_used = avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n", strings_size, table_entries, table_entries_used); if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb)); if (strings_size > 0) { char *strings; /* last byte will be '\0' to play safe with str*() */ char *p, *endp; char *token, *value; char quote; p = strings = av_mallocz((size_t)strings_size + 1); if (!p) return AVERROR(ENOMEM); endp = strings + strings_size; avio_read(pb, strings, strings_size); while (p < endp) { while (*p == ' ') p++; /* strip out spaces */ if (p >= endp-2) break; token = p; p = strchr(p, '='); if (!p || p >= endp-2) break; *p++ = '\0'; quote = *p++; value = p; p = strchr(p, quote); if (!p || p >= endp) break; *p++ = '\0'; av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value); av_dict_set(&s->metadata, token, value, 0); } av_free(strings); } if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb)); if (table_entries_used > 0) { int i; nsv->index_entries = table_entries_used; if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t)) return -1; nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_file_offset) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; nsv->nsvs_file_offset[i] = avio_rl32(pb) + size; } if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_timestamps) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { nsv->nsvs_timestamps[i] = avio_rl32(pb); } } } av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb)); avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */ if (avio_feof(pb)) return -1; nsv->state = NSV_HAS_READ_NSVF; return 0; } static int nsv_parse_NSVs_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; uint32_t vtag, atag; uint16_t vwidth, vheight; AVRational framerate; int i; AVStream *st; NSVStream *nst; vtag = avio_rl32(pb); atag = avio_rl32(pb); vwidth = avio_rl16(pb); vheight = avio_rl16(pb); i = avio_r8(pb); av_log(s, AV_LOG_TRACE, "NSV NSVs framerate code %2x\n", i); if(i&0x80) { /* odd way of giving native framerates from docs */ int t=(i & 0x7F)>>2; if(t<16) framerate = (AVRational){1, t+1}; else framerate = (AVRational){t-15, 1}; if(i&1){ framerate.num *= 1000; framerate.den *= 1001; } if((i&3)==3) framerate.num *= 24; else if((i&3)==2) framerate.num *= 25; else framerate.num *= 30; } else framerate= (AVRational){i, 1}; nsv->avsync = avio_rl16(pb); nsv->framerate = framerate; av_log(s, AV_LOG_TRACE, "NSV NSVs vsize %dx%d\n", vwidth, vheight); /* XXX change to ap != NULL ? */ if (s->nb_streams == 0) { /* streams not yet published, let's do that */ nsv->vtag = vtag; nsv->atag = atag; nsv->vwidth = vwidth; nsv->vheight = vwidth; if (vtag != T_NONE) { int i; st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = NSV_ST_VIDEO; nst = av_mallocz(sizeof(NSVStream)); if (!nst) goto fail; st->priv_data = nst; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_tag = vtag; st->codecpar->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag); st->codecpar->width = vwidth; st->codecpar->height = vheight; st->codecpar->bits_per_coded_sample = 24; /* depth XXX */ avpriv_set_pts_info(st, 64, framerate.den, framerate.num); st->start_time = 0; st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den); for(i=0;i<nsv->index_entries;i++) { if(nsv->nsvs_timestamps) { av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i], 0, 0, AVINDEX_KEYFRAME); } else { int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den); av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME); } } } if (atag != T_NONE) { st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = NSV_ST_AUDIO; nst = av_mallocz(sizeof(NSVStream)); if (!nst) goto fail; st->priv_data = nst; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_tag = atag; st->codecpar->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag); st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */ /* set timebase to common denominator of ms and framerate */ avpriv_set_pts_info(st, 64, 1, framerate.num*1000); st->start_time = 0; st->duration = (int64_t)nsv->duration * framerate.num; } } else { if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) { av_log(s, AV_LOG_TRACE, "NSV NSVs header values differ from the first one!!!\n"); //return -1; } } nsv->state = NSV_HAS_READ_NSVS; return 0; fail: /* XXX */ nsv->state = NSV_UNSYNC; return -1; } static int nsv_read_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; int i, err; nsv->state = NSV_UNSYNC; nsv->ahead[0].data = nsv->ahead[1].data = NULL; for (i = 0; i < NSV_MAX_RESYNC_TRIES; i++) { if (nsv_resync(s) < 0) return -1; if (nsv->state == NSV_FOUND_NSVF) { err = nsv_parse_NSVf_header(s); if (err < 0) return err; } /* we need the first NSVs also... */ if (nsv->state == NSV_FOUND_NSVS) { err = nsv_parse_NSVs_header(s); if (err < 0) return err; break; /* we just want the first one */ } } if (s->nb_streams < 1) /* no luck so far */ return -1; /* now read the first chunk, so we can attempt to decode more info */ err = nsv_read_chunk(s, 1); av_log(s, AV_LOG_TRACE, "parsed header\n"); return err; } static int nsv_read_chunk(AVFormatContext *s, int fill_header) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; AVStream *st[2] = {NULL, NULL}; NSVStream *nst; AVPacket *pkt; int i, err = 0; uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */ uint32_t vsize; uint16_t asize; uint16_t auxsize; int ret; if (nsv->ahead[0].data || nsv->ahead[1].data) return 0; //-1; /* hey! eat what you've in your plate first! */ null_chunk_retry: if (avio_feof(pb)) return -1; for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++) err = nsv_resync(s); if (err < 0) return err; if (nsv->state == NSV_FOUND_NSVS) err = nsv_parse_NSVs_header(s); if (err < 0) return err; if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF) return -1; auxcount = avio_r8(pb); vsize = avio_rl16(pb); asize = avio_rl16(pb); vsize = (vsize << 4) | (auxcount >> 4); auxcount &= 0x0f; av_log(s, AV_LOG_TRACE, "NSV CHUNK %d aux, %"PRIu32" bytes video, %d bytes audio\n", auxcount, vsize, asize); /* skip aux stuff */ for (i = 0; i < auxcount; i++) { uint32_t av_unused auxtag; auxsize = avio_rl16(pb); auxtag = avio_rl32(pb); avio_skip(pb, auxsize); vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */ } if (avio_feof(pb)) return -1; if (!vsize && !asize) { nsv->state = NSV_UNSYNC; goto null_chunk_retry; } /* map back streams to v,a */ if (s->nb_streams > 0) st[s->streams[0]->id] = s->streams[0]; if (s->nb_streams > 1) st[s->streams[1]->id] = s->streams[1]; if (vsize && st[NSV_ST_VIDEO]) { nst = st[NSV_ST_VIDEO]->priv_data; pkt = &nsv->ahead[NSV_ST_VIDEO]; if ((ret = av_get_packet(pb, pkt, vsize)) < 0) return ret; pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO; pkt->dts = nst->frame_offset; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ for (i = 0; i < FFMIN(8, vsize); i++) av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02x\n", i, pkt->data[i]); } if(st[NSV_ST_VIDEO]) ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++; if (asize && st[NSV_ST_AUDIO]) { nst = st[NSV_ST_AUDIO]->priv_data; pkt = &nsv->ahead[NSV_ST_AUDIO]; /* read raw audio specific header on the first audio chunk... */ /* on ALL audio chunks ?? seems so! */ if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) { uint8_t bps; uint8_t channels; uint16_t samplerate; bps = avio_r8(pb); channels = avio_r8(pb); samplerate = avio_rl16(pb); if (!channels || !samplerate) return AVERROR_INVALIDDATA; asize-=4; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate); if (fill_header) { st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */ if (bps != 16) { av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%d)!!!\n", bps); } bps /= channels; // ??? if (bps == 8) st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8; samplerate /= 4;/* UGH ??? XXX */ channels = 1; st[NSV_ST_AUDIO]->codecpar->channels = channels; st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate); } } if ((ret = av_get_packet(pb, pkt, asize)) < 0) return ret; pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) { /* on a nsvs frame we have new information on a/v sync */ pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1); pkt->dts *= (int64_t)1000 * nsv->framerate.den; pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num; av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%d, dts:%"PRId64, nsv->avsync, pkt->dts); } nst->frame_offset++; } nsv->state = NSV_UNSYNC; return 0; } static int nsv_read_packet(AVFormatContext *s, AVPacket *pkt) { NSVContext *nsv = s->priv_data; int i, err = 0; /* in case we don't already have something to eat ... */ if (!nsv->ahead[0].data && !nsv->ahead[1].data) err = nsv_read_chunk(s, 0); if (err < 0) return err; /* now pick one of the plates */ for (i = 0; i < 2; i++) { if (nsv->ahead[i].data) { /* avoid the cost of new_packet + memcpy(->data) */ memcpy(pkt, &nsv->ahead[i], sizeof(AVPacket)); nsv->ahead[i].data = NULL; /* we ate that one */ return pkt->size; } } /* this restaurant is not provisioned :^] */ return -1; } static int nsv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { NSVContext *nsv = s->priv_data; AVStream *st = s->streams[stream_index]; NSVStream *nst = st->priv_data; int index; index = av_index_search_timestamp(st, timestamp, flags); if(index < 0) return -1; if (avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET) < 0) return -1; nst->frame_offset = st->index_entries[index].timestamp; nsv->state = NSV_UNSYNC; return 0; } static int nsv_read_close(AVFormatContext *s) { NSVContext *nsv = s->priv_data; av_freep(&nsv->nsvs_file_offset); av_freep(&nsv->nsvs_timestamps); if (nsv->ahead[0].data) av_packet_unref(&nsv->ahead[0]); if (nsv->ahead[1].data) av_packet_unref(&nsv->ahead[1]); return 0; } static int nsv_probe(AVProbeData *p) { int i, score = 0; /* check file header */ /* streamed files might not have any header */ if (p->buf[0] == 'N' && p->buf[1] == 'S' && p->buf[2] == 'V' && (p->buf[3] == 'f' || p->buf[3] == 's')) return AVPROBE_SCORE_MAX; /* XXX: do streamed files always start at chunk boundary ?? */ /* or do we need to search NSVs in the byte stream ? */ /* seems the servers don't bother starting clean chunks... */ /* sometimes even the first header is at 9KB or something :^) */ for (i = 1; i < p->buf_size - 3; i++) { if (AV_RL32(p->buf + i) == AV_RL32("NSVs")) { /* Get the chunk size and check if at the end we are getting 0xBEEF */ int vsize = AV_RL24(p->buf+i+19) >> 4; int asize = AV_RL16(p->buf+i+22); int offset = i + 23 + asize + vsize + 1; if (offset <= p->buf_size - 2 && AV_RL16(p->buf + offset) == 0xBEEF) return 4*AVPROBE_SCORE_MAX/5; score = AVPROBE_SCORE_MAX/5; } } /* so we'll have more luck on extension... */ if (av_match_ext(p->filename, "nsv")) return AVPROBE_SCORE_EXTENSION; /* FIXME: add mime-type check */ return score; } AVInputFormat ff_nsv_demuxer = { .name = "nsv", .long_name = NULL_IF_CONFIG_SMALL("Nullsoft Streaming Video"), .priv_data_size = sizeof(NSVContext), .read_probe = nsv_probe, .read_header = nsv_read_header, .read_packet = nsv_read_packet, .read_close = nsv_read_close, .read_seek = nsv_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2780_0
crossvul-cpp_data_bad_2761_0
/* * "Real" compatible demuxer. * Copyright (c) 2000, 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/channel_layout.h" #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #include "libavutil/dict.h" #include "avformat.h" #include "avio_internal.h" #include "internal.h" #include "rmsipr.h" #include "rm.h" #define DEINT_ID_GENR MKTAG('g', 'e', 'n', 'r') ///< interleaving for Cooker/ATRAC #define DEINT_ID_INT0 MKTAG('I', 'n', 't', '0') ///< no interleaving needed #define DEINT_ID_INT4 MKTAG('I', 'n', 't', '4') ///< interleaving for 28.8 #define DEINT_ID_SIPR MKTAG('s', 'i', 'p', 'r') ///< interleaving for Sipro #define DEINT_ID_VBRF MKTAG('v', 'b', 'r', 'f') ///< VBR case for AAC #define DEINT_ID_VBRS MKTAG('v', 'b', 'r', 's') ///< VBR case for AAC struct RMStream { AVPacket pkt; ///< place to store merged video frame / reordered audio data int videobufsize; ///< current assembled frame size int videobufpos; ///< position for the next slice in the video buffer int curpic_num; ///< picture number of current frame int cur_slice, slices; int64_t pktpos; ///< first slice position in file /// Audio descrambling matrix parameters int64_t audiotimestamp; ///< Audio packet timestamp int sub_packet_cnt; // Subpacket counter, used while reading int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container int audio_framesize; /// Audio frame size from container int sub_packet_lengths[16]; /// Length of each subpacket int32_t deint_id; ///< deinterleaver used in audio stream }; typedef struct RMDemuxContext { int nb_packets; int old_format; int current_stream; int remaining_len; int audio_stream_num; ///< Stream number for audio packets int audio_pkt_cnt; ///< Output packet counter int data_end; } RMDemuxContext; static int rm_read_close(AVFormatContext *s); static inline void get_strl(AVIOContext *pb, char *buf, int buf_size, int len) { int i; char *q, r; q = buf; for(i=0;i<len;i++) { r = avio_r8(pb); if (i < buf_size - 1) *q++ = r; } if (buf_size > 0) *q = '\0'; } static void get_str8(AVIOContext *pb, char *buf, int buf_size) { get_strl(pb, buf, buf_size, avio_r8(pb)); } static int rm_read_extradata(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, unsigned size) { if (size >= 1<<24) { av_log(s, AV_LOG_ERROR, "extradata size %u too large\n", size); return -1; } if (ff_get_extradata(s, par, pb, size) < 0) return AVERROR(ENOMEM); return 0; } static void rm_read_metadata(AVFormatContext *s, AVIOContext *pb, int wide) { char buf[1024]; int i; for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) { int len = wide ? avio_rb16(pb) : avio_r8(pb); get_strl(pb, buf, sizeof(buf), len); av_dict_set(&s->metadata, ff_rm_metadata[i], buf, 0); } } RMStream *ff_rm_alloc_rmstream (void) { RMStream *rms = av_mallocz(sizeof(RMStream)); if (!rms) return NULL; rms->curpic_num = -1; return rms; } void ff_rm_free_rmstream (RMStream *rms) { av_packet_unref(&rms->pkt); } static int rm_read_audio_stream_info(AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *ast, int read_all) { char buf[256]; uint32_t version; int ret; /* ra type header */ version = avio_rb16(pb); /* version */ if (version == 3) { unsigned bytes_per_minute; int header_size = avio_rb16(pb); int64_t startpos = avio_tell(pb); avio_skip(pb, 8); bytes_per_minute = avio_rb16(pb); avio_skip(pb, 4); rm_read_metadata(s, pb, 0); if ((startpos + header_size) >= avio_tell(pb) + 2) { // fourcc (should always be "lpcJ") avio_r8(pb); get_str8(pb, buf, sizeof(buf)); } // Skip extra header crap (this should never happen) if ((startpos + header_size) > avio_tell(pb)) avio_skip(pb, header_size + startpos - avio_tell(pb)); if (bytes_per_minute) st->codecpar->bit_rate = 8LL * bytes_per_minute / 60; st->codecpar->sample_rate = 8000; st->codecpar->channels = 1; st->codecpar->channel_layout = AV_CH_LAYOUT_MONO; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_RA_144; ast->deint_id = DEINT_ID_INT0; } else { int flavor, sub_packet_h, coded_framesize, sub_packet_size; int codecdata_length; unsigned bytes_per_minute; /* old version (4) */ avio_skip(pb, 2); /* unused */ avio_rb32(pb); /* .ra4 */ avio_rb32(pb); /* data size */ avio_rb16(pb); /* version2 */ avio_rb32(pb); /* header size */ flavor= avio_rb16(pb); /* add codec info / flavor */ ast->coded_framesize = coded_framesize = avio_rb32(pb); /* coded frame size */ avio_rb32(pb); /* ??? */ bytes_per_minute = avio_rb32(pb); if (version == 4) { if (bytes_per_minute) st->codecpar->bit_rate = 8LL * bytes_per_minute / 60; } avio_rb32(pb); /* ??? */ ast->sub_packet_h = sub_packet_h = avio_rb16(pb); /* 1 */ st->codecpar->block_align= avio_rb16(pb); /* frame size */ ast->sub_packet_size = sub_packet_size = avio_rb16(pb); /* sub packet size */ avio_rb16(pb); /* ??? */ if (version == 5) { avio_rb16(pb); avio_rb16(pb); avio_rb16(pb); } st->codecpar->sample_rate = avio_rb16(pb); avio_rb32(pb); st->codecpar->channels = avio_rb16(pb); if (version == 5) { ast->deint_id = avio_rl32(pb); avio_read(pb, buf, 4); buf[4] = 0; } else { AV_WL32(buf, 0); get_str8(pb, buf, sizeof(buf)); /* desc */ ast->deint_id = AV_RL32(buf); get_str8(pb, buf, sizeof(buf)); /* desc */ } st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_tag = AV_RL32(buf); st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, st->codecpar->codec_tag); switch (st->codecpar->codec_id) { case AV_CODEC_ID_AC3: st->need_parsing = AVSTREAM_PARSE_FULL; break; case AV_CODEC_ID_RA_288: st->codecpar->extradata_size= 0; av_freep(&st->codecpar->extradata); ast->audio_framesize = st->codecpar->block_align; st->codecpar->block_align = coded_framesize; break; case AV_CODEC_ID_COOK: st->need_parsing = AVSTREAM_PARSE_HEADERS; case AV_CODEC_ID_ATRAC3: case AV_CODEC_ID_SIPR: if (read_all) { codecdata_length = 0; } else { avio_rb16(pb); avio_r8(pb); if (version == 5) avio_r8(pb); codecdata_length = avio_rb32(pb); if(codecdata_length + AV_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){ av_log(s, AV_LOG_ERROR, "codecdata_length too large\n"); return -1; } } ast->audio_framesize = st->codecpar->block_align; if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) { if (flavor > 3) { av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n", flavor); return -1; } st->codecpar->block_align = ff_sipr_subpk_size[flavor]; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; } else { if(sub_packet_size <= 0){ av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n"); return -1; } st->codecpar->block_align = ast->sub_packet_size; } if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length)) < 0) return ret; break; case AV_CODEC_ID_AAC: avio_rb16(pb); avio_r8(pb); if (version == 5) avio_r8(pb); codecdata_length = avio_rb32(pb); if(codecdata_length + AV_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){ av_log(s, AV_LOG_ERROR, "codecdata_length too large\n"); return -1; } if (codecdata_length >= 1) { avio_r8(pb); if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length - 1)) < 0) return ret; } break; } switch (ast->deint_id) { case DEINT_ID_INT4: if (ast->coded_framesize > ast->audio_framesize || sub_packet_h <= 1 || ast->coded_framesize * sub_packet_h > (2 + (sub_packet_h & 1)) * ast->audio_framesize) return AVERROR_INVALIDDATA; if (ast->coded_framesize * sub_packet_h != 2*ast->audio_framesize) { avpriv_request_sample(s, "mismatching interleaver parameters"); return AVERROR_INVALIDDATA; } break; case DEINT_ID_GENR: if (ast->sub_packet_size <= 0 || ast->sub_packet_size > ast->audio_framesize) return AVERROR_INVALIDDATA; if (ast->audio_framesize % ast->sub_packet_size) return AVERROR_INVALIDDATA; break; case DEINT_ID_SIPR: case DEINT_ID_INT0: case DEINT_ID_VBRS: case DEINT_ID_VBRF: break; default: av_log(s, AV_LOG_ERROR ,"Unknown interleaver %"PRIX32"\n", ast->deint_id); return AVERROR_INVALIDDATA; } if (ast->deint_id == DEINT_ID_INT4 || ast->deint_id == DEINT_ID_GENR || ast->deint_id == DEINT_ID_SIPR) { if (st->codecpar->block_align <= 0 || ast->audio_framesize * sub_packet_h > (unsigned)INT_MAX || ast->audio_framesize * sub_packet_h < st->codecpar->block_align) return AVERROR_INVALIDDATA; if (av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h) < 0) return AVERROR(ENOMEM); } if (read_all) { avio_r8(pb); avio_r8(pb); avio_r8(pb); rm_read_metadata(s, pb, 0); } } return 0; } int ff_rm_read_mdpr_codecdata(AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *rst, unsigned int codec_data_size, const uint8_t *mime) { unsigned int v; int size; int64_t codec_pos; int ret; if (codec_data_size > INT_MAX) return AVERROR_INVALIDDATA; if (codec_data_size == 0) return 0; avpriv_set_pts_info(st, 64, 1, 1000); codec_pos = avio_tell(pb); v = avio_rb32(pb); if (v == MKTAG(0xfd, 'a', 'r', '.')) { /* ra type header */ if (rm_read_audio_stream_info(s, pb, st, rst, 0)) return -1; } else if (v == MKBETAG('L', 'S', 'D', ':')) { avio_seek(pb, -4, SEEK_CUR); if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size)) < 0) return ret; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_tag = AV_RL32(st->codecpar->extradata); st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, st->codecpar->codec_tag); } else if(mime && !strcmp(mime, "logical-fileinfo")){ int stream_count, rule_count, property_count, i; ff_free_stream(s, st); if (avio_rb16(pb) != 0) { av_log(s, AV_LOG_WARNING, "Unsupported version\n"); goto skip; } stream_count = avio_rb16(pb); avio_skip(pb, 6*stream_count); rule_count = avio_rb16(pb); avio_skip(pb, 2*rule_count); property_count = avio_rb16(pb); for(i=0; i<property_count; i++){ uint8_t name[128], val[128]; avio_rb32(pb); if (avio_rb16(pb) != 0) { av_log(s, AV_LOG_WARNING, "Unsupported Name value property version\n"); goto skip; //FIXME skip just this one } get_str8(pb, name, sizeof(name)); switch(avio_rb32(pb)) { case 2: get_strl(pb, val, sizeof(val), avio_rb16(pb)); av_dict_set(&s->metadata, name, val, 0); break; default: avio_skip(pb, avio_rb16(pb)); } } } else { int fps; if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) { fail1: av_log(s, AV_LOG_WARNING, "Unsupported stream type %08x\n", v); goto skip; } st->codecpar->codec_tag = avio_rl32(pb); st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, st->codecpar->codec_tag); av_log(s, AV_LOG_TRACE, "%"PRIX32" %X\n", st->codecpar->codec_tag, MKTAG('R', 'V', '2', '0')); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) goto fail1; st->codecpar->width = avio_rb16(pb); st->codecpar->height = avio_rb16(pb); avio_skip(pb, 2); // looks like bits per sample avio_skip(pb, 4); // always zero? st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; fps = avio_rb32(pb); if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size - (avio_tell(pb) - codec_pos))) < 0) return ret; if (fps > 0) { av_reduce(&st->avg_frame_rate.den, &st->avg_frame_rate.num, 0x10000, fps, (1 << 30) - 1); #if FF_API_R_FRAME_RATE st->r_frame_rate = st->avg_frame_rate; #endif } else if (s->error_recognition & AV_EF_EXPLODE) { av_log(s, AV_LOG_ERROR, "Invalid framerate\n"); return AVERROR_INVALIDDATA; } } skip: /* skip codec info */ size = avio_tell(pb) - codec_pos; if (codec_data_size >= size) { avio_skip(pb, codec_data_size - size); } else { av_log(s, AV_LOG_WARNING, "codec_data_size %u < size %d\n", codec_data_size, size); } return 0; } /** this function assumes that the demuxer has already seeked to the start * of the INDX chunk, and will bail out if not. */ static int rm_read_index(AVFormatContext *s) { AVIOContext *pb = s->pb; unsigned int size, n_pkts, str_id, next_off, n, pos, pts; AVStream *st; do { if (avio_rl32(pb) != MKTAG('I','N','D','X')) return -1; size = avio_rb32(pb); if (size < 20) return -1; avio_skip(pb, 2); n_pkts = avio_rb32(pb); str_id = avio_rb16(pb); next_off = avio_rb32(pb); for (n = 0; n < s->nb_streams; n++) if (s->streams[n]->id == str_id) { st = s->streams[n]; break; } if (n == s->nb_streams) { av_log(s, AV_LOG_ERROR, "Invalid stream index %d for index at pos %"PRId64"\n", str_id, avio_tell(pb)); goto skip; } else if ((avio_size(pb) - avio_tell(pb)) / 14 < n_pkts) { av_log(s, AV_LOG_ERROR, "Nr. of packets in packet index for stream index %d " "exceeds filesize (%"PRId64" at %"PRId64" = %"PRId64")\n", str_id, avio_size(pb), avio_tell(pb), (avio_size(pb) - avio_tell(pb)) / 14); goto skip; } for (n = 0; n < n_pkts; n++) { avio_skip(pb, 2); pts = avio_rb32(pb); pos = avio_rb32(pb); avio_skip(pb, 4); /* packet no. */ av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME); } skip: if (next_off && avio_tell(pb) < next_off && avio_seek(pb, next_off, SEEK_SET) < 0) { av_log(s, AV_LOG_ERROR, "Non-linear index detected, not supported\n"); return -1; } } while (next_off); return 0; } static int rm_read_header_old(AVFormatContext *s) { RMDemuxContext *rm = s->priv_data; AVStream *st; rm->old_format = 1; st = avformat_new_stream(s, NULL); if (!st) return -1; st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1); } static int rm_read_multi(AVFormatContext *s, AVIOContext *pb, AVStream *st, char *mime) { int number_of_streams = avio_rb16(pb); int number_of_mdpr; int i, ret; unsigned size2; for (i = 0; i<number_of_streams; i++) avio_rb16(pb); number_of_mdpr = avio_rb16(pb); if (number_of_mdpr != 1) { avpriv_request_sample(s, "MLTI with multiple (%d) MDPR", number_of_mdpr); } for (i = 0; i < number_of_mdpr; i++) { AVStream *st2; if (i > 0) { st2 = avformat_new_stream(s, NULL); if (!st2) { ret = AVERROR(ENOMEM); return ret; } st2->id = st->id + (i<<16); st2->codecpar->bit_rate = st->codecpar->bit_rate; st2->start_time = st->start_time; st2->duration = st->duration; st2->codecpar->codec_type = AVMEDIA_TYPE_DATA; st2->priv_data = ff_rm_alloc_rmstream(); if (!st2->priv_data) return AVERROR(ENOMEM); } else st2 = st; size2 = avio_rb32(pb); ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data, size2, mime); if (ret < 0) return ret; } return 0; } static int rm_read_header(AVFormatContext *s) { RMDemuxContext *rm = s->priv_data; AVStream *st; AVIOContext *pb = s->pb; unsigned int tag; int tag_size; unsigned int start_time, duration; unsigned int data_off = 0, indx_off = 0; char buf[128], mime[128]; int flags = 0; int ret = -1; unsigned size, v; int64_t codec_pos; tag = avio_rl32(pb); if (tag == MKTAG('.', 'r', 'a', 0xfd)) { /* very old .ra format */ return rm_read_header_old(s); } else if (tag != MKTAG('.', 'R', 'M', 'F')) { return AVERROR(EIO); } tag_size = avio_rb32(pb); avio_skip(pb, tag_size - 8); for(;;) { if (avio_feof(pb)) goto fail; tag = avio_rl32(pb); tag_size = avio_rb32(pb); avio_rb16(pb); av_log(s, AV_LOG_TRACE, "tag=%s size=%d\n", av_fourcc2str(tag), tag_size); if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A')) goto fail; switch(tag) { case MKTAG('P', 'R', 'O', 'P'): /* file header */ avio_rb32(pb); /* max bit rate */ avio_rb32(pb); /* avg bit rate */ avio_rb32(pb); /* max packet size */ avio_rb32(pb); /* avg packet size */ avio_rb32(pb); /* nb packets */ duration = avio_rb32(pb); /* duration */ s->duration = av_rescale(duration, AV_TIME_BASE, 1000); avio_rb32(pb); /* preroll */ indx_off = avio_rb32(pb); /* index offset */ data_off = avio_rb32(pb); /* data offset */ avio_rb16(pb); /* nb streams */ flags = avio_rb16(pb); /* flags */ break; case MKTAG('C', 'O', 'N', 'T'): rm_read_metadata(s, pb, 1); break; case MKTAG('M', 'D', 'P', 'R'): st = avformat_new_stream(s, NULL); if (!st) { ret = AVERROR(ENOMEM); goto fail; } st->id = avio_rb16(pb); avio_rb32(pb); /* max bit rate */ st->codecpar->bit_rate = avio_rb32(pb); /* bit rate */ avio_rb32(pb); /* max packet size */ avio_rb32(pb); /* avg packet size */ start_time = avio_rb32(pb); /* start time */ avio_rb32(pb); /* preroll */ duration = avio_rb32(pb); /* duration */ st->start_time = start_time; st->duration = duration; if(duration>0) s->duration = AV_NOPTS_VALUE; get_str8(pb, buf, sizeof(buf)); /* desc */ get_str8(pb, mime, sizeof(mime)); /* mimetype */ st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); size = avio_rb32(pb); codec_pos = avio_tell(pb); ffio_ensure_seekback(pb, 4); v = avio_rb32(pb); if (v == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, s->pb, st, mime); if (ret < 0) goto fail; avio_seek(pb, codec_pos + size, SEEK_SET); } else { avio_skip(pb, -4); if (ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data, size, mime) < 0) goto fail; } break; case MKTAG('D', 'A', 'T', 'A'): goto header_end; default: /* unknown tag: skip it */ avio_skip(pb, tag_size - 10); break; } } header_end: rm->nb_packets = avio_rb32(pb); /* number of packets */ if (!rm->nb_packets && (flags & 4)) rm->nb_packets = 3600 * 25; avio_rb32(pb); /* next data header */ if (!data_off) data_off = avio_tell(pb) - 18; if (indx_off && (pb->seekable & AVIO_SEEKABLE_NORMAL) && !(s->flags & AVFMT_FLAG_IGNIDX) && avio_seek(pb, indx_off, SEEK_SET) >= 0) { rm_read_index(s); avio_seek(pb, data_off + 18, SEEK_SET); } return 0; fail: rm_read_close(s); return ret; } static int get_num(AVIOContext *pb, int *len) { int n, n1; n = avio_rb16(pb); (*len)-=2; n &= 0x7FFF; if (n >= 0x4000) { return n - 0x4000; } else { n1 = avio_rb16(pb); (*len)-=2; return (n << 16) | n1; } } /* multiple of 20 bytes for ra144 (ugly) */ #define RAW_PACKET_SIZE 1000 static int rm_sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){ RMDemuxContext *rm = s->priv_data; AVIOContext *pb = s->pb; AVStream *st; uint32_t state=0xFFFFFFFF; while(!avio_feof(pb)){ int len, num, i; int mlti_id; *pos= avio_tell(pb) - 3; if(rm->remaining_len > 0){ num= rm->current_stream; mlti_id = 0; len= rm->remaining_len; *timestamp = AV_NOPTS_VALUE; *flags= 0; }else{ state= (state<<8) + avio_r8(pb); if(state == MKBETAG('I', 'N', 'D', 'X')){ int n_pkts, expected_len; len = avio_rb32(pb); avio_skip(pb, 2); n_pkts = avio_rb32(pb); expected_len = 20 + n_pkts * 14; if (len == 20) /* some files don't add index entries to chunk size... */ len = expected_len; else if (len != expected_len) av_log(s, AV_LOG_WARNING, "Index size %d (%d pkts) is wrong, should be %d.\n", len, n_pkts, expected_len); len -= 14; // we already read part of the index header if(len<0) continue; goto skip; } else if (state == MKBETAG('D','A','T','A')) { av_log(s, AV_LOG_WARNING, "DATA tag in middle of chunk, file may be broken.\n"); } if(state > (unsigned)0xFFFF || state <= 12) continue; len=state - 12; state= 0xFFFFFFFF; num = avio_rb16(pb); *timestamp = avio_rb32(pb); mlti_id = (avio_r8(pb)>>1)-1<<16; mlti_id = FFMAX(mlti_id, 0); *flags = avio_r8(pb); /* flags */ } for(i=0;i<s->nb_streams;i++) { st = s->streams[i]; if (mlti_id + num == st->id) break; } if (i == s->nb_streams) { skip: /* skip packet if unknown number */ avio_skip(pb, len); rm->remaining_len = 0; continue; } *stream_index= i; return len; } return -1; } static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb, RMDemuxContext *rm, RMStream *vst, AVPacket *pkt, int len, int *pseq, int64_t *timestamp) { int hdr; int seq = 0, pic_num = 0, len2 = 0, pos = 0; //init to silence compiler warning int type; int ret; hdr = avio_r8(pb); len--; type = hdr >> 6; if(type != 3){ // not frame as a part of packet seq = avio_r8(pb); len--; } if(type != 1){ // not whole frame len2 = get_num(pb, &len); pos = get_num(pb, &len); pic_num = avio_r8(pb); len--; } if(len<0) { av_log(s, AV_LOG_ERROR, "Insufficient data\n"); return -1; } rm->remaining_len = len; if(type&1){ // frame, not slice if(type == 3){ // frame as a part of packet len= len2; *timestamp = pos; } if(rm->remaining_len < len) { av_log(s, AV_LOG_ERROR, "Insufficient remaining len\n"); return -1; } rm->remaining_len -= len; if(av_new_packet(pkt, len + 9) < 0) return AVERROR(EIO); pkt->data[0] = 0; AV_WL32(pkt->data + 1, 1); AV_WL32(pkt->data + 5, 0); if ((ret = avio_read(pb, pkt->data + 9, len)) != len) { av_packet_unref(pkt); av_log(s, AV_LOG_ERROR, "Failed to read %d bytes\n", len); return ret < 0 ? ret : AVERROR(EIO); } return 0; } //now we have to deal with single slice *pseq = seq; if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){ if (len2 > ffio_limit(pb, len2)) { av_log(s, AV_LOG_ERROR, "Impossibly sized packet\n"); return AVERROR_INVALIDDATA; } vst->slices = ((hdr & 0x3F) << 1) + 1; vst->videobufsize = len2 + 8*vst->slices + 1; av_packet_unref(&vst->pkt); //FIXME this should be output. if(av_new_packet(&vst->pkt, vst->videobufsize) < 0) return AVERROR(ENOMEM); memset(vst->pkt.data, 0, vst->pkt.size); vst->videobufpos = 8*vst->slices + 1; vst->cur_slice = 0; vst->curpic_num = pic_num; vst->pktpos = avio_tell(pb); } if(type == 2) len = FFMIN(len, pos); if(++vst->cur_slice > vst->slices) { av_log(s, AV_LOG_ERROR, "cur slice %d, too large\n", vst->cur_slice); return 1; } if(!vst->pkt.data) return AVERROR(ENOMEM); AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1); AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1); if(vst->videobufpos + len > vst->videobufsize) { av_log(s, AV_LOG_ERROR, "outside videobufsize\n"); return 1; } if (avio_read(pb, vst->pkt.data + vst->videobufpos, len) != len) return AVERROR(EIO); vst->videobufpos += len; rm->remaining_len-= len; if (type == 2 || vst->videobufpos == vst->videobufsize) { vst->pkt.data[0] = vst->cur_slice-1; *pkt= vst->pkt; vst->pkt.data= NULL; vst->pkt.size= 0; vst->pkt.buf = NULL; if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices, vst->videobufpos - 1 - 8*vst->slices); pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices); pkt->pts = AV_NOPTS_VALUE; pkt->pos = vst->pktpos; vst->slices = 0; return 0; } return 1; } static inline void rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt) { uint8_t *ptr; int j; if (st->codecpar->codec_id == AV_CODEC_ID_AC3) { ptr = pkt->data; for (j=0;j<pkt->size;j+=2) { FFSWAP(int, ptr[0], ptr[1]); ptr += 2; } } } static int readfull(AVFormatContext *s, AVIOContext *pb, uint8_t *dst, int n) { int ret = avio_read(pb, dst, n); if (ret != n) { if (ret >= 0) memset(dst + ret, 0, n - ret); else memset(dst , 0, n); av_log(s, AV_LOG_ERROR, "Failed to fully read block\n"); } return ret; } int ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *ast, int len, AVPacket *pkt, int *seq, int flags, int64_t timestamp) { RMDemuxContext *rm = s->priv_data; int ret; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { rm->current_stream= st->id; ret = rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq, &timestamp); if(ret) return ret < 0 ? ret : -1; //got partial frame or error } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if ((ast->deint_id == DEINT_ID_GENR) || (ast->deint_id == DEINT_ID_INT4) || (ast->deint_id == DEINT_ID_SIPR)) { int x; int sps = ast->sub_packet_size; int cfs = ast->coded_framesize; int h = ast->sub_packet_h; int y = ast->sub_packet_cnt; int w = ast->audio_framesize; if (flags & 2) y = ast->sub_packet_cnt = 0; if (!y) ast->audiotimestamp = timestamp; switch (ast->deint_id) { case DEINT_ID_INT4: for (x = 0; x < h/2; x++) readfull(s, pb, ast->pkt.data+x*2*w+y*cfs, cfs); break; case DEINT_ID_GENR: for (x = 0; x < w/sps; x++) readfull(s, pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps); break; case DEINT_ID_SIPR: readfull(s, pb, ast->pkt.data + y * w, w); break; } if (++(ast->sub_packet_cnt) < h) return -1; if (ast->deint_id == DEINT_ID_SIPR) ff_rm_reorder_sipr_data(ast->pkt.data, h, w); ast->sub_packet_cnt = 0; rm->audio_stream_num = st->index; if (st->codecpar->block_align <= 0) { av_log(s, AV_LOG_ERROR, "Invalid block alignment %d\n", st->codecpar->block_align); return AVERROR_INVALIDDATA; } rm->audio_pkt_cnt = h * w / st->codecpar->block_align; } else if ((ast->deint_id == DEINT_ID_VBRF) || (ast->deint_id == DEINT_ID_VBRS)) { int x; rm->audio_stream_num = st->index; ast->sub_packet_cnt = (avio_rb16(pb) & 0xf0) >> 4; if (ast->sub_packet_cnt) { for (x = 0; x < ast->sub_packet_cnt; x++) ast->sub_packet_lengths[x] = avio_rb16(pb); rm->audio_pkt_cnt = ast->sub_packet_cnt; ast->audiotimestamp = timestamp; } else return -1; } else { if ((ret = av_get_packet(pb, pkt, len)) < 0) return ret; rm_ac3_swap_bytes(st, pkt); } } else { if ((ret = av_get_packet(pb, pkt, len)) < 0) return ret; } pkt->stream_index = st->index; pkt->pts = timestamp; if (flags & 2) pkt->flags |= AV_PKT_FLAG_KEY; return st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0; } int ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *ast, AVPacket *pkt) { RMDemuxContext *rm = s->priv_data; av_assert0 (rm->audio_pkt_cnt > 0); if (ast->deint_id == DEINT_ID_VBRF || ast->deint_id == DEINT_ID_VBRS) { int ret = av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]); if (ret < 0) return ret; } else { int ret = av_new_packet(pkt, st->codecpar->block_align); if (ret < 0) return ret; memcpy(pkt->data, ast->pkt.data + st->codecpar->block_align * //FIXME avoid this (ast->sub_packet_h * ast->audio_framesize / st->codecpar->block_align - rm->audio_pkt_cnt), st->codecpar->block_align); } rm->audio_pkt_cnt--; if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) { ast->audiotimestamp = AV_NOPTS_VALUE; pkt->flags = AV_PKT_FLAG_KEY; } else pkt->flags = 0; pkt->stream_index = st->index; return rm->audio_pkt_cnt; } static int rm_read_packet(AVFormatContext *s, AVPacket *pkt) { RMDemuxContext *rm = s->priv_data; AVStream *st = NULL; // init to silence compiler warning int i, len, res, seq = 1; int64_t timestamp, pos; int flags; for (;;) { if (rm->audio_pkt_cnt) { // If there are queued audio packet return them first st = s->streams[rm->audio_stream_num]; res = ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt); if(res < 0) return res; flags = 0; } else { if (rm->old_format) { RMStream *ast; st = s->streams[0]; ast = st->priv_data; timestamp = AV_NOPTS_VALUE; len = !ast->audio_framesize ? RAW_PACKET_SIZE : ast->coded_framesize * ast->sub_packet_h / 2; flags = (seq++ == 1) ? 2 : 0; pos = avio_tell(s->pb); } else { len = rm_sync(s, &timestamp, &flags, &i, &pos); if (len > 0) st = s->streams[i]; } if (avio_feof(s->pb)) return AVERROR_EOF; if (len <= 0) return AVERROR(EIO); res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt, &seq, flags, timestamp); if (res < -1) return res; if((flags&2) && (seq&0x7F) == 1) av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME); if (res) continue; } if( (st->discard >= AVDISCARD_NONKEY && !(flags&2)) || st->discard >= AVDISCARD_ALL){ av_packet_unref(pkt); } else break; } return 0; } static int rm_read_close(AVFormatContext *s) { int i; for (i=0;i<s->nb_streams;i++) ff_rm_free_rmstream(s->streams[i]->priv_data); return 0; } static int rm_probe(AVProbeData *p) { /* check file header */ if ((p->buf[0] == '.' && p->buf[1] == 'R' && p->buf[2] == 'M' && p->buf[3] == 'F' && p->buf[4] == 0 && p->buf[5] == 0) || (p->buf[0] == '.' && p->buf[1] == 'r' && p->buf[2] == 'a' && p->buf[3] == 0xfd)) return AVPROBE_SCORE_MAX; else return 0; } static int64_t rm_read_dts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit) { RMDemuxContext *rm = s->priv_data; int64_t pos, dts; int stream_index2, flags, len, h; pos = *ppos; if(rm->old_format) return AV_NOPTS_VALUE; if (avio_seek(s->pb, pos, SEEK_SET) < 0) return AV_NOPTS_VALUE; rm->remaining_len=0; for(;;){ int seq=1; AVStream *st; len = rm_sync(s, &dts, &flags, &stream_index2, &pos); if(len<0) return AV_NOPTS_VALUE; st = s->streams[stream_index2]; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { h= avio_r8(s->pb); len--; if(!(h & 0x40)){ seq = avio_r8(s->pb); len--; } } if((flags&2) && (seq&0x7F) == 1){ av_log(s, AV_LOG_TRACE, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq); av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME); if(stream_index2 == stream_index) break; } avio_skip(s->pb, len); } *ppos = pos; return dts; } static int rm_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags) { RMDemuxContext *rm = s->priv_data; if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0) return -1; rm->audio_pkt_cnt = 0; return 0; } AVInputFormat ff_rm_demuxer = { .name = "rm", .long_name = NULL_IF_CONFIG_SMALL("RealMedia"), .priv_data_size = sizeof(RMDemuxContext), .read_probe = rm_probe, .read_header = rm_read_header, .read_packet = rm_read_packet, .read_close = rm_read_close, .read_timestamp = rm_read_dts, .read_seek = rm_read_seek, }; AVInputFormat ff_rdt_demuxer = { .name = "rdt", .long_name = NULL_IF_CONFIG_SMALL("RDT demuxer"), .priv_data_size = sizeof(RMDemuxContext), .read_close = rm_read_close, .flags = AVFMT_NOFILE, }; static int ivr_probe(AVProbeData *p) { if (memcmp(p->buf, ".R1M\x0\x1\x1", 7) && memcmp(p->buf, ".REC", 4)) return 0; return AVPROBE_SCORE_MAX; } static int ivr_read_header(AVFormatContext *s) { unsigned tag, type, len, tlen, value; int i, j, n, count, nb_streams = 0, ret; uint8_t key[256], val[256]; AVIOContext *pb = s->pb; AVStream *st; int64_t pos, offset, temp; pos = avio_tell(pb); tag = avio_rl32(pb); if (tag == MKTAG('.','R','1','M')) { if (avio_rb16(pb) != 1) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); avio_skip(pb, 5); temp = avio_rb64(pb); while (!avio_feof(pb) && temp) { offset = temp; temp = avio_rb64(pb); } avio_skip(pb, offset - avio_tell(pb)); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); if (avio_r8(pb) != 2) return AVERROR_INVALIDDATA; avio_skip(pb, 16); pos = avio_tell(pb); tag = avio_rl32(pb); } if (tag != MKTAG('.','R','E','C')) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4) { av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) { nb_streams = value = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } for (n = 0; n < nb_streams; n++) { st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) { ret = ffio_ensure_seekback(pb, 4); if (ret < 0) return ret; if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, pb, st, NULL); } else { avio_seek(pb, -4, SEEK_CUR); ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); } if (ret < 0) return ret; } else if (type == 4) { int j; av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) { st->duration = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } } if (avio_r8(pb) != 6) return AVERROR_INVALIDDATA; avio_skip(pb, 12); avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); if (avio_r8(pb) != 8) return AVERROR_INVALIDDATA; avio_skip(pb, 8); return 0; } static int ivr_read_packet(AVFormatContext *s, AVPacket *pkt) { RMDemuxContext *rm = s->priv_data; int ret = AVERROR_EOF, opcode; AVIOContext *pb = s->pb; unsigned size, index; int64_t pos, pts; if (avio_feof(pb) || rm->data_end) return AVERROR_EOF; pos = avio_tell(pb); for (;;) { if (rm->audio_pkt_cnt) { // If there are queued audio packet return them first AVStream *st; st = s->streams[rm->audio_stream_num]; ret = ff_rm_retrieve_cache(s, pb, st, st->priv_data, pkt); if (ret < 0) { return ret; } } else { if (rm->remaining_len) { avio_skip(pb, rm->remaining_len); rm->remaining_len = 0; } if (avio_feof(pb)) return AVERROR_EOF; opcode = avio_r8(pb); if (opcode == 2) { AVStream *st; int seq = 1; pts = avio_rb32(pb); index = avio_rb16(pb); if (index >= s->nb_streams) return AVERROR_INVALIDDATA; avio_skip(pb, 4); size = avio_rb32(pb); avio_skip(pb, 4); if (size < 1 || size > INT_MAX/4) { av_log(s, AV_LOG_ERROR, "size %u is invalid\n", size); return AVERROR_INVALIDDATA; } st = s->streams[index]; ret = ff_rm_parse_packet(s, pb, st, st->priv_data, size, pkt, &seq, 0, pts); if (ret < -1) { return ret; } else if (ret) { continue; } pkt->pos = pos; pkt->pts = pts; pkt->stream_index = index; } else if (opcode == 7) { pos = avio_rb64(pb); if (!pos) { rm->data_end = 1; return AVERROR_EOF; } } else { av_log(s, AV_LOG_ERROR, "Unsupported opcode=%d at %"PRIX64"\n", opcode, avio_tell(pb) - 1); return AVERROR(EIO); } } break; } return ret; } AVInputFormat ff_ivr_demuxer = { .name = "ivr", .long_name = NULL_IF_CONFIG_SMALL("IVR (Internet Video Recording)"), .priv_data_size = sizeof(RMDemuxContext), .read_probe = ivr_probe, .read_header = ivr_read_header, .read_packet = ivr_read_packet, .read_close = rm_read_close, .extensions = "ivr", };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2761_0
crossvul-cpp_data_bad_2780_0
/* * NSV demuxer * Copyright (c) 2004 The FFmpeg Project * * first version by Francois Revol <revol@free.fr> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/attributes.h" #include "libavutil/mathematics.h" #include "avformat.h" #include "internal.h" #include "libavutil/dict.h" #include "libavutil/intreadwrite.h" /* max bytes to crawl for trying to resync * stupid streaming servers don't start at chunk boundaries... */ #define NSV_MAX_RESYNC (500*1024) #define NSV_MAX_RESYNC_TRIES 300 /* * References: * (1) http://www.multimedia.cx/nsv-format.txt * seems someone came to the same conclusions as me, and updated it: * (2) http://www.stud.ktu.lt/~vitslav/nsv/nsv-format.txt * http://www.stud.ktu.lt/~vitslav/nsv/ * official docs * (3) http://ultravox.aol.com/NSVFormat.rtf * Sample files: * (S1) http://www.nullsoft.com/nsv/samples/ * http://www.nullsoft.com/nsv/samples/faster.nsv * http://streamripper.sourceforge.net/openbb/read.php?TID=492&page=4 */ /* * notes on the header (Francois Revol): * * It is followed by strings, then a table, but nothing tells * where the table begins according to (1). After checking faster.nsv, * I believe NVSf[16-19] gives the size of the strings data * (that is the offset of the data table after the header). * After checking all samples from (S1) all confirms this. * * Then, about NSVf[12-15], faster.nsf has 179700. When viewing it in VLC, * I noticed there was about 1 NVSs chunk/s, so I ran * strings faster.nsv | grep NSVs | wc -l * which gave me 180. That leads me to think that NSVf[12-15] might be the * file length in milliseconds. * Let's try that: * for f in *.nsv; do HTIME="$(od -t x4 "$f" | head -1 | sed 's/.* //')"; echo "'$f' $((0x$HTIME))s = $((0x$HTIME/1000/60)):$((0x$HTIME/1000%60))"; done * except for nsvtrailer (which doesn't have an NSVf header), it reports correct time. * * nsvtrailer.nsv (S1) does not have any NSVf header, only NSVs chunks, * so the header seems to not be mandatory. (for streaming). * * index slice duration check (excepts nsvtrailer.nsv): * for f in [^n]*.nsv; do DUR="$(ffmpeg -i "$f" 2>/dev/null | grep 'NSVf duration' | cut -d ' ' -f 4)"; IC="$(ffmpeg -i "$f" 2>/dev/null | grep 'INDEX ENTRIES' | cut -d ' ' -f 2)"; echo "duration $DUR, slite time $(($DUR/$IC))"; done */ /* * TODO: * - handle timestamps !!! * - use index * - mime-type in probe() * - seek */ #if 0 struct NSVf_header { uint32_t chunk_tag; /* 'NSVf' */ uint32_t chunk_size; uint32_t file_size; /* max 4GB ??? no one learns anything it seems :^) */ uint32_t file_length; //unknown1; /* what about MSB of file_size ? */ uint32_t info_strings_size; /* size of the info strings */ //unknown2; uint32_t table_entries; uint32_t table_entries_used; /* the left ones should be -1 */ }; struct NSVs_header { uint32_t chunk_tag; /* 'NSVs' */ uint32_t v4cc; /* or 'NONE' */ uint32_t a4cc; /* or 'NONE' */ uint16_t vwidth; /* av_assert0(vwidth%16==0) */ uint16_t vheight; /* av_assert0(vheight%16==0) */ uint8_t framerate; /* value = (framerate&0x80)?frtable[frameratex0x7f]:framerate */ uint16_t unknown; }; struct nsv_avchunk_header { uint8_t vchunk_size_lsb; uint16_t vchunk_size_msb; /* value = (vchunk_size_msb << 4) | (vchunk_size_lsb >> 4) */ uint16_t achunk_size; }; struct nsv_pcm_header { uint8_t bits_per_sample; uint8_t channel_count; uint16_t sample_rate; }; #endif /* variation from avi.h */ /*typedef struct CodecTag { int id; unsigned int tag; } CodecTag;*/ /* tags */ #define T_NSVF MKTAG('N', 'S', 'V', 'f') /* file header */ #define T_NSVS MKTAG('N', 'S', 'V', 's') /* chunk header */ #define T_TOC2 MKTAG('T', 'O', 'C', '2') /* extra index marker */ #define T_NONE MKTAG('N', 'O', 'N', 'E') /* null a/v 4CC */ #define T_SUBT MKTAG('S', 'U', 'B', 'T') /* subtitle aux data */ #define T_ASYN MKTAG('A', 'S', 'Y', 'N') /* async a/v aux marker */ #define T_KEYF MKTAG('K', 'E', 'Y', 'F') /* video keyframe aux marker (addition) */ #define TB_NSVF MKBETAG('N', 'S', 'V', 'f') #define TB_NSVS MKBETAG('N', 'S', 'V', 's') /* hardcoded stream indexes */ #define NSV_ST_VIDEO 0 #define NSV_ST_AUDIO 1 #define NSV_ST_SUBT 2 enum NSVStatus { NSV_UNSYNC, NSV_FOUND_NSVF, NSV_HAS_READ_NSVF, NSV_FOUND_NSVS, NSV_HAS_READ_NSVS, NSV_FOUND_BEEF, NSV_GOT_VIDEO, NSV_GOT_AUDIO, }; typedef struct NSVStream { int frame_offset; /* current frame (video) or byte (audio) counter (used to compute the pts) */ int scale; int rate; int sample_size; /* audio only data */ int start; int new_frame_offset; /* temporary storage (used during seek) */ int cum_len; /* temporary storage (used during seek) */ } NSVStream; typedef struct NSVContext { int base_offset; int NSVf_end; uint32_t *nsvs_file_offset; int index_entries; enum NSVStatus state; AVPacket ahead[2]; /* [v, a] if .data is !NULL there is something */ /* cached */ int64_t duration; uint32_t vtag, atag; uint16_t vwidth, vheight; int16_t avsync; AVRational framerate; uint32_t *nsvs_timestamps; } NSVContext; static const AVCodecTag nsv_codec_video_tags[] = { { AV_CODEC_ID_VP3, MKTAG('V', 'P', '3', ' ') }, { AV_CODEC_ID_VP3, MKTAG('V', 'P', '3', '0') }, { AV_CODEC_ID_VP3, MKTAG('V', 'P', '3', '1') }, { AV_CODEC_ID_VP5, MKTAG('V', 'P', '5', ' ') }, { AV_CODEC_ID_VP5, MKTAG('V', 'P', '5', '0') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', ' ') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', '0') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', '1') }, { AV_CODEC_ID_VP6, MKTAG('V', 'P', '6', '2') }, { AV_CODEC_ID_VP8, MKTAG('V', 'P', '8', '0') }, /* { AV_CODEC_ID_VP4, MKTAG('V', 'P', '4', ' ') }, { AV_CODEC_ID_VP4, MKTAG('V', 'P', '4', '0') }, */ { AV_CODEC_ID_MPEG4, MKTAG('X', 'V', 'I', 'D') }, /* cf sample xvid decoder from nsv_codec_sdk.zip */ { AV_CODEC_ID_RAWVIDEO, MKTAG('R', 'G', 'B', '3') }, { AV_CODEC_ID_NONE, 0 }, }; static const AVCodecTag nsv_codec_audio_tags[] = { { AV_CODEC_ID_MP3, MKTAG('M', 'P', '3', ' ') }, { AV_CODEC_ID_AAC, MKTAG('A', 'A', 'C', ' ') }, { AV_CODEC_ID_AAC, MKTAG('A', 'A', 'C', 'P') }, { AV_CODEC_ID_AAC, MKTAG('V', 'L', 'B', ' ') }, { AV_CODEC_ID_SPEEX, MKTAG('S', 'P', 'X', ' ') }, { AV_CODEC_ID_PCM_U16LE, MKTAG('P', 'C', 'M', ' ') }, { AV_CODEC_ID_NONE, 0 }, }; //static int nsv_load_index(AVFormatContext *s); static int nsv_read_chunk(AVFormatContext *s, int fill_header); /* try to find something we recognize, and set the state accordingly */ static int nsv_resync(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; uint32_t v = 0; int i; for (i = 0; i < NSV_MAX_RESYNC; i++) { if (avio_feof(pb)) { av_log(s, AV_LOG_TRACE, "NSV EOF\n"); nsv->state = NSV_UNSYNC; return -1; } v <<= 8; v |= avio_r8(pb); if (i < 8) { av_log(s, AV_LOG_TRACE, "NSV resync: [%d] = %02"PRIx32"\n", i, v & 0x0FF); } if ((v & 0x0000ffff) == 0xefbe) { /* BEEF */ av_log(s, AV_LOG_TRACE, "NSV resynced on BEEF after %d bytes\n", i+1); nsv->state = NSV_FOUND_BEEF; return 0; } /* we read as big-endian, thus the MK*BE* */ if (v == TB_NSVF) { /* NSVf */ av_log(s, AV_LOG_TRACE, "NSV resynced on NSVf after %d bytes\n", i+1); nsv->state = NSV_FOUND_NSVF; return 0; } if (v == MKBETAG('N', 'S', 'V', 's')) { /* NSVs */ av_log(s, AV_LOG_TRACE, "NSV resynced on NSVs after %d bytes\n", i+1); nsv->state = NSV_FOUND_NSVS; return 0; } } av_log(s, AV_LOG_TRACE, "NSV sync lost\n"); return -1; } static int nsv_parse_NSVf_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; unsigned int av_unused file_size; unsigned int size; int64_t duration; int strings_size; int table_entries; int table_entries_used; nsv->state = NSV_UNSYNC; /* in case we fail */ size = avio_rl32(pb); if (size < 28) return -1; nsv->NSVf_end = size; file_size = (uint32_t)avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf chunk_size %u\n", size); av_log(s, AV_LOG_TRACE, "NSV NSVf file_size %u\n", file_size); nsv->duration = duration = avio_rl32(pb); /* in ms */ av_log(s, AV_LOG_TRACE, "NSV NSVf duration %"PRId64" ms\n", duration); // XXX: store it in AVStreams strings_size = avio_rl32(pb); table_entries = avio_rl32(pb); table_entries_used = avio_rl32(pb); av_log(s, AV_LOG_TRACE, "NSV NSVf info-strings size: %d, table entries: %d, bis %d\n", strings_size, table_entries, table_entries_used); if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got header; filepos %"PRId64"\n", avio_tell(pb)); if (strings_size > 0) { char *strings; /* last byte will be '\0' to play safe with str*() */ char *p, *endp; char *token, *value; char quote; p = strings = av_mallocz((size_t)strings_size + 1); if (!p) return AVERROR(ENOMEM); endp = strings + strings_size; avio_read(pb, strings, strings_size); while (p < endp) { while (*p == ' ') p++; /* strip out spaces */ if (p >= endp-2) break; token = p; p = strchr(p, '='); if (!p || p >= endp-2) break; *p++ = '\0'; quote = *p++; value = p; p = strchr(p, quote); if (!p || p >= endp) break; *p++ = '\0'; av_log(s, AV_LOG_TRACE, "NSV NSVf INFO: %s='%s'\n", token, value); av_dict_set(&s->metadata, token, value, 0); } av_free(strings); } if (avio_feof(pb)) return -1; av_log(s, AV_LOG_TRACE, "NSV got infos; filepos %"PRId64"\n", avio_tell(pb)); if (table_entries_used > 0) { int i; nsv->index_entries = table_entries_used; if((unsigned)table_entries_used >= UINT_MAX / sizeof(uint32_t)) return -1; nsv->nsvs_file_offset = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_file_offset) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) nsv->nsvs_file_offset[i] = avio_rl32(pb) + size; if(table_entries > table_entries_used && avio_rl32(pb) == MKTAG('T','O','C','2')) { nsv->nsvs_timestamps = av_malloc_array((unsigned)table_entries_used, sizeof(uint32_t)); if (!nsv->nsvs_timestamps) return AVERROR(ENOMEM); for(i=0;i<table_entries_used;i++) { nsv->nsvs_timestamps[i] = avio_rl32(pb); } } } av_log(s, AV_LOG_TRACE, "NSV got index; filepos %"PRId64"\n", avio_tell(pb)); avio_seek(pb, nsv->base_offset + size, SEEK_SET); /* required for dumbdriving-271.nsv (2 extra bytes) */ if (avio_feof(pb)) return -1; nsv->state = NSV_HAS_READ_NSVF; return 0; } static int nsv_parse_NSVs_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; uint32_t vtag, atag; uint16_t vwidth, vheight; AVRational framerate; int i; AVStream *st; NSVStream *nst; vtag = avio_rl32(pb); atag = avio_rl32(pb); vwidth = avio_rl16(pb); vheight = avio_rl16(pb); i = avio_r8(pb); av_log(s, AV_LOG_TRACE, "NSV NSVs framerate code %2x\n", i); if(i&0x80) { /* odd way of giving native framerates from docs */ int t=(i & 0x7F)>>2; if(t<16) framerate = (AVRational){1, t+1}; else framerate = (AVRational){t-15, 1}; if(i&1){ framerate.num *= 1000; framerate.den *= 1001; } if((i&3)==3) framerate.num *= 24; else if((i&3)==2) framerate.num *= 25; else framerate.num *= 30; } else framerate= (AVRational){i, 1}; nsv->avsync = avio_rl16(pb); nsv->framerate = framerate; av_log(s, AV_LOG_TRACE, "NSV NSVs vsize %dx%d\n", vwidth, vheight); /* XXX change to ap != NULL ? */ if (s->nb_streams == 0) { /* streams not yet published, let's do that */ nsv->vtag = vtag; nsv->atag = atag; nsv->vwidth = vwidth; nsv->vheight = vwidth; if (vtag != T_NONE) { int i; st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = NSV_ST_VIDEO; nst = av_mallocz(sizeof(NSVStream)); if (!nst) goto fail; st->priv_data = nst; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_tag = vtag; st->codecpar->codec_id = ff_codec_get_id(nsv_codec_video_tags, vtag); st->codecpar->width = vwidth; st->codecpar->height = vheight; st->codecpar->bits_per_coded_sample = 24; /* depth XXX */ avpriv_set_pts_info(st, 64, framerate.den, framerate.num); st->start_time = 0; st->duration = av_rescale(nsv->duration, framerate.num, 1000*framerate.den); for(i=0;i<nsv->index_entries;i++) { if(nsv->nsvs_timestamps) { av_add_index_entry(st, nsv->nsvs_file_offset[i], nsv->nsvs_timestamps[i], 0, 0, AVINDEX_KEYFRAME); } else { int64_t ts = av_rescale(i*nsv->duration/nsv->index_entries, framerate.num, 1000*framerate.den); av_add_index_entry(st, nsv->nsvs_file_offset[i], ts, 0, 0, AVINDEX_KEYFRAME); } } } if (atag != T_NONE) { st = avformat_new_stream(s, NULL); if (!st) goto fail; st->id = NSV_ST_AUDIO; nst = av_mallocz(sizeof(NSVStream)); if (!nst) goto fail; st->priv_data = nst; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_tag = atag; st->codecpar->codec_id = ff_codec_get_id(nsv_codec_audio_tags, atag); st->need_parsing = AVSTREAM_PARSE_FULL; /* for PCM we will read a chunk later and put correct info */ /* set timebase to common denominator of ms and framerate */ avpriv_set_pts_info(st, 64, 1, framerate.num*1000); st->start_time = 0; st->duration = (int64_t)nsv->duration * framerate.num; } } else { if (nsv->vtag != vtag || nsv->atag != atag || nsv->vwidth != vwidth || nsv->vheight != vwidth) { av_log(s, AV_LOG_TRACE, "NSV NSVs header values differ from the first one!!!\n"); //return -1; } } nsv->state = NSV_HAS_READ_NSVS; return 0; fail: /* XXX */ nsv->state = NSV_UNSYNC; return -1; } static int nsv_read_header(AVFormatContext *s) { NSVContext *nsv = s->priv_data; int i, err; nsv->state = NSV_UNSYNC; nsv->ahead[0].data = nsv->ahead[1].data = NULL; for (i = 0; i < NSV_MAX_RESYNC_TRIES; i++) { if (nsv_resync(s) < 0) return -1; if (nsv->state == NSV_FOUND_NSVF) { err = nsv_parse_NSVf_header(s); if (err < 0) return err; } /* we need the first NSVs also... */ if (nsv->state == NSV_FOUND_NSVS) { err = nsv_parse_NSVs_header(s); if (err < 0) return err; break; /* we just want the first one */ } } if (s->nb_streams < 1) /* no luck so far */ return -1; /* now read the first chunk, so we can attempt to decode more info */ err = nsv_read_chunk(s, 1); av_log(s, AV_LOG_TRACE, "parsed header\n"); return err; } static int nsv_read_chunk(AVFormatContext *s, int fill_header) { NSVContext *nsv = s->priv_data; AVIOContext *pb = s->pb; AVStream *st[2] = {NULL, NULL}; NSVStream *nst; AVPacket *pkt; int i, err = 0; uint8_t auxcount; /* number of aux metadata, also 4 bits of vsize */ uint32_t vsize; uint16_t asize; uint16_t auxsize; int ret; if (nsv->ahead[0].data || nsv->ahead[1].data) return 0; //-1; /* hey! eat what you've in your plate first! */ null_chunk_retry: if (avio_feof(pb)) return -1; for (i = 0; i < NSV_MAX_RESYNC_TRIES && nsv->state < NSV_FOUND_NSVS && !err; i++) err = nsv_resync(s); if (err < 0) return err; if (nsv->state == NSV_FOUND_NSVS) err = nsv_parse_NSVs_header(s); if (err < 0) return err; if (nsv->state != NSV_HAS_READ_NSVS && nsv->state != NSV_FOUND_BEEF) return -1; auxcount = avio_r8(pb); vsize = avio_rl16(pb); asize = avio_rl16(pb); vsize = (vsize << 4) | (auxcount >> 4); auxcount &= 0x0f; av_log(s, AV_LOG_TRACE, "NSV CHUNK %d aux, %"PRIu32" bytes video, %d bytes audio\n", auxcount, vsize, asize); /* skip aux stuff */ for (i = 0; i < auxcount; i++) { uint32_t av_unused auxtag; auxsize = avio_rl16(pb); auxtag = avio_rl32(pb); avio_skip(pb, auxsize); vsize -= auxsize + sizeof(uint16_t) + sizeof(uint32_t); /* that's becoming brain-dead */ } if (avio_feof(pb)) return -1; if (!vsize && !asize) { nsv->state = NSV_UNSYNC; goto null_chunk_retry; } /* map back streams to v,a */ if (s->nb_streams > 0) st[s->streams[0]->id] = s->streams[0]; if (s->nb_streams > 1) st[s->streams[1]->id] = s->streams[1]; if (vsize && st[NSV_ST_VIDEO]) { nst = st[NSV_ST_VIDEO]->priv_data; pkt = &nsv->ahead[NSV_ST_VIDEO]; if ((ret = av_get_packet(pb, pkt, vsize)) < 0) return ret; pkt->stream_index = st[NSV_ST_VIDEO]->index;//NSV_ST_VIDEO; pkt->dts = nst->frame_offset; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ for (i = 0; i < FFMIN(8, vsize); i++) av_log(s, AV_LOG_TRACE, "NSV video: [%d] = %02x\n", i, pkt->data[i]); } if(st[NSV_ST_VIDEO]) ((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset++; if (asize && st[NSV_ST_AUDIO]) { nst = st[NSV_ST_AUDIO]->priv_data; pkt = &nsv->ahead[NSV_ST_AUDIO]; /* read raw audio specific header on the first audio chunk... */ /* on ALL audio chunks ?? seems so! */ if (asize && st[NSV_ST_AUDIO]->codecpar->codec_tag == MKTAG('P', 'C', 'M', ' ')/* && fill_header*/) { uint8_t bps; uint8_t channels; uint16_t samplerate; bps = avio_r8(pb); channels = avio_r8(pb); samplerate = avio_rl16(pb); if (!channels || !samplerate) return AVERROR_INVALIDDATA; asize-=4; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate); if (fill_header) { st[NSV_ST_AUDIO]->need_parsing = AVSTREAM_PARSE_NONE; /* we know everything */ if (bps != 16) { av_log(s, AV_LOG_TRACE, "NSV AUDIO bit/sample != 16 (%d)!!!\n", bps); } bps /= channels; // ??? if (bps == 8) st[NSV_ST_AUDIO]->codecpar->codec_id = AV_CODEC_ID_PCM_U8; samplerate /= 4;/* UGH ??? XXX */ channels = 1; st[NSV_ST_AUDIO]->codecpar->channels = channels; st[NSV_ST_AUDIO]->codecpar->sample_rate = samplerate; av_log(s, AV_LOG_TRACE, "NSV RAWAUDIO: bps %d, nchan %d, srate %d\n", bps, channels, samplerate); } } if ((ret = av_get_packet(pb, pkt, asize)) < 0) return ret; pkt->stream_index = st[NSV_ST_AUDIO]->index;//NSV_ST_AUDIO; pkt->flags |= nsv->state == NSV_HAS_READ_NSVS ? AV_PKT_FLAG_KEY : 0; /* keyframe only likely on a sync frame */ if( nsv->state == NSV_HAS_READ_NSVS && st[NSV_ST_VIDEO] ) { /* on a nsvs frame we have new information on a/v sync */ pkt->dts = (((NSVStream*)st[NSV_ST_VIDEO]->priv_data)->frame_offset-1); pkt->dts *= (int64_t)1000 * nsv->framerate.den; pkt->dts += (int64_t)nsv->avsync * nsv->framerate.num; av_log(s, AV_LOG_TRACE, "NSV AUDIO: sync:%d, dts:%"PRId64, nsv->avsync, pkt->dts); } nst->frame_offset++; } nsv->state = NSV_UNSYNC; return 0; } static int nsv_read_packet(AVFormatContext *s, AVPacket *pkt) { NSVContext *nsv = s->priv_data; int i, err = 0; /* in case we don't already have something to eat ... */ if (!nsv->ahead[0].data && !nsv->ahead[1].data) err = nsv_read_chunk(s, 0); if (err < 0) return err; /* now pick one of the plates */ for (i = 0; i < 2; i++) { if (nsv->ahead[i].data) { /* avoid the cost of new_packet + memcpy(->data) */ memcpy(pkt, &nsv->ahead[i], sizeof(AVPacket)); nsv->ahead[i].data = NULL; /* we ate that one */ return pkt->size; } } /* this restaurant is not provisioned :^] */ return -1; } static int nsv_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { NSVContext *nsv = s->priv_data; AVStream *st = s->streams[stream_index]; NSVStream *nst = st->priv_data; int index; index = av_index_search_timestamp(st, timestamp, flags); if(index < 0) return -1; if (avio_seek(s->pb, st->index_entries[index].pos, SEEK_SET) < 0) return -1; nst->frame_offset = st->index_entries[index].timestamp; nsv->state = NSV_UNSYNC; return 0; } static int nsv_read_close(AVFormatContext *s) { NSVContext *nsv = s->priv_data; av_freep(&nsv->nsvs_file_offset); av_freep(&nsv->nsvs_timestamps); if (nsv->ahead[0].data) av_packet_unref(&nsv->ahead[0]); if (nsv->ahead[1].data) av_packet_unref(&nsv->ahead[1]); return 0; } static int nsv_probe(AVProbeData *p) { int i, score = 0; /* check file header */ /* streamed files might not have any header */ if (p->buf[0] == 'N' && p->buf[1] == 'S' && p->buf[2] == 'V' && (p->buf[3] == 'f' || p->buf[3] == 's')) return AVPROBE_SCORE_MAX; /* XXX: do streamed files always start at chunk boundary ?? */ /* or do we need to search NSVs in the byte stream ? */ /* seems the servers don't bother starting clean chunks... */ /* sometimes even the first header is at 9KB or something :^) */ for (i = 1; i < p->buf_size - 3; i++) { if (AV_RL32(p->buf + i) == AV_RL32("NSVs")) { /* Get the chunk size and check if at the end we are getting 0xBEEF */ int vsize = AV_RL24(p->buf+i+19) >> 4; int asize = AV_RL16(p->buf+i+22); int offset = i + 23 + asize + vsize + 1; if (offset <= p->buf_size - 2 && AV_RL16(p->buf + offset) == 0xBEEF) return 4*AVPROBE_SCORE_MAX/5; score = AVPROBE_SCORE_MAX/5; } } /* so we'll have more luck on extension... */ if (av_match_ext(p->filename, "nsv")) return AVPROBE_SCORE_EXTENSION; /* FIXME: add mime-type check */ return score; } AVInputFormat ff_nsv_demuxer = { .name = "nsv", .long_name = NULL_IF_CONFIG_SMALL("Nullsoft Streaming Video"), .priv_data_size = sizeof(NSVContext), .read_probe = nsv_probe, .read_header = nsv_read_header, .read_packet = nsv_read_packet, .read_close = nsv_read_close, .read_seek = nsv_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2780_0
crossvul-cpp_data_good_2784_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/policy.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; break; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image, ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(option) == MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); image->matte=MagickTrue; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->matte=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if (name_length % 2 == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) return; p=PushLongPixel(MSBEndian,p,&count); if ((p+count) > (blocks+length)) return; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ if (count < 16) return; p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((count > 3) && (*(p+4) == 0)) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { PixelPacket *color; if (type == 0) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); } color=image->colormap+(ssize_t) ConstrainColormapIndex(image, GetPixelIndex(indexes+x)); if ((type == 0) && (channels > 1)) return; else SetPixelAlpha(color,pixel); SetPixelRGBO(q,color); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels < 3 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { SetPixelGreen(q,pixel); break; } case 2: { SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image,const size_t channels, const size_t row,const ssize_t type,const unsigned char *pixels, ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { mask->matte=MagickFalse; channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->matte=MagickTrue; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } (void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (EOFBlob(image) != MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickFalse); return(ReadPSDLayersInternal(image,image_info,psd_info,skip_layers, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image* image,const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if (has_merged_image != MagickFalse || GetImageListLength(image) == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { char layer_name[MaxTextExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,&image->exception) != MagickFalse)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } base_image=GetNextImageInList(image); if (base_image == (Image *)NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->matte != MagickFalse) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->matte != MagickFalse) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->matte != MagickFalse) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue, &image->exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image); property=(const char *) GetImageProperty(next_image,"label"); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,&image->exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+ mask->page.y); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+ mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0, MagickFalse) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-834/c/good_2784_0
crossvul-cpp_data_bad_2785_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % X X BBBB M M % % X X B B MM MM % % X BBBB M M M % % X X B B M M % % X X BBBB M M % % % % % % Read/Write X Windows System Bitmap Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" /* Forward declarations. */ static MagickBooleanType WriteXBMImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s X B M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsXBM() returns MagickTrue if the image format type, identified by the % magick string, is XBM. % % The format of the IsXBM method is: % % MagickBooleanType IsXBM(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsXBM(const unsigned char *magick,const size_t length) { if (length < 7) return(MagickFalse); if (memcmp(magick,"#define",7) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadXBMImage() reads an X11 bitmap image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadXBMImage method is: % % Image *ReadXBMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static unsigned int XBMInteger(Image *image,short int *hex_digits) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(0); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); /* Evaluate number. */ value=0; while (hex_digits[c] >= 0) { if (value > (unsigned int) (INT_MAX/10)) break; value*=16; c&=0xff; if (value > (unsigned int) (INT_MAX-hex_digits[c])) break; value+=hex_digits[c]; c=ReadBlobByte(image); if (c == EOF) return(0); } return(value); } static Image *ReadXBMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MaxTextExtent], name[MaxTextExtent]; Image *image; MagickBooleanType status; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; short int hex_digits[256]; ssize_t y; unsigned char *data; unsigned int bit, byte, bytes_per_line, height, length, padding, value, version, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read X bitmap header. */ width=0; height=0; while (ReadBlobString(image,buffer) != (char *) NULL) if (sscanf(buffer,"#define %32s %u",name,&width) == 2) if ((strlen(name) >= 6) && (LocaleCompare(name+strlen(name)-6,"_width") == 0)) break; while (ReadBlobString(image,buffer) != (char *) NULL) if (sscanf(buffer,"#define %32s %u",name,&height) == 2) if ((strlen(name) >= 7) && (LocaleCompare(name+strlen(name)-7,"_height") == 0)) break; image->columns=width; image->rows=height; image->depth=8; image->storage_class=PseudoClass; image->colors=2; /* Scan until hex digits. */ version=11; while (ReadBlobString(image,buffer) != (char *) NULL) { if (sscanf(buffer,"static short %32s = {",name) == 1) version=10; else if (sscanf(buffer,"static unsigned char %s = {",name) == 1) version=11; else if (sscanf(buffer,"static char %32s = {",name) == 1) version=11; else continue; p=(unsigned char *) strrchr(name,'_'); if (p == (unsigned char *) NULL) p=(unsigned char *) name; else p++; if (LocaleCompare("bits[]",(char *) p) == 0) break; } if ((image->columns == 0) || (image->rows == 0) || (EOFBlob(image) != MagickFalse)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize colormap. */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=(Quantum) 0; image->colormap[1].green=(Quantum) 0; image->colormap[1].blue=(Quantum) 0; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Initialize hex values. */ hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'x']=0; hex_digits[(int) ' ']=(-1); hex_digits[(int) ',']=(-1); hex_digits[(int) '}']=(-1); hex_digits[(int) '\n']=(-1); hex_digits[(int) '\t']=(-1); /* Read hex image data. */ padding=0; if (((image->columns % 16) != 0) && ((image->columns % 16) < 9) && (version == 10)) padding=1; bytes_per_line=(unsigned int) (image->columns+7)/8+padding; length=(unsigned int) image->rows; data=(unsigned char *) AcquireQuantumMemory(length,bytes_per_line* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; if (version == 10) for (i=0; i < (ssize_t) (bytes_per_line*image->rows); (i+=2)) { value=XBMInteger(image,hex_digits); *p++=(unsigned char) value; if ((padding == 0) || (((i+2) % bytes_per_line) != 0)) *p++=(unsigned char) (value >> 8); } else for (i=0; i < (ssize_t) (bytes_per_line*image->rows); i++) { value=XBMInteger(image,hex_digits); *p++=(unsigned char) value; } /* Convert X bitmap image to pixel packets. */ p=data; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte=(size_t) (*p++); SetPixelIndex(indexes+x,(byte & 0x01) != 0 ? 0x01 : 0x00); bit++; byte>>=1; if (bit == 8) bit=0; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } data=(unsigned char *) RelinquishMagickMemory(data); (void) SyncImage(image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterXBMImage() adds attributes for the XBM image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterXBMImage method is: % % size_t RegisterXBMImage(void) % */ ModuleExport size_t RegisterXBMImage(void) { MagickInfo *entry; entry=SetMagickInfo("XBM"); entry->decoder=(DecodeImageHandler *) ReadXBMImage; entry->encoder=(EncodeImageHandler *) WriteXBMImage; entry->magick=(IsImageFormatHandler *) IsXBM; entry->adjoin=MagickFalse; entry->description=ConstantString( "X Windows system bitmap (black and white)"); entry->module=ConstantString("XBM"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterXBMImage() removes format registrations made by the % XBM module from the list of supported formats. % % The format of the UnregisterXBMImage method is: % % UnregisterXBMImage(void) % */ ModuleExport void UnregisterXBMImage(void) { (void) UnregisterMagickInfo("XBM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Procedure WriteXBMImage() writes an image to a file in the X bitmap format. % % The format of the WriteXBMImage method is: % % MagickBooleanType WriteXBMImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % */ static MagickBooleanType WriteXBMImage(const ImageInfo *image_info,Image *image) { char basename[MaxTextExtent], buffer[MaxTextExtent]; MagickBooleanType status; register const PixelPacket *p; register ssize_t x; size_t bit, byte; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Write X bitmap header. */ GetPathComponent(image->filename,BasePath,basename); (void) FormatLocaleString(buffer,MaxTextExtent,"#define %s_width %.20g\n", basename,(double) image->columns); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"#define %s_height %.20g\n", basename,(double) image->rows); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "static char %s_bits[] = {\n",basename); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) CopyMagickString(buffer," ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); /* Convert MIFF to X bitmap pixels. */ (void) SetImageType(image,BilevelType); bit=0; byte=0; count=0; x=0; y=0; (void) CopyMagickString(buffer," ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x80; bit++; if (bit == 8) { /* Write a bitmap byte to the image file. */ (void) FormatLocaleString(buffer,MaxTextExtent,"0x%02X, ", (unsigned int) (byte & 0xff)); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count++; if (count == 12) { (void) CopyMagickString(buffer,"\n ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count=0; }; bit=0; byte=0; } p++; } if (bit != 0) { /* Write a bitmap byte to the image file. */ byte>>=(8-bit); (void) FormatLocaleString(buffer,MaxTextExtent,"0x%02X, ", (unsigned int) (byte & 0xff)); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count++; if (count == 12) { (void) CopyMagickString(buffer,"\n ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count=0; }; bit=0; byte=0; }; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) CopyMagickString(buffer,"};\n",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2785_0
crossvul-cpp_data_good_2764_0
/* * ASF compatible demuxer * Copyright (c) 2000, 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "libavutil/attributes.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/bswap.h" #include "libavutil/common.h" #include "libavutil/dict.h" #include "libavutil/internal.h" #include "libavutil/mathematics.h" #include "libavutil/opt.h" #include "avformat.h" #include "avio_internal.h" #include "avlanguage.h" #include "id3v2.h" #include "internal.h" #include "riff.h" #include "asf.h" #include "asfcrypt.h" typedef struct ASFPayload { uint8_t type; uint16_t size; } ASFPayload; typedef struct ASFStream { int num; unsigned char seq; /* use for reading */ AVPacket pkt; int frag_offset; int packet_obj_size; int timestamp; int64_t duration; int skip_to_key; int pkt_clean; int ds_span; /* descrambling */ int ds_packet_size; int ds_chunk_size; int64_t packet_pos; uint16_t stream_language_index; int palette_changed; uint32_t palette[256]; int payload_ext_ct; ASFPayload payload[8]; } ASFStream; typedef struct ASFContext { const AVClass *class; int asfid2avid[128]; ///< conversion table from asf ID 2 AVStream ID ASFStream streams[128]; ///< it's max number and it's not that big uint32_t stream_bitrates[128]; ///< max number of streams, bitrate for each (for streaming) AVRational dar[128]; char stream_languages[128][6]; ///< max number of streams, language for each (RFC1766, e.g. en-US) /* non streamed additonnal info */ /* packet filling */ int packet_size_left; /* only for reading */ uint64_t data_offset; ///< beginning of the first data packet uint64_t data_object_offset; ///< data object offset (excl. GUID & size) uint64_t data_object_size; ///< size of the data object int index_read; ASFMainHeader hdr; int packet_flags; int packet_property; int packet_timestamp; int packet_segsizetype; int packet_segments; int packet_seq; int packet_replic_size; int packet_key_frame; int packet_padsize; unsigned int packet_frag_offset; unsigned int packet_frag_size; int64_t packet_frag_timestamp; int ts_is_pts; int packet_multi_size; int packet_time_delta; int packet_time_start; int64_t packet_pos; int stream_index; ASFStream *asf_st; ///< currently decoded stream int no_resync_search; int export_xmp; int uses_std_ecc; } ASFContext; static const AVOption options[] = { { "no_resync_search", "Don't try to resynchronize by looking for a certain optional start code", offsetof(ASFContext, no_resync_search), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM }, { "export_xmp", "Export full XMP metadata", offsetof(ASFContext, export_xmp), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM }, { NULL }, }; static const AVClass asf_class = { .class_name = "asf demuxer", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; #undef NDEBUG #include <assert.h> #define ASF_MAX_STREAMS 127 #define FRAME_HEADER_SIZE 6 // Fix Me! FRAME_HEADER_SIZE may be different. // (7 is known to be too large for GipsyGuitar.wmv) #ifdef DEBUG static const ff_asf_guid stream_bitrate_guid = { /* (http://get.to/sdp) */ 0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2 }; #define PRINT_IF_GUID(g, cmp) \ if (!ff_guidcmp(g, &cmp)) \ av_log(NULL, AV_LOG_TRACE, "(GUID: %s) ", # cmp) static void print_guid(ff_asf_guid *g) { int i; PRINT_IF_GUID(g, ff_asf_header); else PRINT_IF_GUID(g, ff_asf_file_header); else PRINT_IF_GUID(g, ff_asf_stream_header); else PRINT_IF_GUID(g, ff_asf_audio_stream); else PRINT_IF_GUID(g, ff_asf_audio_conceal_none); else PRINT_IF_GUID(g, ff_asf_video_stream); else PRINT_IF_GUID(g, ff_asf_video_conceal_none); else PRINT_IF_GUID(g, ff_asf_command_stream); else PRINT_IF_GUID(g, ff_asf_comment_header); else PRINT_IF_GUID(g, ff_asf_codec_comment_header); else PRINT_IF_GUID(g, ff_asf_codec_comment1_header); else PRINT_IF_GUID(g, ff_asf_data_header); else PRINT_IF_GUID(g, ff_asf_simple_index_header); else PRINT_IF_GUID(g, ff_asf_head1_guid); else PRINT_IF_GUID(g, ff_asf_head2_guid); else PRINT_IF_GUID(g, ff_asf_my_guid); else PRINT_IF_GUID(g, ff_asf_ext_stream_header); else PRINT_IF_GUID(g, ff_asf_extended_content_header); else PRINT_IF_GUID(g, ff_asf_ext_stream_embed_stream_header); else PRINT_IF_GUID(g, ff_asf_ext_stream_audio_stream); else PRINT_IF_GUID(g, ff_asf_metadata_header); else PRINT_IF_GUID(g, ff_asf_metadata_library_header); else PRINT_IF_GUID(g, ff_asf_marker_header); else PRINT_IF_GUID(g, stream_bitrate_guid); else PRINT_IF_GUID(g, ff_asf_language_guid); else av_log(NULL, AV_LOG_TRACE, "(GUID: unknown) "); for (i = 0; i < 16; i++) av_log(NULL, AV_LOG_TRACE, " 0x%02x,", (*g)[i]); av_log(NULL, AV_LOG_TRACE, "}\n"); } #undef PRINT_IF_GUID #else #define print_guid(g) while(0) #endif static int asf_probe(AVProbeData *pd) { /* check file header */ if (!ff_guidcmp(pd->buf, &ff_asf_header)) return AVPROBE_SCORE_MAX; else return 0; } /* size of type 2 (BOOL) is 32bit for "Extended Content Description Object" * but 16 bit for "Metadata Object" and "Metadata Library Object" */ static int get_value(AVIOContext *pb, int type, int type2_size) { switch (type) { case 2: return (type2_size == 32) ? avio_rl32(pb) : avio_rl16(pb); case 3: return avio_rl32(pb); case 4: return avio_rl64(pb); case 5: return avio_rl16(pb); default: return INT_MIN; } } /* MSDN claims that this should be "compatible with the ID3 frame, APIC", * but in reality this is only loosely similar */ static int asf_read_picture(AVFormatContext *s, int len) { AVPacket pkt = { 0 }; const CodecMime *mime = ff_id3v2_mime_tags; enum AVCodecID id = AV_CODEC_ID_NONE; char mimetype[64]; uint8_t *desc = NULL; AVStream *st = NULL; int ret, type, picsize, desc_len; /* type + picsize + mime + desc */ if (len < 1 + 4 + 2 + 2) { av_log(s, AV_LOG_ERROR, "Invalid attached picture size: %d.\n", len); return AVERROR_INVALIDDATA; } /* picture type */ type = avio_r8(s->pb); len--; if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) { av_log(s, AV_LOG_WARNING, "Unknown attached picture type: %d.\n", type); type = 0; } /* picture data size */ picsize = avio_rl32(s->pb); len -= 4; /* picture MIME type */ len -= avio_get_str16le(s->pb, len, mimetype, sizeof(mimetype)); while (mime->id != AV_CODEC_ID_NONE) { if (!strncmp(mime->str, mimetype, sizeof(mimetype))) { id = mime->id; break; } mime++; } if (id == AV_CODEC_ID_NONE) { av_log(s, AV_LOG_ERROR, "Unknown attached picture mimetype: %s.\n", mimetype); return 0; } if (picsize >= len) { av_log(s, AV_LOG_ERROR, "Invalid attached picture data size: %d >= %d.\n", picsize, len); return AVERROR_INVALIDDATA; } /* picture description */ desc_len = (len - picsize) * 2 + 1; desc = av_malloc(desc_len); if (!desc) return AVERROR(ENOMEM); len -= avio_get_str16le(s->pb, len - picsize, desc, desc_len); ret = av_get_packet(s->pb, &pkt, picsize); if (ret < 0) goto fail; st = avformat_new_stream(s, NULL); if (!st) { ret = AVERROR(ENOMEM); goto fail; } st->disposition |= AV_DISPOSITION_ATTACHED_PIC; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = id; st->attached_pic = pkt; st->attached_pic.stream_index = st->index; st->attached_pic.flags |= AV_PKT_FLAG_KEY; if (*desc) av_dict_set(&st->metadata, "title", desc, AV_DICT_DONT_STRDUP_VAL); else av_freep(&desc); av_dict_set(&st->metadata, "comment", ff_id3v2_picture_types[type], 0); return 0; fail: av_freep(&desc); av_packet_unref(&pkt); return ret; } static void get_id3_tag(AVFormatContext *s, int len) { ID3v2ExtraMeta *id3v2_extra_meta = NULL; ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, len); if (id3v2_extra_meta) ff_id3v2_parse_apic(s, &id3v2_extra_meta); ff_id3v2_free_extra_meta(&id3v2_extra_meta); } static void get_tag(AVFormatContext *s, const char *key, int type, int len, int type2_size) { ASFContext *asf = s->priv_data; char *value = NULL; int64_t off = avio_tell(s->pb); #define LEN 22 if ((unsigned)len >= (UINT_MAX - LEN) / 2) return; if (!asf->export_xmp && !strncmp(key, "xmp", 3)) goto finish; value = av_malloc(2 * len + LEN); if (!value) goto finish; switch (type) { case ASF_UNICODE: avio_get_str16le(s->pb, len, value, 2 * len + 1); break; case -1: // ASCI avio_read(s->pb, value, len); value[len]=0; break; case ASF_BYTE_ARRAY: if (!strcmp(key, "WM/Picture")) { // handle cover art asf_read_picture(s, len); } else if (!strcmp(key, "ID3")) { // handle ID3 tag get_id3_tag(s, len); } else { av_log(s, AV_LOG_VERBOSE, "Unsupported byte array in tag %s.\n", key); } goto finish; case ASF_BOOL: case ASF_DWORD: case ASF_QWORD: case ASF_WORD: { uint64_t num = get_value(s->pb, type, type2_size); snprintf(value, LEN, "%"PRIu64, num); break; } case ASF_GUID: av_log(s, AV_LOG_DEBUG, "Unsupported GUID value in tag %s.\n", key); goto finish; default: av_log(s, AV_LOG_DEBUG, "Unsupported value type %d in tag %s.\n", type, key); goto finish; } if (*value) av_dict_set(&s->metadata, key, value, 0); finish: av_freep(&value); avio_seek(s->pb, off + len, SEEK_SET); } static int asf_read_file_properties(AVFormatContext *s, int64_t size) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; ff_get_guid(pb, &asf->hdr.guid); asf->hdr.file_size = avio_rl64(pb); asf->hdr.create_time = avio_rl64(pb); avio_rl64(pb); /* number of packets */ asf->hdr.play_time = avio_rl64(pb); asf->hdr.send_time = avio_rl64(pb); asf->hdr.preroll = avio_rl32(pb); asf->hdr.ignore = avio_rl32(pb); asf->hdr.flags = avio_rl32(pb); asf->hdr.min_pktsize = avio_rl32(pb); asf->hdr.max_pktsize = avio_rl32(pb); if (asf->hdr.min_pktsize >= (1U << 29)) return AVERROR_INVALIDDATA; asf->hdr.max_bitrate = avio_rl32(pb); s->packet_size = asf->hdr.max_pktsize; return 0; } static int asf_read_stream_properties(AVFormatContext *s, int64_t size) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; AVStream *st; ASFStream *asf_st; ff_asf_guid g; enum AVMediaType type; int type_specific_size, sizeX; unsigned int tag1; int64_t pos1, pos2, start_time; int test_for_ext_stream_audio, is_dvr_ms_audio = 0; if (s->nb_streams == ASF_MAX_STREAMS) { av_log(s, AV_LOG_ERROR, "too many streams\n"); return AVERROR(EINVAL); } pos1 = avio_tell(pb); st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */ start_time = asf->hdr.preroll; if (!(asf->hdr.flags & 0x01)) { // if we aren't streaming... int64_t fsize = avio_size(pb); if (fsize <= 0 || (int64_t)asf->hdr.file_size <= 0 || 20*FFABS(fsize - (int64_t)asf->hdr.file_size) < FFMIN(fsize, asf->hdr.file_size)) st->duration = asf->hdr.play_time / (10000000 / 1000) - start_time; } ff_get_guid(pb, &g); test_for_ext_stream_audio = 0; if (!ff_guidcmp(&g, &ff_asf_audio_stream)) { type = AVMEDIA_TYPE_AUDIO; } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) { type = AVMEDIA_TYPE_VIDEO; } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) { type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_MJPEG; } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) { type = AVMEDIA_TYPE_DATA; } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) { test_for_ext_stream_audio = 1; type = AVMEDIA_TYPE_UNKNOWN; } else { return -1; } ff_get_guid(pb, &g); avio_skip(pb, 8); /* total_size */ type_specific_size = avio_rl32(pb); avio_rl32(pb); st->id = avio_rl16(pb) & 0x7f; /* stream id */ // mapping of asf ID to AV stream ID; asf->asfid2avid[st->id] = s->nb_streams - 1; asf_st = &asf->streams[st->id]; avio_rl32(pb); if (test_for_ext_stream_audio) { ff_get_guid(pb, &g); if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) { type = AVMEDIA_TYPE_AUDIO; is_dvr_ms_audio = 1; ff_get_guid(pb, &g); avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); ff_get_guid(pb, &g); avio_rl32(pb); } } st->codecpar->codec_type = type; if (type == AVMEDIA_TYPE_AUDIO) { int ret = ff_get_wav_header(s, pb, st->codecpar, type_specific_size, 0); if (ret < 0) return ret; if (is_dvr_ms_audio) { // codec_id and codec_tag are unreliable in dvr_ms // files. Set them later by probing stream. st->request_probe = 1; st->codecpar->codec_tag = 0; } if (st->codecpar->codec_id == AV_CODEC_ID_AAC) st->need_parsing = AVSTREAM_PARSE_NONE; else st->need_parsing = AVSTREAM_PARSE_FULL; /* We have to init the frame size at some point .... */ pos2 = avio_tell(pb); if (size >= (pos2 + 8 - pos1 + 24)) { asf_st->ds_span = avio_r8(pb); asf_st->ds_packet_size = avio_rl16(pb); asf_st->ds_chunk_size = avio_rl16(pb); avio_rl16(pb); // ds_data_size avio_r8(pb); // ds_silence_data } if (asf_st->ds_span > 1) { if (!asf_st->ds_chunk_size || (asf_st->ds_packet_size / asf_st->ds_chunk_size <= 1) || asf_st->ds_packet_size % asf_st->ds_chunk_size) asf_st->ds_span = 0; // disable descrambling } } else if (type == AVMEDIA_TYPE_VIDEO && size - (avio_tell(pb) - pos1 + 24) >= 51) { avio_rl32(pb); avio_rl32(pb); avio_r8(pb); avio_rl16(pb); /* size */ sizeX = avio_rl32(pb); /* size */ st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); /* not available for asf */ avio_rl16(pb); /* panes */ st->codecpar->bits_per_coded_sample = avio_rl16(pb); /* depth */ tag1 = avio_rl32(pb); avio_skip(pb, 20); if (sizeX > 40) { st->codecpar->extradata_size = ffio_limit(pb, sizeX - 40); st->codecpar->extradata = av_mallocz(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size); } /* Extract palette from extradata if bpp <= 8 */ /* This code assumes that extradata contains only palette */ /* This is true for all paletted codecs implemented in libavcodec */ if (st->codecpar->extradata_size && (st->codecpar->bits_per_coded_sample <= 8)) { #if HAVE_BIGENDIAN int i; for (i = 0; i < FFMIN(st->codecpar->extradata_size, AVPALETTE_SIZE) / 4; i++) asf_st->palette[i] = av_bswap32(((uint32_t *)st->codecpar->extradata)[i]); #else memcpy(asf_st->palette, st->codecpar->extradata, FFMIN(st->codecpar->extradata_size, AVPALETTE_SIZE)); #endif asf_st->palette_changed = 1; } st->codecpar->codec_tag = tag1; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1); if (tag1 == MKTAG('D', 'V', 'R', ' ')) { st->need_parsing = AVSTREAM_PARSE_FULL; /* issue658 contains wrong w/h and MS even puts a fake seq header * with wrong w/h in extradata while a correct one is in the stream. * maximum lameness */ st->codecpar->width = st->codecpar->height = 0; av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = 0; } if (st->codecpar->codec_id == AV_CODEC_ID_H264) st->need_parsing = AVSTREAM_PARSE_FULL_ONCE; if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) st->need_parsing = AVSTREAM_PARSE_FULL_ONCE; } pos2 = avio_tell(pb); avio_skip(pb, size - (pos2 - pos1 + 24)); return 0; } static int asf_read_ext_stream_properties(AVFormatContext *s, int64_t size) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; ff_asf_guid g; int ext_len, payload_ext_ct, stream_ct, i; uint32_t leak_rate, stream_num; unsigned int stream_languageid_index; avio_rl64(pb); // starttime avio_rl64(pb); // endtime leak_rate = avio_rl32(pb); // leak-datarate avio_rl32(pb); // bucket-datasize avio_rl32(pb); // init-bucket-fullness avio_rl32(pb); // alt-leak-datarate avio_rl32(pb); // alt-bucket-datasize avio_rl32(pb); // alt-init-bucket-fullness avio_rl32(pb); // max-object-size avio_rl32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved) stream_num = avio_rl16(pb); // stream-num stream_languageid_index = avio_rl16(pb); // stream-language-id-index if (stream_num < 128) asf->streams[stream_num].stream_language_index = stream_languageid_index; avio_rl64(pb); // avg frametime in 100ns units stream_ct = avio_rl16(pb); // stream-name-count payload_ext_ct = avio_rl16(pb); // payload-extension-system-count if (stream_num < 128) { asf->stream_bitrates[stream_num] = leak_rate; asf->streams[stream_num].payload_ext_ct = 0; } for (i = 0; i < stream_ct; i++) { avio_rl16(pb); ext_len = avio_rl16(pb); avio_skip(pb, ext_len); } for (i = 0; i < payload_ext_ct; i++) { int size; ff_get_guid(pb, &g); size = avio_rl16(pb); ext_len = avio_rl32(pb); avio_skip(pb, ext_len); if (stream_num < 128 && i < FF_ARRAY_ELEMS(asf->streams[stream_num].payload)) { ASFPayload *p = &asf->streams[stream_num].payload[i]; p->type = g[0]; p->size = size; av_log(s, AV_LOG_DEBUG, "Payload extension %x %d\n", g[0], p->size ); asf->streams[stream_num].payload_ext_ct ++; } } return 0; } static int asf_read_content_desc(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; int len1, len2, len3, len4, len5; len1 = avio_rl16(pb); len2 = avio_rl16(pb); len3 = avio_rl16(pb); len4 = avio_rl16(pb); len5 = avio_rl16(pb); get_tag(s, "title", 0, len1, 32); get_tag(s, "author", 0, len2, 32); get_tag(s, "copyright", 0, len3, 32); get_tag(s, "comment", 0, len4, 32); avio_skip(pb, len5); return 0; } static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int desc_count, i, ret; desc_count = avio_rl16(pb); for (i = 0; i < desc_count; i++) { int name_len, value_type, value_len; char name[1024]; name_len = avio_rl16(pb); if (name_len % 2) // must be even, broken lavf versions wrote len-1 name_len += 1; if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len) avio_skip(pb, name_len - ret); value_type = avio_rl16(pb); value_len = avio_rl16(pb); if (!value_type && value_len % 2) value_len += 1; /* My sample has that stream set to 0 maybe that mean the container. * ASF stream count starts at 1. I am using 0 to the container value * since it's unused. */ if (!strcmp(name, "AspectRatioX")) asf->dar[0].num = get_value(s->pb, value_type, 32); else if (!strcmp(name, "AspectRatioY")) asf->dar[0].den = get_value(s->pb, value_type, 32); else get_tag(s, name, value_type, value_len, 32); } return 0; } static int asf_read_language_list(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int j, ret; int stream_count = avio_rl16(pb); for (j = 0; j < stream_count; j++) { char lang[6]; unsigned int lang_len = avio_r8(pb); if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len) avio_skip(pb, lang_len - ret); if (j < 128) av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages)); } return 0; } static int asf_read_metadata(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int n, stream_num, name_len_utf16, name_len_utf8, value_len; int ret, i; n = avio_rl16(pb); for (i = 0; i < n; i++) { uint8_t *name; int value_type; avio_rl16(pb); // lang_list_index stream_num = avio_rl16(pb); name_len_utf16 = avio_rl16(pb); value_type = avio_rl16(pb); /* value_type */ value_len = avio_rl32(pb); name_len_utf8 = 2*name_len_utf16 + 1; name = av_malloc(name_len_utf8); if (!name) return AVERROR(ENOMEM); if ((ret = avio_get_str16le(pb, name_len_utf16, name, name_len_utf8)) < name_len_utf16) avio_skip(pb, name_len_utf16 - ret); av_log(s, AV_LOG_TRACE, "%d stream %d name_len %2d type %d len %4d <%s>\n", i, stream_num, name_len_utf16, value_type, value_len, name); if (!strcmp(name, "AspectRatioX")){ int aspect_x = get_value(s->pb, value_type, 16); if(stream_num < 128) asf->dar[stream_num].num = aspect_x; } else if(!strcmp(name, "AspectRatioY")){ int aspect_y = get_value(s->pb, value_type, 16); if(stream_num < 128) asf->dar[stream_num].den = aspect_y; } else { get_tag(s, name, value_type, value_len, 16); } av_freep(&name); } return 0; } static int asf_read_marker(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int i, count, name_len, ret; char name[1024]; avio_rl64(pb); // reserved 16 bytes avio_rl64(pb); // ... count = avio_rl32(pb); // markers count avio_rl16(pb); // reserved 2 bytes name_len = avio_rl16(pb); // name length avio_skip(pb, name_len); for (i = 0; i < count; i++) { int64_t pres_time; int name_len; if (avio_feof(pb)) return AVERROR_INVALIDDATA; avio_rl64(pb); // offset, 8 bytes pres_time = avio_rl64(pb); // presentation time pres_time -= asf->hdr.preroll * 10000; avio_rl16(pb); // entry length avio_rl32(pb); // send time avio_rl32(pb); // flags name_len = avio_rl32(pb); // name length if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len) avio_skip(pb, name_len - ret); avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time, AV_NOPTS_VALUE, name); } return 0; } static int asf_read_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; ff_asf_guid g; AVIOContext *pb = s->pb; int i; int64_t gsize; ff_get_guid(pb, &g); if (ff_guidcmp(&g, &ff_asf_header)) return AVERROR_INVALIDDATA; avio_rl64(pb); avio_rl32(pb); avio_r8(pb); avio_r8(pb); memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid)); for (i = 0; i<128; i++) asf->streams[i].stream_language_index = 128; // invalid stream index means no language info for (;;) { uint64_t gpos = avio_tell(pb); int ret = 0; ff_get_guid(pb, &g); gsize = avio_rl64(pb); print_guid(&g); if (!ff_guidcmp(&g, &ff_asf_data_header)) { asf->data_object_offset = avio_tell(pb); /* If not streaming, gsize is not unlimited (how?), * and there is enough space in the file.. */ if (!(asf->hdr.flags & 0x01) && gsize >= 100) asf->data_object_size = gsize - 24; else asf->data_object_size = (uint64_t)-1; break; } if (gsize < 24) return AVERROR_INVALIDDATA; if (!ff_guidcmp(&g, &ff_asf_file_header)) { ret = asf_read_file_properties(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) { ret = asf_read_stream_properties(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) { asf_read_content_desc(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) { asf_read_language_list(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) { asf_read_ext_content_desc(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) { asf_read_metadata(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_metadata_library_header)) { asf_read_metadata(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) { asf_read_ext_stream_properties(s, gsize); // there could be an optional stream properties object to follow // if so the next iteration will pick it up continue; } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) { ff_get_guid(pb, &g); avio_skip(pb, 6); continue; } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) { asf_read_marker(s, gsize); } else if (avio_feof(pb)) { return AVERROR_EOF; } else { if (!s->keylen) { if (!ff_guidcmp(&g, &ff_asf_content_encryption)) { unsigned int len; AVPacket pkt; av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n"); len= avio_rl32(pb); av_log(s, AV_LOG_DEBUG, "Secret data:\n"); if ((ret = av_get_packet(pb, &pkt, len)) < 0) return ret; av_hex_dump_log(s, AV_LOG_DEBUG, pkt.data, pkt.size); av_packet_unref(&pkt); len= avio_rl32(pb); get_tag(s, "ASF_Protection_Type", -1, len, 32); len= avio_rl32(pb); get_tag(s, "ASF_Key_ID", -1, len, 32); len= avio_rl32(pb); get_tag(s, "ASF_License_URL", -1, len, 32); } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) { av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n"); av_dict_set(&s->metadata, "encryption", "ASF Extended Content Encryption", 0); } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) { av_log(s, AV_LOG_INFO, "Digital signature detected!\n"); } } } if (ret < 0) return ret; if (avio_tell(pb) != gpos + gsize) av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRId64"\n", avio_tell(pb) - gpos, gsize); avio_seek(pb, gpos + gsize, SEEK_SET); } ff_get_guid(pb, &g); avio_rl64(pb); avio_r8(pb); avio_r8(pb); if (avio_feof(pb)) return AVERROR_EOF; asf->data_offset = avio_tell(pb); asf->packet_size_left = 0; for (i = 0; i < 128; i++) { int stream_num = asf->asfid2avid[i]; if (stream_num >= 0) { AVStream *st = s->streams[stream_num]; if (!st->codecpar->bit_rate) st->codecpar->bit_rate = asf->stream_bitrates[i]; if (asf->dar[i].num > 0 && asf->dar[i].den > 0) { av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, asf->dar[i].num, asf->dar[i].den, INT_MAX); } else if ((asf->dar[0].num > 0) && (asf->dar[0].den > 0) && // Use ASF container value if the stream doesn't set AR. (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, asf->dar[0].num, asf->dar[0].den, INT_MAX); av_log(s, AV_LOG_TRACE, "i=%d, st->codecpar->codec_type:%d, asf->dar %d:%d sar=%d:%d\n", i, st->codecpar->codec_type, asf->dar[i].num, asf->dar[i].den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den); // copy and convert language codes to the frontend if (asf->streams[i].stream_language_index < 128) { const char *rfc1766 = asf->stream_languages[asf->streams[i].stream_language_index]; if (rfc1766 && strlen(rfc1766) > 1) { const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any const char *iso6392 = ff_convert_lang_to(primary_tag, AV_LANG_ISO639_2_BIBL); if (iso6392) av_dict_set(&st->metadata, "language", iso6392, 0); } } } } ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv); return 0; } #define DO_2BITS(bits, var, defval) \ switch (bits & 3) { \ case 3: \ var = avio_rl32(pb); \ rsize += 4; \ break; \ case 2: \ var = avio_rl16(pb); \ rsize += 2; \ break; \ case 1: \ var = avio_r8(pb); \ rsize++; \ break; \ default: \ var = defval; \ break; \ } /** * Load a single ASF packet into the demuxer. * @param s demux context * @param pb context to read data from * @return 0 on success, <0 on error */ static int asf_get_packet(AVFormatContext *s, AVIOContext *pb) { ASFContext *asf = s->priv_data; uint32_t packet_length, padsize; int rsize = 8; int c, d, e, off; if (asf->uses_std_ecc > 0) { // if we do not know packet size, allow skipping up to 32 kB off = 32768; if (asf->no_resync_search) off = 3; // else if (s->packet_size > 0 && !asf->uses_std_ecc) // off = (avio_tell(pb) - s->internal->data_offset) % s->packet_size + 3; c = d = e = -1; while (off-- > 0) { c = d; d = e; e = avio_r8(pb); if (c == 0x82 && !d && !e) break; } if (c != 0x82) { /* This code allows handling of -EAGAIN at packet boundaries (i.e. * if the packet sync code above triggers -EAGAIN). This does not * imply complete -EAGAIN handling support at random positions in * the stream. */ if (pb->error == AVERROR(EAGAIN)) return AVERROR(EAGAIN); if (!avio_feof(pb)) av_log(s, AV_LOG_ERROR, "ff asf bad header %x at:%"PRId64"\n", c, avio_tell(pb)); } if ((c & 0x8f) == 0x82) { if (d || e) { if (!avio_feof(pb)) av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n"); return AVERROR_INVALIDDATA; } c = avio_r8(pb); d = avio_r8(pb); rsize += 3; } else if(!avio_feof(pb)) { avio_seek(pb, -1, SEEK_CUR); // FIXME } } else { c = avio_r8(pb); if (c & 0x80) { rsize ++; if (!(c & 0x60)) { d = avio_r8(pb); e = avio_r8(pb); avio_seek(pb, (c & 0xF) - 2, SEEK_CUR); rsize += c & 0xF; } if (c != 0x82) avpriv_request_sample(s, "Invalid ECC byte"); if (!asf->uses_std_ecc) asf->uses_std_ecc = (c == 0x82 && !d && !e) ? 1 : -1; c = avio_r8(pb); } else asf->uses_std_ecc = -1; d = avio_r8(pb); } asf->packet_flags = c; asf->packet_property = d; DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size); DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length // the following checks prevent overflows and infinite loops if (!packet_length || packet_length >= (1U << 29)) { av_log(s, AV_LOG_ERROR, "invalid packet_length %"PRIu32" at:%"PRId64"\n", packet_length, avio_tell(pb)); return AVERROR_INVALIDDATA; } if (padsize >= packet_length) { av_log(s, AV_LOG_ERROR, "invalid padsize %"PRIu32" at:%"PRId64"\n", padsize, avio_tell(pb)); return AVERROR_INVALIDDATA; } asf->packet_timestamp = avio_rl32(pb); avio_rl16(pb); /* duration */ // rsize has at least 11 bytes which have to be present if (asf->packet_flags & 0x01) { asf->packet_segsizetype = avio_r8(pb); rsize++; asf->packet_segments = asf->packet_segsizetype & 0x3f; } else { asf->packet_segments = 1; asf->packet_segsizetype = 0x80; } if (rsize > packet_length - padsize) { asf->packet_size_left = 0; av_log(s, AV_LOG_ERROR, "invalid packet header length %d for pktlen %"PRIu32"-%"PRIu32" at %"PRId64"\n", rsize, packet_length, padsize, avio_tell(pb)); return AVERROR_INVALIDDATA; } asf->packet_size_left = packet_length - padsize - rsize; if (packet_length < asf->hdr.min_pktsize) padsize += asf->hdr.min_pktsize - packet_length; asf->packet_padsize = padsize; av_log(s, AV_LOG_TRACE, "packet: size=%d padsize=%d left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left); return 0; } /** * * @return <0 if error */ static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb) { ASFContext *asf = s->priv_data; ASFStream *asfst; int rsize = 1; int num = avio_r8(pb); int i; int64_t ts0, ts1 av_unused; asf->packet_segments--; asf->packet_key_frame = num >> 7; asf->stream_index = asf->asfid2avid[num & 0x7f]; asfst = &asf->streams[num & 0x7f]; // sequence should be ignored! DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0); DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0); DO_2BITS(asf->packet_property, asf->packet_replic_size, 0); av_log(asf, AV_LOG_TRACE, "key:%d stream:%d seq:%d offset:%d replic_size:%d num:%X packet_property %X\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, asf->packet_frag_offset, asf->packet_replic_size, num, asf->packet_property); if (rsize+(int64_t)asf->packet_replic_size > asf->packet_size_left) { av_log(s, AV_LOG_ERROR, "packet_replic_size %d is invalid\n", asf->packet_replic_size); return AVERROR_INVALIDDATA; } if (asf->packet_replic_size >= 8) { int64_t end = avio_tell(pb) + asf->packet_replic_size; AVRational aspect; asfst->packet_obj_size = avio_rl32(pb); if (asfst->packet_obj_size >= (1 << 24) || asfst->packet_obj_size < 0) { av_log(s, AV_LOG_ERROR, "packet_obj_size %d invalid\n", asfst->packet_obj_size); asfst->packet_obj_size = 0; return AVERROR_INVALIDDATA; } asf->packet_frag_timestamp = avio_rl32(pb); // timestamp for (i = 0; i < asfst->payload_ext_ct; i++) { ASFPayload *p = &asfst->payload[i]; int size = p->size; int64_t payend; if (size == 0xFFFF) size = avio_rl16(pb); payend = avio_tell(pb) + size; if (payend > end) { av_log(s, AV_LOG_ERROR, "too long payload\n"); break; } switch (p->type) { case 0x50: // duration = avio_rl16(pb); break; case 0x54: aspect.num = avio_r8(pb); aspect.den = avio_r8(pb); if (aspect.num > 0 && aspect.den > 0 && asf->stream_index >= 0) { s->streams[asf->stream_index]->sample_aspect_ratio = aspect; } break; case 0x2A: avio_skip(pb, 8); ts0 = avio_rl64(pb); ts1 = avio_rl64(pb); if (ts0!= -1) asf->packet_frag_timestamp = ts0/10000; else asf->packet_frag_timestamp = AV_NOPTS_VALUE; asf->ts_is_pts = 1; break; case 0x5B: case 0xB7: case 0xCC: case 0xC0: case 0xA0: //unknown break; } avio_seek(pb, payend, SEEK_SET); } avio_seek(pb, end, SEEK_SET); rsize += asf->packet_replic_size; // FIXME - check validity } else if (asf->packet_replic_size == 1) { // multipacket - frag_offset is beginning timestamp asf->packet_time_start = asf->packet_frag_offset; asf->packet_frag_offset = 0; asf->packet_frag_timestamp = asf->packet_timestamp; asf->packet_time_delta = avio_r8(pb); rsize++; } else if (asf->packet_replic_size != 0) { av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n", asf->packet_replic_size); return AVERROR_INVALIDDATA; } if (asf->packet_flags & 0x01) { DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal if (rsize > asf->packet_size_left) { av_log(s, AV_LOG_ERROR, "packet_replic_size is invalid\n"); return AVERROR_INVALIDDATA; } else if (asf->packet_frag_size > asf->packet_size_left - rsize) { if (asf->packet_frag_size > asf->packet_size_left - rsize + asf->packet_padsize) { av_log(s, AV_LOG_ERROR, "packet_frag_size is invalid (%d>%d-%d+%d)\n", asf->packet_frag_size, asf->packet_size_left, rsize, asf->packet_padsize); return AVERROR_INVALIDDATA; } else { int diff = asf->packet_frag_size - (asf->packet_size_left - rsize); asf->packet_size_left += diff; asf->packet_padsize -= diff; } } } else { asf->packet_frag_size = asf->packet_size_left - rsize; } if (asf->packet_replic_size == 1) { asf->packet_multi_size = asf->packet_frag_size; if (asf->packet_multi_size > asf->packet_size_left) return AVERROR_INVALIDDATA; } asf->packet_size_left -= rsize; return 0; } /** * Parse data from individual ASF packets (which were previously loaded * with asf_get_packet()). * @param s demux context * @param pb context to read data from * @param pkt pointer to store packet data into * @return 0 if data was stored in pkt, <0 on error or 1 if more ASF * packets need to be loaded (through asf_get_packet()) */ static int asf_parse_packet(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt) { ASFContext *asf = s->priv_data; ASFStream *asf_st = 0; for (;;) { int ret; if (avio_feof(pb)) return AVERROR_EOF; if (asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1 && asf->packet_time_start == 0) { int ret = asf->packet_size_left + asf->packet_padsize; if (asf->packet_size_left && asf->packet_size_left < FRAME_HEADER_SIZE) av_log(s, AV_LOG_WARNING, "Skip due to FRAME_HEADER_SIZE\n"); assert(ret >= 0); /* fail safe */ avio_skip(pb, ret); asf->packet_pos = avio_tell(pb); if (asf->data_object_size != (uint64_t)-1 && (asf->packet_pos - asf->data_object_offset >= asf->data_object_size)) return AVERROR_EOF; /* Do not exceed the size of the data object */ return 1; } if (asf->packet_time_start == 0) { if (asf_read_frame_header(s, pb) < 0) { asf->packet_time_start = asf->packet_segments = 0; continue; } if (asf->stream_index < 0 || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL || (!asf->packet_key_frame && (s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY || asf->streams[s->streams[asf->stream_index]->id].skip_to_key))) { asf->packet_time_start = 0; /* unhandled packet (should not happen) */ avio_skip(pb, asf->packet_frag_size); asf->packet_size_left -= asf->packet_frag_size; if (asf->stream_index < 0) av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size); continue; } asf->asf_st = &asf->streams[s->streams[asf->stream_index]->id]; if (!asf->packet_frag_offset) asf->asf_st->skip_to_key = 0; } asf_st = asf->asf_st; av_assert0(asf_st); if (!asf_st->frag_offset && asf->packet_frag_offset) { av_log(s, AV_LOG_TRACE, "skipping asf data pkt with fragment offset for " "stream:%d, expected:%d but got %d from pkt)\n", asf->stream_index, asf_st->frag_offset, asf->packet_frag_offset); avio_skip(pb, asf->packet_frag_size); asf->packet_size_left -= asf->packet_frag_size; continue; } if (asf->packet_replic_size == 1) { // frag_offset is here used as the beginning timestamp asf->packet_frag_timestamp = asf->packet_time_start; asf->packet_time_start += asf->packet_time_delta; asf_st->packet_obj_size = asf->packet_frag_size = avio_r8(pb); asf->packet_size_left--; asf->packet_multi_size--; if (asf->packet_multi_size < asf_st->packet_obj_size) { asf->packet_time_start = 0; avio_skip(pb, asf->packet_multi_size); asf->packet_size_left -= asf->packet_multi_size; continue; } asf->packet_multi_size -= asf_st->packet_obj_size; } if (asf_st->pkt.size != asf_st->packet_obj_size || // FIXME is this condition sufficient? asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { int ret; if (asf_st->pkt.data) { av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf_st->packet_obj_size); asf_st->frag_offset = 0; av_packet_unref(&asf_st->pkt); } /* new packet */ if ((ret = av_new_packet(&asf_st->pkt, asf_st->packet_obj_size)) < 0) return ret; asf_st->seq = asf->packet_seq; if (asf->ts_is_pts) { asf_st->pkt.pts = asf->packet_frag_timestamp - asf->hdr.preroll; } else asf_st->pkt.dts = asf->packet_frag_timestamp - asf->hdr.preroll; asf_st->pkt.stream_index = asf->stream_index; asf_st->pkt.pos = asf_st->packet_pos = asf->packet_pos; asf_st->pkt_clean = 0; if (asf_st->pkt.data && asf_st->palette_changed) { uint8_t *pal; pal = av_packet_new_side_data(&asf_st->pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); if (!pal) { av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n"); } else { memcpy(pal, asf_st->palette, AVPALETTE_SIZE); asf_st->palette_changed = 0; } } av_log(asf, AV_LOG_TRACE, "new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n", asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY, s->streams[asf->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO, asf_st->packet_obj_size); if (s->streams[asf->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) asf->packet_key_frame = 1; if (asf->packet_key_frame) asf_st->pkt.flags |= AV_PKT_FLAG_KEY; } /* read data */ av_log(asf, AV_LOG_TRACE, "READ PACKET s:%d os:%d o:%d,%d l:%d DATA:%p\n", s->packet_size, asf_st->pkt.size, asf->packet_frag_offset, asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data); asf->packet_size_left -= asf->packet_frag_size; if (asf->packet_size_left < 0) continue; if (asf->packet_frag_offset >= asf_st->pkt.size || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset) { av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n", asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size); continue; } if (asf->packet_frag_offset != asf_st->frag_offset && !asf_st->pkt_clean) { memset(asf_st->pkt.data + asf_st->frag_offset, 0, asf_st->pkt.size - asf_st->frag_offset); asf_st->pkt_clean = 1; } ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset, asf->packet_frag_size); if (ret != asf->packet_frag_size) { if (ret < 0 || asf->packet_frag_offset + ret == 0) return ret < 0 ? ret : AVERROR_EOF; if (asf_st->ds_span > 1) { // scrambling, we can either drop it completely or fill the remainder // TODO: should we fill the whole packet instead of just the current // fragment? memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0, asf->packet_frag_size - ret); ret = asf->packet_frag_size; } else { // no scrambling, so we can return partial packets av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret); } } if (s->key && s->keylen == 20) ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset, ret); asf_st->frag_offset += ret; /* test if whole packet is read */ if (asf_st->frag_offset == asf_st->pkt.size) { // workaround for macroshit radio DVR-MS files if (s->streams[asf->stream_index]->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO && asf_st->pkt.size > 100) { int i; for (i = 0; i < asf_st->pkt.size && !asf_st->pkt.data[i]; i++) ; if (i == asf_st->pkt.size) { av_log(s, AV_LOG_DEBUG, "discarding ms fart\n"); asf_st->frag_offset = 0; av_packet_unref(&asf_st->pkt); continue; } } /* return packet */ if (asf_st->ds_span > 1) { if (asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span) { av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span); } else { /* packet descrambling */ AVBufferRef *buf = av_buffer_alloc(asf_st->pkt.size + AV_INPUT_BUFFER_PADDING_SIZE); if (buf) { uint8_t *newdata = buf->data; int offset = 0; memset(newdata + asf_st->pkt.size, 0, AV_INPUT_BUFFER_PADDING_SIZE); while (offset < asf_st->pkt.size) { int off = offset / asf_st->ds_chunk_size; int row = off / asf_st->ds_span; int col = off % asf_st->ds_span; int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size; assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size); assert(idx + 1 <= asf_st->pkt.size / asf_st->ds_chunk_size); memcpy(newdata + offset, asf_st->pkt.data + idx * asf_st->ds_chunk_size, asf_st->ds_chunk_size); offset += asf_st->ds_chunk_size; } av_buffer_unref(&asf_st->pkt.buf); asf_st->pkt.buf = buf; asf_st->pkt.data = buf->data; } } } asf_st->frag_offset = 0; *pkt = asf_st->pkt; asf_st->pkt.buf = 0; asf_st->pkt.size = 0; asf_st->pkt.data = 0; asf_st->pkt.side_data_elems = 0; asf_st->pkt.side_data = NULL; break; // packet completed } } return 0; } static int asf_read_packet(AVFormatContext *s, AVPacket *pkt) { ASFContext *asf = s->priv_data; for (;;) { int ret; /* parse cached packets, if any */ if ((ret = asf_parse_packet(s, s->pb, pkt)) <= 0) return ret; if ((ret = asf_get_packet(s, s->pb)) < 0) assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1); asf->packet_time_start = 0; } } // Added to support seeking after packets have been read // If information is not reset, read_packet fails due to // leftover information from previous reads static void asf_reset_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; ASFStream *asf_st; int i; asf->packet_size_left = 0; asf->packet_flags = 0; asf->packet_property = 0; asf->packet_timestamp = 0; asf->packet_segsizetype = 0; asf->packet_segments = 0; asf->packet_seq = 0; asf->packet_replic_size = 0; asf->packet_key_frame = 0; asf->packet_padsize = 0; asf->packet_frag_offset = 0; asf->packet_frag_size = 0; asf->packet_frag_timestamp = 0; asf->packet_multi_size = 0; asf->packet_time_delta = 0; asf->packet_time_start = 0; for (i = 0; i < 128; i++) { asf_st = &asf->streams[i]; av_packet_unref(&asf_st->pkt); asf_st->packet_obj_size = 0; asf_st->frag_offset = 0; asf_st->seq = 0; } asf->asf_st = NULL; } static void skip_to_key(AVFormatContext *s) { ASFContext *asf = s->priv_data; int i; for (i = 0; i < 128; i++) { int j = asf->asfid2avid[i]; ASFStream *asf_st = &asf->streams[i]; if (j < 0 || s->streams[j]->codecpar->codec_type != AVMEDIA_TYPE_VIDEO) continue; asf_st->skip_to_key = 1; } } static int asf_read_close(AVFormatContext *s) { asf_reset_header(s); return 0; } static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit) { ASFContext *asf = s->priv_data; AVPacket pkt1, *pkt = &pkt1; ASFStream *asf_st; int64_t pts; int64_t pos = *ppos; int i; int64_t start_pos[ASF_MAX_STREAMS]; for (i = 0; i < s->nb_streams; i++) start_pos[i] = pos; if (s->packet_size > 0) pos = (pos + s->packet_size - 1 - s->internal->data_offset) / s->packet_size * s->packet_size + s->internal->data_offset; *ppos = pos; if (avio_seek(s->pb, pos, SEEK_SET) < 0) return AV_NOPTS_VALUE; ff_read_frame_flush(s); asf_reset_header(s); for (;;) { if (av_read_frame(s, pkt) < 0) { av_log(s, AV_LOG_INFO, "asf_read_pts failed\n"); return AV_NOPTS_VALUE; } pts = pkt->dts; if (pkt->flags & AV_PKT_FLAG_KEY) { i = pkt->stream_index; asf_st = &asf->streams[s->streams[i]->id]; // assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0); pos = asf_st->packet_pos; av_assert1(pkt->pos == asf_st->packet_pos); av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME); start_pos[i] = asf_st->packet_pos + 1; if (pkt->stream_index == stream_index) { av_packet_unref(pkt); break; } } av_packet_unref(pkt); } *ppos = pos; return pts; } static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: // if (avio_feof(s->pb)) { // ret = 0; // } avio_seek(s->pb, current_pos, SEEK_SET); return ret; } static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags) { ASFContext *asf = s->priv_data; AVStream *st = s->streams[stream_index]; int ret = 0; if (s->packet_size <= 0) return -1; /* Try using the protocol's read_seek if available */ if (s->pb) { int64_t ret = avio_seek_time(s->pb, stream_index, pts, flags); if (ret >= 0) asf_reset_header(s); if (ret != AVERROR(ENOSYS)) return ret; } /* explicitly handle the case of seeking to 0 */ if (!pts) { asf_reset_header(s); avio_seek(s->pb, s->internal->data_offset, SEEK_SET); return 0; } if (!asf->index_read) { ret = asf_build_simple_index(s, stream_index); if (ret < 0) asf->index_read = -1; } if (asf->index_read > 0 && st->index_entries) { int index = av_index_search_timestamp(st, pts, flags); if (index >= 0) { /* find the position */ uint64_t pos = st->index_entries[index].pos; /* do the seek */ av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos); if(avio_seek(s->pb, pos, SEEK_SET) < 0) return -1; asf_reset_header(s); skip_to_key(s); return 0; } } /* no index or seeking by index failed */ if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0) return -1; asf_reset_header(s); skip_to_key(s); return 0; } AVInputFormat ff_asf_demuxer = { .name = "asf", .long_name = NULL_IF_CONFIG_SMALL("ASF (Advanced / Active Streaming Format)"), .priv_data_size = sizeof(ASFContext), .read_probe = asf_probe, .read_header = asf_read_header, .read_packet = asf_read_packet, .read_close = asf_read_close, .read_seek = asf_read_seek, .read_timestamp = asf_read_pts, .flags = AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH, .priv_class = &asf_class, };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2764_0
crossvul-cpp_data_bad_2783_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->alpha_trait=BlendPixelTrait; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register Quantum *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) return; p=PushLongPixel(MSBEndian,p,&count); if ((p+count) > (blocks+length)) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ if (count < 16) return; p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((count > 3) && (*(p+4) == 0)) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { PixelInfo *color; if (type == 0) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); } color=image->colormap+(ssize_t) ConstrainColormapIndex(image, GetPixelIndex(image,q),exception); if ((type == 0) && (channels > 1)) return; else color->alpha=(MagickRealType) pixel; SetPixelViaPixelInfo(image,color,q); return; } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); break; } case 1: { SetPixelGreen(image,pixel,q); break; } case 2: { SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (EOFBlob(image) != MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickFalse); return(ReadPSDLayersInternal(image,image_info,psd_info,skip_layers, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); if (psd_info.channels > 4) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); if (psd_info.channels > 1) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); } else if (psd_info.channels > 3) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,exception) != MagickFalse)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+ mask->page.y); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+ mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2783_0
crossvul-cpp_data_bad_2766_0
/* * Phantom Cine demuxer * Copyright (c) 2010-2011 Peter Ross <pross@xvid.org> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Phantom Cine demuxer * @author Peter Ross <pross@xvid.org> */ #include "libavutil/intreadwrite.h" #include "libavcodec/bmp.h" #include "libavutil/intfloat.h" #include "avformat.h" #include "internal.h" typedef struct { uint64_t pts; } CineDemuxContext; /** Compression */ enum { CC_RGB = 0, /**< Gray */ CC_LEAD = 1, /**< LEAD (M)JPEG */ CC_UNINT = 2 /**< Uninterpolated color image (CFA field indicates color ordering) */ }; /** Color Filter Array */ enum { CFA_NONE = 0, /**< GRAY */ CFA_VRI = 1, /**< GBRG/RGGB */ CFA_VRIV6 = 2, /**< BGGR/GRBG */ CFA_BAYER = 3, /**< GB/RG */ CFA_BAYERFLIP = 4, /**< RG/GB */ }; #define CFA_TLGRAY 0x80000000U #define CFA_TRGRAY 0x40000000U #define CFA_BLGRAY 0x20000000U #define CFA_BRGRAY 0x10000000U static int cine_read_probe(AVProbeData *p) { int HeaderSize; if (p->buf[0] == 'C' && p->buf[1] == 'I' && // Type (HeaderSize = AV_RL16(p->buf + 2)) >= 0x2C && // HeaderSize AV_RL16(p->buf + 4) <= CC_UNINT && // Compression AV_RL16(p->buf + 6) <= 1 && // Version AV_RL32(p->buf + 20) && // ImageCount AV_RL32(p->buf + 24) >= HeaderSize && // OffImageHeader AV_RL32(p->buf + 28) >= HeaderSize && // OffSetup AV_RL32(p->buf + 32) >= HeaderSize) // OffImageOffsets return AVPROBE_SCORE_MAX; return 0; } static int set_metadata_int(AVDictionary **dict, const char *key, int value, int allow_zero) { if (value || allow_zero) { return av_dict_set_int(dict, key, value, 0); } return 0; } static int set_metadata_float(AVDictionary **dict, const char *key, float value, int allow_zero) { if (value != 0 || allow_zero) { char tmp[64]; snprintf(tmp, sizeof(tmp), "%f", value); return av_dict_set(dict, key, tmp, 0); } return 0; } static int cine_read_header(AVFormatContext *avctx) { AVIOContext *pb = avctx->pb; AVStream *st; unsigned int version, compression, offImageHeader, offSetup, offImageOffsets, biBitCount, length, CFA; int vflip; char *description; uint64_t i; st = avformat_new_stream(avctx, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; st->codecpar->codec_tag = 0; /* CINEFILEHEADER structure */ avio_skip(pb, 4); // Type, Headersize compression = avio_rl16(pb); version = avio_rl16(pb); if (version != 1) { avpriv_request_sample(avctx, "unknown version %i", version); return AVERROR_INVALIDDATA; } avio_skip(pb, 12); // FirstMovieImage, TotalImageCount, FirstImageNumber st->duration = avio_rl32(pb); offImageHeader = avio_rl32(pb); offSetup = avio_rl32(pb); offImageOffsets = avio_rl32(pb); avio_skip(pb, 8); // TriggerTime /* BITMAPINFOHEADER structure */ avio_seek(pb, offImageHeader, SEEK_SET); avio_skip(pb, 4); //biSize st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); if (avio_rl16(pb) != 1) // biPlanes return AVERROR_INVALIDDATA; biBitCount = avio_rl16(pb); if (biBitCount != 8 && biBitCount != 16 && biBitCount != 24 && biBitCount != 48) { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } switch (avio_rl32(pb)) { case BMP_RGB: vflip = 0; break; case 0x100: /* BI_PACKED */ st->codecpar->codec_tag = MKTAG('B', 'I', 'T', 0); vflip = 1; break; default: avpriv_request_sample(avctx, "unknown bitmap compression"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); // biSizeImage /* parse SETUP structure */ avio_seek(pb, offSetup, SEEK_SET); avio_skip(pb, 140); // FrameRatae16 .. descriptionOld if (avio_rl16(pb) != 0x5453) return AVERROR_INVALIDDATA; length = avio_rl16(pb); if (length < 0x163C) { avpriv_request_sample(avctx, "short SETUP header"); return AVERROR_INVALIDDATA; } avio_skip(pb, 616); // Binning .. bFlipH if (!avio_rl32(pb) ^ vflip) { st->codecpar->extradata = av_strdup("BottomUp"); st->codecpar->extradata_size = 9; } avio_skip(pb, 4); // Grid avpriv_set_pts_info(st, 64, 1, avio_rl32(pb)); avio_skip(pb, 20); // Shutter .. bEnableColor set_metadata_int(&st->metadata, "camera_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "firmware_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "software_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "recording_timezone", avio_rl32(pb), 0); CFA = avio_rl32(pb); set_metadata_int(&st->metadata, "brightness", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "contrast", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "gamma", avio_rl32(pb), 1); avio_skip(pb, 12 + 16); // Reserved1 .. AutoExpRect set_metadata_float(&st->metadata, "wbgain[0].r", av_int2float(avio_rl32(pb)), 1); set_metadata_float(&st->metadata, "wbgain[0].b", av_int2float(avio_rl32(pb)), 1); avio_skip(pb, 36); // WBGain[1].. WBView st->codecpar->bits_per_coded_sample = avio_rl32(pb); if (compression == CC_RGB) { if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_GRAY8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_GRAY16LE; } else if (biBitCount == 24) { st->codecpar->format = AV_PIX_FMT_BGR24; } else if (biBitCount == 48) { st->codecpar->format = AV_PIX_FMT_BGR48LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } } else if (compression == CC_UNINT) { switch (CFA & 0xFFFFFF) { case CFA_BAYER: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; case CFA_BAYERFLIP: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; default: avpriv_request_sample(avctx, "unsupported Color Field Array (CFA) %i", CFA & 0xFFFFFF); return AVERROR_INVALIDDATA; } } else { //CC_LEAD avpriv_request_sample(avctx, "unsupported compression %i", compression); return AVERROR_INVALIDDATA; } avio_skip(pb, 668); // Conv8Min ... Sensor set_metadata_int(&st->metadata, "shutter_ns", avio_rl32(pb), 0); avio_skip(pb, 24); // EDRShutterNs ... ImHeightAcq #define DESCRIPTION_SIZE 4096 description = av_malloc(DESCRIPTION_SIZE + 1); if (!description) return AVERROR(ENOMEM); i = avio_get_str(pb, DESCRIPTION_SIZE, description, DESCRIPTION_SIZE + 1); if (i < DESCRIPTION_SIZE) avio_skip(pb, DESCRIPTION_SIZE - i); if (description[0]) av_dict_set(&st->metadata, "description", description, AV_DICT_DONT_STRDUP_VAL); else av_free(description); avio_skip(pb, 1176); // RisingEdge ... cmUser set_metadata_int(&st->metadata, "enable_crop", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_left", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_top", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_right", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_bottom", avio_rl32(pb), 1); /* parse image offsets */ avio_seek(pb, offImageOffsets, SEEK_SET); for (i = 0; i < st->duration; i++) av_add_index_entry(st, avio_rl64(pb), i, 0, 0, AVINDEX_KEYFRAME); return 0; } static int cine_read_packet(AVFormatContext *avctx, AVPacket *pkt) { CineDemuxContext *cine = avctx->priv_data; AVStream *st = avctx->streams[0]; AVIOContext *pb = avctx->pb; int n, size, ret; if (cine->pts >= st->duration) return AVERROR_EOF; avio_seek(pb, st->index_entries[cine->pts].pos, SEEK_SET); n = avio_rl32(pb); if (n < 8) return AVERROR_INVALIDDATA; avio_skip(pb, n - 8); size = avio_rl32(pb); ret = av_get_packet(pb, pkt, size); if (ret < 0) return ret; pkt->pts = cine->pts++; pkt->stream_index = 0; pkt->flags |= AV_PKT_FLAG_KEY; return 0; } static int cine_read_seek(AVFormatContext *avctx, int stream_index, int64_t timestamp, int flags) { CineDemuxContext *cine = avctx->priv_data; if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE)) return AVERROR(ENOSYS); if (!(avctx->pb->seekable & AVIO_SEEKABLE_NORMAL)) return AVERROR(EIO); cine->pts = timestamp; return 0; } AVInputFormat ff_cine_demuxer = { .name = "cine", .long_name = NULL_IF_CONFIG_SMALL("Phantom Cine"), .priv_data_size = sizeof(CineDemuxContext), .read_probe = cine_read_probe, .read_header = cine_read_header, .read_packet = cine_read_packet, .read_seek = cine_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2766_0
crossvul-cpp_data_good_2761_0
/* * "Real" compatible demuxer. * Copyright (c) 2000, 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/channel_layout.h" #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #include "libavutil/dict.h" #include "avformat.h" #include "avio_internal.h" #include "internal.h" #include "rmsipr.h" #include "rm.h" #define DEINT_ID_GENR MKTAG('g', 'e', 'n', 'r') ///< interleaving for Cooker/ATRAC #define DEINT_ID_INT0 MKTAG('I', 'n', 't', '0') ///< no interleaving needed #define DEINT_ID_INT4 MKTAG('I', 'n', 't', '4') ///< interleaving for 28.8 #define DEINT_ID_SIPR MKTAG('s', 'i', 'p', 'r') ///< interleaving for Sipro #define DEINT_ID_VBRF MKTAG('v', 'b', 'r', 'f') ///< VBR case for AAC #define DEINT_ID_VBRS MKTAG('v', 'b', 'r', 's') ///< VBR case for AAC struct RMStream { AVPacket pkt; ///< place to store merged video frame / reordered audio data int videobufsize; ///< current assembled frame size int videobufpos; ///< position for the next slice in the video buffer int curpic_num; ///< picture number of current frame int cur_slice, slices; int64_t pktpos; ///< first slice position in file /// Audio descrambling matrix parameters int64_t audiotimestamp; ///< Audio packet timestamp int sub_packet_cnt; // Subpacket counter, used while reading int sub_packet_size, sub_packet_h, coded_framesize; ///< Descrambling parameters from container int audio_framesize; /// Audio frame size from container int sub_packet_lengths[16]; /// Length of each subpacket int32_t deint_id; ///< deinterleaver used in audio stream }; typedef struct RMDemuxContext { int nb_packets; int old_format; int current_stream; int remaining_len; int audio_stream_num; ///< Stream number for audio packets int audio_pkt_cnt; ///< Output packet counter int data_end; } RMDemuxContext; static int rm_read_close(AVFormatContext *s); static inline void get_strl(AVIOContext *pb, char *buf, int buf_size, int len) { int i; char *q, r; q = buf; for(i=0;i<len;i++) { r = avio_r8(pb); if (i < buf_size - 1) *q++ = r; } if (buf_size > 0) *q = '\0'; } static void get_str8(AVIOContext *pb, char *buf, int buf_size) { get_strl(pb, buf, buf_size, avio_r8(pb)); } static int rm_read_extradata(AVFormatContext *s, AVIOContext *pb, AVCodecParameters *par, unsigned size) { if (size >= 1<<24) { av_log(s, AV_LOG_ERROR, "extradata size %u too large\n", size); return -1; } if (ff_get_extradata(s, par, pb, size) < 0) return AVERROR(ENOMEM); return 0; } static void rm_read_metadata(AVFormatContext *s, AVIOContext *pb, int wide) { char buf[1024]; int i; for (i=0; i<FF_ARRAY_ELEMS(ff_rm_metadata); i++) { int len = wide ? avio_rb16(pb) : avio_r8(pb); get_strl(pb, buf, sizeof(buf), len); av_dict_set(&s->metadata, ff_rm_metadata[i], buf, 0); } } RMStream *ff_rm_alloc_rmstream (void) { RMStream *rms = av_mallocz(sizeof(RMStream)); if (!rms) return NULL; rms->curpic_num = -1; return rms; } void ff_rm_free_rmstream (RMStream *rms) { av_packet_unref(&rms->pkt); } static int rm_read_audio_stream_info(AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *ast, int read_all) { char buf[256]; uint32_t version; int ret; /* ra type header */ version = avio_rb16(pb); /* version */ if (version == 3) { unsigned bytes_per_minute; int header_size = avio_rb16(pb); int64_t startpos = avio_tell(pb); avio_skip(pb, 8); bytes_per_minute = avio_rb16(pb); avio_skip(pb, 4); rm_read_metadata(s, pb, 0); if ((startpos + header_size) >= avio_tell(pb) + 2) { // fourcc (should always be "lpcJ") avio_r8(pb); get_str8(pb, buf, sizeof(buf)); } // Skip extra header crap (this should never happen) if ((startpos + header_size) > avio_tell(pb)) avio_skip(pb, header_size + startpos - avio_tell(pb)); if (bytes_per_minute) st->codecpar->bit_rate = 8LL * bytes_per_minute / 60; st->codecpar->sample_rate = 8000; st->codecpar->channels = 1; st->codecpar->channel_layout = AV_CH_LAYOUT_MONO; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_RA_144; ast->deint_id = DEINT_ID_INT0; } else { int flavor, sub_packet_h, coded_framesize, sub_packet_size; int codecdata_length; unsigned bytes_per_minute; /* old version (4) */ avio_skip(pb, 2); /* unused */ avio_rb32(pb); /* .ra4 */ avio_rb32(pb); /* data size */ avio_rb16(pb); /* version2 */ avio_rb32(pb); /* header size */ flavor= avio_rb16(pb); /* add codec info / flavor */ ast->coded_framesize = coded_framesize = avio_rb32(pb); /* coded frame size */ avio_rb32(pb); /* ??? */ bytes_per_minute = avio_rb32(pb); if (version == 4) { if (bytes_per_minute) st->codecpar->bit_rate = 8LL * bytes_per_minute / 60; } avio_rb32(pb); /* ??? */ ast->sub_packet_h = sub_packet_h = avio_rb16(pb); /* 1 */ st->codecpar->block_align= avio_rb16(pb); /* frame size */ ast->sub_packet_size = sub_packet_size = avio_rb16(pb); /* sub packet size */ avio_rb16(pb); /* ??? */ if (version == 5) { avio_rb16(pb); avio_rb16(pb); avio_rb16(pb); } st->codecpar->sample_rate = avio_rb16(pb); avio_rb32(pb); st->codecpar->channels = avio_rb16(pb); if (version == 5) { ast->deint_id = avio_rl32(pb); avio_read(pb, buf, 4); buf[4] = 0; } else { AV_WL32(buf, 0); get_str8(pb, buf, sizeof(buf)); /* desc */ ast->deint_id = AV_RL32(buf); get_str8(pb, buf, sizeof(buf)); /* desc */ } st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_tag = AV_RL32(buf); st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, st->codecpar->codec_tag); switch (st->codecpar->codec_id) { case AV_CODEC_ID_AC3: st->need_parsing = AVSTREAM_PARSE_FULL; break; case AV_CODEC_ID_RA_288: st->codecpar->extradata_size= 0; av_freep(&st->codecpar->extradata); ast->audio_framesize = st->codecpar->block_align; st->codecpar->block_align = coded_framesize; break; case AV_CODEC_ID_COOK: st->need_parsing = AVSTREAM_PARSE_HEADERS; case AV_CODEC_ID_ATRAC3: case AV_CODEC_ID_SIPR: if (read_all) { codecdata_length = 0; } else { avio_rb16(pb); avio_r8(pb); if (version == 5) avio_r8(pb); codecdata_length = avio_rb32(pb); if(codecdata_length + AV_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){ av_log(s, AV_LOG_ERROR, "codecdata_length too large\n"); return -1; } } ast->audio_framesize = st->codecpar->block_align; if (st->codecpar->codec_id == AV_CODEC_ID_SIPR) { if (flavor > 3) { av_log(s, AV_LOG_ERROR, "bad SIPR file flavor %d\n", flavor); return -1; } st->codecpar->block_align = ff_sipr_subpk_size[flavor]; st->need_parsing = AVSTREAM_PARSE_FULL_RAW; } else { if(sub_packet_size <= 0){ av_log(s, AV_LOG_ERROR, "sub_packet_size is invalid\n"); return -1; } st->codecpar->block_align = ast->sub_packet_size; } if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length)) < 0) return ret; break; case AV_CODEC_ID_AAC: avio_rb16(pb); avio_r8(pb); if (version == 5) avio_r8(pb); codecdata_length = avio_rb32(pb); if(codecdata_length + AV_INPUT_BUFFER_PADDING_SIZE <= (unsigned)codecdata_length){ av_log(s, AV_LOG_ERROR, "codecdata_length too large\n"); return -1; } if (codecdata_length >= 1) { avio_r8(pb); if ((ret = rm_read_extradata(s, pb, st->codecpar, codecdata_length - 1)) < 0) return ret; } break; } switch (ast->deint_id) { case DEINT_ID_INT4: if (ast->coded_framesize > ast->audio_framesize || sub_packet_h <= 1 || ast->coded_framesize * sub_packet_h > (2 + (sub_packet_h & 1)) * ast->audio_framesize) return AVERROR_INVALIDDATA; if (ast->coded_framesize * sub_packet_h != 2*ast->audio_framesize) { avpriv_request_sample(s, "mismatching interleaver parameters"); return AVERROR_INVALIDDATA; } break; case DEINT_ID_GENR: if (ast->sub_packet_size <= 0 || ast->sub_packet_size > ast->audio_framesize) return AVERROR_INVALIDDATA; if (ast->audio_framesize % ast->sub_packet_size) return AVERROR_INVALIDDATA; break; case DEINT_ID_SIPR: case DEINT_ID_INT0: case DEINT_ID_VBRS: case DEINT_ID_VBRF: break; default: av_log(s, AV_LOG_ERROR ,"Unknown interleaver %"PRIX32"\n", ast->deint_id); return AVERROR_INVALIDDATA; } if (ast->deint_id == DEINT_ID_INT4 || ast->deint_id == DEINT_ID_GENR || ast->deint_id == DEINT_ID_SIPR) { if (st->codecpar->block_align <= 0 || ast->audio_framesize * sub_packet_h > (unsigned)INT_MAX || ast->audio_framesize * sub_packet_h < st->codecpar->block_align) return AVERROR_INVALIDDATA; if (av_new_packet(&ast->pkt, ast->audio_framesize * sub_packet_h) < 0) return AVERROR(ENOMEM); } if (read_all) { avio_r8(pb); avio_r8(pb); avio_r8(pb); rm_read_metadata(s, pb, 0); } } return 0; } int ff_rm_read_mdpr_codecdata(AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *rst, unsigned int codec_data_size, const uint8_t *mime) { unsigned int v; int size; int64_t codec_pos; int ret; if (codec_data_size > INT_MAX) return AVERROR_INVALIDDATA; if (codec_data_size == 0) return 0; avpriv_set_pts_info(st, 64, 1, 1000); codec_pos = avio_tell(pb); v = avio_rb32(pb); if (v == MKTAG(0xfd, 'a', 'r', '.')) { /* ra type header */ if (rm_read_audio_stream_info(s, pb, st, rst, 0)) return -1; } else if (v == MKBETAG('L', 'S', 'D', ':')) { avio_seek(pb, -4, SEEK_CUR); if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size)) < 0) return ret; st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_tag = AV_RL32(st->codecpar->extradata); st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, st->codecpar->codec_tag); } else if(mime && !strcmp(mime, "logical-fileinfo")){ int stream_count, rule_count, property_count, i; ff_free_stream(s, st); if (avio_rb16(pb) != 0) { av_log(s, AV_LOG_WARNING, "Unsupported version\n"); goto skip; } stream_count = avio_rb16(pb); avio_skip(pb, 6*stream_count); rule_count = avio_rb16(pb); avio_skip(pb, 2*rule_count); property_count = avio_rb16(pb); for(i=0; i<property_count; i++){ uint8_t name[128], val[128]; avio_rb32(pb); if (avio_rb16(pb) != 0) { av_log(s, AV_LOG_WARNING, "Unsupported Name value property version\n"); goto skip; //FIXME skip just this one } get_str8(pb, name, sizeof(name)); switch(avio_rb32(pb)) { case 2: get_strl(pb, val, sizeof(val), avio_rb16(pb)); av_dict_set(&s->metadata, name, val, 0); break; default: avio_skip(pb, avio_rb16(pb)); } } } else { int fps; if (avio_rl32(pb) != MKTAG('V', 'I', 'D', 'O')) { fail1: av_log(s, AV_LOG_WARNING, "Unsupported stream type %08x\n", v); goto skip; } st->codecpar->codec_tag = avio_rl32(pb); st->codecpar->codec_id = ff_codec_get_id(ff_rm_codec_tags, st->codecpar->codec_tag); av_log(s, AV_LOG_TRACE, "%"PRIX32" %X\n", st->codecpar->codec_tag, MKTAG('R', 'V', '2', '0')); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) goto fail1; st->codecpar->width = avio_rb16(pb); st->codecpar->height = avio_rb16(pb); avio_skip(pb, 2); // looks like bits per sample avio_skip(pb, 4); // always zero? st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; fps = avio_rb32(pb); if ((ret = rm_read_extradata(s, pb, st->codecpar, codec_data_size - (avio_tell(pb) - codec_pos))) < 0) return ret; if (fps > 0) { av_reduce(&st->avg_frame_rate.den, &st->avg_frame_rate.num, 0x10000, fps, (1 << 30) - 1); #if FF_API_R_FRAME_RATE st->r_frame_rate = st->avg_frame_rate; #endif } else if (s->error_recognition & AV_EF_EXPLODE) { av_log(s, AV_LOG_ERROR, "Invalid framerate\n"); return AVERROR_INVALIDDATA; } } skip: /* skip codec info */ size = avio_tell(pb) - codec_pos; if (codec_data_size >= size) { avio_skip(pb, codec_data_size - size); } else { av_log(s, AV_LOG_WARNING, "codec_data_size %u < size %d\n", codec_data_size, size); } return 0; } /** this function assumes that the demuxer has already seeked to the start * of the INDX chunk, and will bail out if not. */ static int rm_read_index(AVFormatContext *s) { AVIOContext *pb = s->pb; unsigned int size, n_pkts, str_id, next_off, n, pos, pts; AVStream *st; do { if (avio_rl32(pb) != MKTAG('I','N','D','X')) return -1; size = avio_rb32(pb); if (size < 20) return -1; avio_skip(pb, 2); n_pkts = avio_rb32(pb); str_id = avio_rb16(pb); next_off = avio_rb32(pb); for (n = 0; n < s->nb_streams; n++) if (s->streams[n]->id == str_id) { st = s->streams[n]; break; } if (n == s->nb_streams) { av_log(s, AV_LOG_ERROR, "Invalid stream index %d for index at pos %"PRId64"\n", str_id, avio_tell(pb)); goto skip; } else if ((avio_size(pb) - avio_tell(pb)) / 14 < n_pkts) { av_log(s, AV_LOG_ERROR, "Nr. of packets in packet index for stream index %d " "exceeds filesize (%"PRId64" at %"PRId64" = %"PRId64")\n", str_id, avio_size(pb), avio_tell(pb), (avio_size(pb) - avio_tell(pb)) / 14); goto skip; } for (n = 0; n < n_pkts; n++) { avio_skip(pb, 2); pts = avio_rb32(pb); pos = avio_rb32(pb); avio_skip(pb, 4); /* packet no. */ av_add_index_entry(st, pos, pts, 0, 0, AVINDEX_KEYFRAME); } skip: if (next_off && avio_tell(pb) < next_off && avio_seek(pb, next_off, SEEK_SET) < 0) { av_log(s, AV_LOG_ERROR, "Non-linear index detected, not supported\n"); return -1; } } while (next_off); return 0; } static int rm_read_header_old(AVFormatContext *s) { RMDemuxContext *rm = s->priv_data; AVStream *st; rm->old_format = 1; st = avformat_new_stream(s, NULL); if (!st) return -1; st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); return rm_read_audio_stream_info(s, s->pb, st, st->priv_data, 1); } static int rm_read_multi(AVFormatContext *s, AVIOContext *pb, AVStream *st, char *mime) { int number_of_streams = avio_rb16(pb); int number_of_mdpr; int i, ret; unsigned size2; for (i = 0; i<number_of_streams; i++) avio_rb16(pb); number_of_mdpr = avio_rb16(pb); if (number_of_mdpr != 1) { avpriv_request_sample(s, "MLTI with multiple (%d) MDPR", number_of_mdpr); } for (i = 0; i < number_of_mdpr; i++) { AVStream *st2; if (i > 0) { st2 = avformat_new_stream(s, NULL); if (!st2) { ret = AVERROR(ENOMEM); return ret; } st2->id = st->id + (i<<16); st2->codecpar->bit_rate = st->codecpar->bit_rate; st2->start_time = st->start_time; st2->duration = st->duration; st2->codecpar->codec_type = AVMEDIA_TYPE_DATA; st2->priv_data = ff_rm_alloc_rmstream(); if (!st2->priv_data) return AVERROR(ENOMEM); } else st2 = st; size2 = avio_rb32(pb); ret = ff_rm_read_mdpr_codecdata(s, s->pb, st2, st2->priv_data, size2, mime); if (ret < 0) return ret; } return 0; } static int rm_read_header(AVFormatContext *s) { RMDemuxContext *rm = s->priv_data; AVStream *st; AVIOContext *pb = s->pb; unsigned int tag; int tag_size; unsigned int start_time, duration; unsigned int data_off = 0, indx_off = 0; char buf[128], mime[128]; int flags = 0; int ret = -1; unsigned size, v; int64_t codec_pos; tag = avio_rl32(pb); if (tag == MKTAG('.', 'r', 'a', 0xfd)) { /* very old .ra format */ return rm_read_header_old(s); } else if (tag != MKTAG('.', 'R', 'M', 'F')) { return AVERROR(EIO); } tag_size = avio_rb32(pb); avio_skip(pb, tag_size - 8); for(;;) { if (avio_feof(pb)) goto fail; tag = avio_rl32(pb); tag_size = avio_rb32(pb); avio_rb16(pb); av_log(s, AV_LOG_TRACE, "tag=%s size=%d\n", av_fourcc2str(tag), tag_size); if (tag_size < 10 && tag != MKTAG('D', 'A', 'T', 'A')) goto fail; switch(tag) { case MKTAG('P', 'R', 'O', 'P'): /* file header */ avio_rb32(pb); /* max bit rate */ avio_rb32(pb); /* avg bit rate */ avio_rb32(pb); /* max packet size */ avio_rb32(pb); /* avg packet size */ avio_rb32(pb); /* nb packets */ duration = avio_rb32(pb); /* duration */ s->duration = av_rescale(duration, AV_TIME_BASE, 1000); avio_rb32(pb); /* preroll */ indx_off = avio_rb32(pb); /* index offset */ data_off = avio_rb32(pb); /* data offset */ avio_rb16(pb); /* nb streams */ flags = avio_rb16(pb); /* flags */ break; case MKTAG('C', 'O', 'N', 'T'): rm_read_metadata(s, pb, 1); break; case MKTAG('M', 'D', 'P', 'R'): st = avformat_new_stream(s, NULL); if (!st) { ret = AVERROR(ENOMEM); goto fail; } st->id = avio_rb16(pb); avio_rb32(pb); /* max bit rate */ st->codecpar->bit_rate = avio_rb32(pb); /* bit rate */ avio_rb32(pb); /* max packet size */ avio_rb32(pb); /* avg packet size */ start_time = avio_rb32(pb); /* start time */ avio_rb32(pb); /* preroll */ duration = avio_rb32(pb); /* duration */ st->start_time = start_time; st->duration = duration; if(duration>0) s->duration = AV_NOPTS_VALUE; get_str8(pb, buf, sizeof(buf)); /* desc */ get_str8(pb, mime, sizeof(mime)); /* mimetype */ st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); size = avio_rb32(pb); codec_pos = avio_tell(pb); ffio_ensure_seekback(pb, 4); v = avio_rb32(pb); if (v == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, s->pb, st, mime); if (ret < 0) goto fail; avio_seek(pb, codec_pos + size, SEEK_SET); } else { avio_skip(pb, -4); if (ff_rm_read_mdpr_codecdata(s, s->pb, st, st->priv_data, size, mime) < 0) goto fail; } break; case MKTAG('D', 'A', 'T', 'A'): goto header_end; default: /* unknown tag: skip it */ avio_skip(pb, tag_size - 10); break; } } header_end: rm->nb_packets = avio_rb32(pb); /* number of packets */ if (!rm->nb_packets && (flags & 4)) rm->nb_packets = 3600 * 25; avio_rb32(pb); /* next data header */ if (!data_off) data_off = avio_tell(pb) - 18; if (indx_off && (pb->seekable & AVIO_SEEKABLE_NORMAL) && !(s->flags & AVFMT_FLAG_IGNIDX) && avio_seek(pb, indx_off, SEEK_SET) >= 0) { rm_read_index(s); avio_seek(pb, data_off + 18, SEEK_SET); } return 0; fail: rm_read_close(s); return ret; } static int get_num(AVIOContext *pb, int *len) { int n, n1; n = avio_rb16(pb); (*len)-=2; n &= 0x7FFF; if (n >= 0x4000) { return n - 0x4000; } else { n1 = avio_rb16(pb); (*len)-=2; return (n << 16) | n1; } } /* multiple of 20 bytes for ra144 (ugly) */ #define RAW_PACKET_SIZE 1000 static int rm_sync(AVFormatContext *s, int64_t *timestamp, int *flags, int *stream_index, int64_t *pos){ RMDemuxContext *rm = s->priv_data; AVIOContext *pb = s->pb; AVStream *st; uint32_t state=0xFFFFFFFF; while(!avio_feof(pb)){ int len, num, i; int mlti_id; *pos= avio_tell(pb) - 3; if(rm->remaining_len > 0){ num= rm->current_stream; mlti_id = 0; len= rm->remaining_len; *timestamp = AV_NOPTS_VALUE; *flags= 0; }else{ state= (state<<8) + avio_r8(pb); if(state == MKBETAG('I', 'N', 'D', 'X')){ int n_pkts, expected_len; len = avio_rb32(pb); avio_skip(pb, 2); n_pkts = avio_rb32(pb); expected_len = 20 + n_pkts * 14; if (len == 20) /* some files don't add index entries to chunk size... */ len = expected_len; else if (len != expected_len) av_log(s, AV_LOG_WARNING, "Index size %d (%d pkts) is wrong, should be %d.\n", len, n_pkts, expected_len); len -= 14; // we already read part of the index header if(len<0) continue; goto skip; } else if (state == MKBETAG('D','A','T','A')) { av_log(s, AV_LOG_WARNING, "DATA tag in middle of chunk, file may be broken.\n"); } if(state > (unsigned)0xFFFF || state <= 12) continue; len=state - 12; state= 0xFFFFFFFF; num = avio_rb16(pb); *timestamp = avio_rb32(pb); mlti_id = (avio_r8(pb)>>1)-1<<16; mlti_id = FFMAX(mlti_id, 0); *flags = avio_r8(pb); /* flags */ } for(i=0;i<s->nb_streams;i++) { st = s->streams[i]; if (mlti_id + num == st->id) break; } if (i == s->nb_streams) { skip: /* skip packet if unknown number */ avio_skip(pb, len); rm->remaining_len = 0; continue; } *stream_index= i; return len; } return -1; } static int rm_assemble_video_frame(AVFormatContext *s, AVIOContext *pb, RMDemuxContext *rm, RMStream *vst, AVPacket *pkt, int len, int *pseq, int64_t *timestamp) { int hdr; int seq = 0, pic_num = 0, len2 = 0, pos = 0; //init to silence compiler warning int type; int ret; hdr = avio_r8(pb); len--; type = hdr >> 6; if(type != 3){ // not frame as a part of packet seq = avio_r8(pb); len--; } if(type != 1){ // not whole frame len2 = get_num(pb, &len); pos = get_num(pb, &len); pic_num = avio_r8(pb); len--; } if(len<0) { av_log(s, AV_LOG_ERROR, "Insufficient data\n"); return -1; } rm->remaining_len = len; if(type&1){ // frame, not slice if(type == 3){ // frame as a part of packet len= len2; *timestamp = pos; } if(rm->remaining_len < len) { av_log(s, AV_LOG_ERROR, "Insufficient remaining len\n"); return -1; } rm->remaining_len -= len; if(av_new_packet(pkt, len + 9) < 0) return AVERROR(EIO); pkt->data[0] = 0; AV_WL32(pkt->data + 1, 1); AV_WL32(pkt->data + 5, 0); if ((ret = avio_read(pb, pkt->data + 9, len)) != len) { av_packet_unref(pkt); av_log(s, AV_LOG_ERROR, "Failed to read %d bytes\n", len); return ret < 0 ? ret : AVERROR(EIO); } return 0; } //now we have to deal with single slice *pseq = seq; if((seq & 0x7F) == 1 || vst->curpic_num != pic_num){ if (len2 > ffio_limit(pb, len2)) { av_log(s, AV_LOG_ERROR, "Impossibly sized packet\n"); return AVERROR_INVALIDDATA; } vst->slices = ((hdr & 0x3F) << 1) + 1; vst->videobufsize = len2 + 8*vst->slices + 1; av_packet_unref(&vst->pkt); //FIXME this should be output. if(av_new_packet(&vst->pkt, vst->videobufsize) < 0) return AVERROR(ENOMEM); memset(vst->pkt.data, 0, vst->pkt.size); vst->videobufpos = 8*vst->slices + 1; vst->cur_slice = 0; vst->curpic_num = pic_num; vst->pktpos = avio_tell(pb); } if(type == 2) len = FFMIN(len, pos); if(++vst->cur_slice > vst->slices) { av_log(s, AV_LOG_ERROR, "cur slice %d, too large\n", vst->cur_slice); return 1; } if(!vst->pkt.data) return AVERROR(ENOMEM); AV_WL32(vst->pkt.data - 7 + 8*vst->cur_slice, 1); AV_WL32(vst->pkt.data - 3 + 8*vst->cur_slice, vst->videobufpos - 8*vst->slices - 1); if(vst->videobufpos + len > vst->videobufsize) { av_log(s, AV_LOG_ERROR, "outside videobufsize\n"); return 1; } if (avio_read(pb, vst->pkt.data + vst->videobufpos, len) != len) return AVERROR(EIO); vst->videobufpos += len; rm->remaining_len-= len; if (type == 2 || vst->videobufpos == vst->videobufsize) { vst->pkt.data[0] = vst->cur_slice-1; *pkt= vst->pkt; vst->pkt.data= NULL; vst->pkt.size= 0; vst->pkt.buf = NULL; if(vst->slices != vst->cur_slice) //FIXME find out how to set slices correct from the begin memmove(pkt->data + 1 + 8*vst->cur_slice, pkt->data + 1 + 8*vst->slices, vst->videobufpos - 1 - 8*vst->slices); pkt->size = vst->videobufpos + 8*(vst->cur_slice - vst->slices); pkt->pts = AV_NOPTS_VALUE; pkt->pos = vst->pktpos; vst->slices = 0; return 0; } return 1; } static inline void rm_ac3_swap_bytes (AVStream *st, AVPacket *pkt) { uint8_t *ptr; int j; if (st->codecpar->codec_id == AV_CODEC_ID_AC3) { ptr = pkt->data; for (j=0;j<pkt->size;j+=2) { FFSWAP(int, ptr[0], ptr[1]); ptr += 2; } } } static int readfull(AVFormatContext *s, AVIOContext *pb, uint8_t *dst, int n) { int ret = avio_read(pb, dst, n); if (ret != n) { if (ret >= 0) memset(dst + ret, 0, n - ret); else memset(dst , 0, n); av_log(s, AV_LOG_ERROR, "Failed to fully read block\n"); } return ret; } int ff_rm_parse_packet (AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *ast, int len, AVPacket *pkt, int *seq, int flags, int64_t timestamp) { RMDemuxContext *rm = s->priv_data; int ret; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { rm->current_stream= st->id; ret = rm_assemble_video_frame(s, pb, rm, ast, pkt, len, seq, &timestamp); if(ret) return ret < 0 ? ret : -1; //got partial frame or error } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if ((ast->deint_id == DEINT_ID_GENR) || (ast->deint_id == DEINT_ID_INT4) || (ast->deint_id == DEINT_ID_SIPR)) { int x; int sps = ast->sub_packet_size; int cfs = ast->coded_framesize; int h = ast->sub_packet_h; int y = ast->sub_packet_cnt; int w = ast->audio_framesize; if (flags & 2) y = ast->sub_packet_cnt = 0; if (!y) ast->audiotimestamp = timestamp; switch (ast->deint_id) { case DEINT_ID_INT4: for (x = 0; x < h/2; x++) readfull(s, pb, ast->pkt.data+x*2*w+y*cfs, cfs); break; case DEINT_ID_GENR: for (x = 0; x < w/sps; x++) readfull(s, pb, ast->pkt.data+sps*(h*x+((h+1)/2)*(y&1)+(y>>1)), sps); break; case DEINT_ID_SIPR: readfull(s, pb, ast->pkt.data + y * w, w); break; } if (++(ast->sub_packet_cnt) < h) return -1; if (ast->deint_id == DEINT_ID_SIPR) ff_rm_reorder_sipr_data(ast->pkt.data, h, w); ast->sub_packet_cnt = 0; rm->audio_stream_num = st->index; if (st->codecpar->block_align <= 0) { av_log(s, AV_LOG_ERROR, "Invalid block alignment %d\n", st->codecpar->block_align); return AVERROR_INVALIDDATA; } rm->audio_pkt_cnt = h * w / st->codecpar->block_align; } else if ((ast->deint_id == DEINT_ID_VBRF) || (ast->deint_id == DEINT_ID_VBRS)) { int x; rm->audio_stream_num = st->index; ast->sub_packet_cnt = (avio_rb16(pb) & 0xf0) >> 4; if (ast->sub_packet_cnt) { for (x = 0; x < ast->sub_packet_cnt; x++) ast->sub_packet_lengths[x] = avio_rb16(pb); rm->audio_pkt_cnt = ast->sub_packet_cnt; ast->audiotimestamp = timestamp; } else return -1; } else { if ((ret = av_get_packet(pb, pkt, len)) < 0) return ret; rm_ac3_swap_bytes(st, pkt); } } else { if ((ret = av_get_packet(pb, pkt, len)) < 0) return ret; } pkt->stream_index = st->index; pkt->pts = timestamp; if (flags & 2) pkt->flags |= AV_PKT_FLAG_KEY; return st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO ? rm->audio_pkt_cnt : 0; } int ff_rm_retrieve_cache (AVFormatContext *s, AVIOContext *pb, AVStream *st, RMStream *ast, AVPacket *pkt) { RMDemuxContext *rm = s->priv_data; av_assert0 (rm->audio_pkt_cnt > 0); if (ast->deint_id == DEINT_ID_VBRF || ast->deint_id == DEINT_ID_VBRS) { int ret = av_get_packet(pb, pkt, ast->sub_packet_lengths[ast->sub_packet_cnt - rm->audio_pkt_cnt]); if (ret < 0) return ret; } else { int ret = av_new_packet(pkt, st->codecpar->block_align); if (ret < 0) return ret; memcpy(pkt->data, ast->pkt.data + st->codecpar->block_align * //FIXME avoid this (ast->sub_packet_h * ast->audio_framesize / st->codecpar->block_align - rm->audio_pkt_cnt), st->codecpar->block_align); } rm->audio_pkt_cnt--; if ((pkt->pts = ast->audiotimestamp) != AV_NOPTS_VALUE) { ast->audiotimestamp = AV_NOPTS_VALUE; pkt->flags = AV_PKT_FLAG_KEY; } else pkt->flags = 0; pkt->stream_index = st->index; return rm->audio_pkt_cnt; } static int rm_read_packet(AVFormatContext *s, AVPacket *pkt) { RMDemuxContext *rm = s->priv_data; AVStream *st = NULL; // init to silence compiler warning int i, len, res, seq = 1; int64_t timestamp, pos; int flags; for (;;) { if (rm->audio_pkt_cnt) { // If there are queued audio packet return them first st = s->streams[rm->audio_stream_num]; res = ff_rm_retrieve_cache(s, s->pb, st, st->priv_data, pkt); if(res < 0) return res; flags = 0; } else { if (rm->old_format) { RMStream *ast; st = s->streams[0]; ast = st->priv_data; timestamp = AV_NOPTS_VALUE; len = !ast->audio_framesize ? RAW_PACKET_SIZE : ast->coded_framesize * ast->sub_packet_h / 2; flags = (seq++ == 1) ? 2 : 0; pos = avio_tell(s->pb); } else { len = rm_sync(s, &timestamp, &flags, &i, &pos); if (len > 0) st = s->streams[i]; } if (avio_feof(s->pb)) return AVERROR_EOF; if (len <= 0) return AVERROR(EIO); res = ff_rm_parse_packet (s, s->pb, st, st->priv_data, len, pkt, &seq, flags, timestamp); if (res < -1) return res; if((flags&2) && (seq&0x7F) == 1) av_add_index_entry(st, pos, timestamp, 0, 0, AVINDEX_KEYFRAME); if (res) continue; } if( (st->discard >= AVDISCARD_NONKEY && !(flags&2)) || st->discard >= AVDISCARD_ALL){ av_packet_unref(pkt); } else break; } return 0; } static int rm_read_close(AVFormatContext *s) { int i; for (i=0;i<s->nb_streams;i++) ff_rm_free_rmstream(s->streams[i]->priv_data); return 0; } static int rm_probe(AVProbeData *p) { /* check file header */ if ((p->buf[0] == '.' && p->buf[1] == 'R' && p->buf[2] == 'M' && p->buf[3] == 'F' && p->buf[4] == 0 && p->buf[5] == 0) || (p->buf[0] == '.' && p->buf[1] == 'r' && p->buf[2] == 'a' && p->buf[3] == 0xfd)) return AVPROBE_SCORE_MAX; else return 0; } static int64_t rm_read_dts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit) { RMDemuxContext *rm = s->priv_data; int64_t pos, dts; int stream_index2, flags, len, h; pos = *ppos; if(rm->old_format) return AV_NOPTS_VALUE; if (avio_seek(s->pb, pos, SEEK_SET) < 0) return AV_NOPTS_VALUE; rm->remaining_len=0; for(;;){ int seq=1; AVStream *st; len = rm_sync(s, &dts, &flags, &stream_index2, &pos); if(len<0) return AV_NOPTS_VALUE; st = s->streams[stream_index2]; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { h= avio_r8(s->pb); len--; if(!(h & 0x40)){ seq = avio_r8(s->pb); len--; } } if((flags&2) && (seq&0x7F) == 1){ av_log(s, AV_LOG_TRACE, "%d %d-%d %"PRId64" %d\n", flags, stream_index2, stream_index, dts, seq); av_add_index_entry(st, pos, dts, 0, 0, AVINDEX_KEYFRAME); if(stream_index2 == stream_index) break; } avio_skip(s->pb, len); } *ppos = pos; return dts; } static int rm_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags) { RMDemuxContext *rm = s->priv_data; if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0) return -1; rm->audio_pkt_cnt = 0; return 0; } AVInputFormat ff_rm_demuxer = { .name = "rm", .long_name = NULL_IF_CONFIG_SMALL("RealMedia"), .priv_data_size = sizeof(RMDemuxContext), .read_probe = rm_probe, .read_header = rm_read_header, .read_packet = rm_read_packet, .read_close = rm_read_close, .read_timestamp = rm_read_dts, .read_seek = rm_read_seek, }; AVInputFormat ff_rdt_demuxer = { .name = "rdt", .long_name = NULL_IF_CONFIG_SMALL("RDT demuxer"), .priv_data_size = sizeof(RMDemuxContext), .read_close = rm_read_close, .flags = AVFMT_NOFILE, }; static int ivr_probe(AVProbeData *p) { if (memcmp(p->buf, ".R1M\x0\x1\x1", 7) && memcmp(p->buf, ".REC", 4)) return 0; return AVPROBE_SCORE_MAX; } static int ivr_read_header(AVFormatContext *s) { unsigned tag, type, len, tlen, value; int i, j, n, count, nb_streams = 0, ret; uint8_t key[256], val[256]; AVIOContext *pb = s->pb; AVStream *st; int64_t pos, offset, temp; pos = avio_tell(pb); tag = avio_rl32(pb); if (tag == MKTAG('.','R','1','M')) { if (avio_rb16(pb) != 1) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); avio_skip(pb, 5); temp = avio_rb64(pb); while (!avio_feof(pb) && temp) { offset = temp; temp = avio_rb64(pb); } avio_skip(pb, offset - avio_tell(pb)); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; len = avio_rb32(pb); avio_skip(pb, len); if (avio_r8(pb) != 2) return AVERROR_INVALIDDATA; avio_skip(pb, 16); pos = avio_tell(pb); tag = avio_rl32(pb); } if (tag != MKTAG('.','R','E','C')) return AVERROR_INVALIDDATA; if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4) { av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); } av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "StreamCount", tlen)) { nb_streams = value = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } for (n = 0; n < nb_streams; n++) { st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->priv_data = ff_rm_alloc_rmstream(); if (!st->priv_data) return AVERROR(ENOMEM); if (avio_r8(pb) != 1) return AVERROR_INVALIDDATA; count = avio_rb32(pb); for (i = 0; i < count; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; type = avio_r8(pb); tlen = avio_rb32(pb); avio_get_str(pb, tlen, key, sizeof(key)); len = avio_rb32(pb); if (type == 5) { avio_get_str(pb, len, val, sizeof(val)); av_log(s, AV_LOG_DEBUG, "%s = '%s'\n", key, val); } else if (type == 4 && !strncmp(key, "OpaqueData", tlen)) { ret = ffio_ensure_seekback(pb, 4); if (ret < 0) return ret; if (avio_rb32(pb) == MKBETAG('M', 'L', 'T', 'I')) { ret = rm_read_multi(s, pb, st, NULL); } else { avio_seek(pb, -4, SEEK_CUR); ret = ff_rm_read_mdpr_codecdata(s, pb, st, st->priv_data, len, NULL); } if (ret < 0) return ret; } else if (type == 4) { int j; av_log(s, AV_LOG_DEBUG, "%s = '0x", key); for (j = 0; j < len; j++) av_log(s, AV_LOG_DEBUG, "%X", avio_r8(pb)); av_log(s, AV_LOG_DEBUG, "'\n"); } else if (len == 4 && type == 3 && !strncmp(key, "Duration", tlen)) { st->duration = avio_rb32(pb); } else if (len == 4 && type == 3) { value = avio_rb32(pb); av_log(s, AV_LOG_DEBUG, "%s = %d\n", key, value); } else { av_log(s, AV_LOG_DEBUG, "Skipping unsupported key: %s\n", key); avio_skip(pb, len); } } } if (avio_r8(pb) != 6) return AVERROR_INVALIDDATA; avio_skip(pb, 12); avio_skip(pb, avio_rb64(pb) + pos - avio_tell(s->pb)); if (avio_r8(pb) != 8) return AVERROR_INVALIDDATA; avio_skip(pb, 8); return 0; } static int ivr_read_packet(AVFormatContext *s, AVPacket *pkt) { RMDemuxContext *rm = s->priv_data; int ret = AVERROR_EOF, opcode; AVIOContext *pb = s->pb; unsigned size, index; int64_t pos, pts; if (avio_feof(pb) || rm->data_end) return AVERROR_EOF; pos = avio_tell(pb); for (;;) { if (rm->audio_pkt_cnt) { // If there are queued audio packet return them first AVStream *st; st = s->streams[rm->audio_stream_num]; ret = ff_rm_retrieve_cache(s, pb, st, st->priv_data, pkt); if (ret < 0) { return ret; } } else { if (rm->remaining_len) { avio_skip(pb, rm->remaining_len); rm->remaining_len = 0; } if (avio_feof(pb)) return AVERROR_EOF; opcode = avio_r8(pb); if (opcode == 2) { AVStream *st; int seq = 1; pts = avio_rb32(pb); index = avio_rb16(pb); if (index >= s->nb_streams) return AVERROR_INVALIDDATA; avio_skip(pb, 4); size = avio_rb32(pb); avio_skip(pb, 4); if (size < 1 || size > INT_MAX/4) { av_log(s, AV_LOG_ERROR, "size %u is invalid\n", size); return AVERROR_INVALIDDATA; } st = s->streams[index]; ret = ff_rm_parse_packet(s, pb, st, st->priv_data, size, pkt, &seq, 0, pts); if (ret < -1) { return ret; } else if (ret) { continue; } pkt->pos = pos; pkt->pts = pts; pkt->stream_index = index; } else if (opcode == 7) { pos = avio_rb64(pb); if (!pos) { rm->data_end = 1; return AVERROR_EOF; } } else { av_log(s, AV_LOG_ERROR, "Unsupported opcode=%d at %"PRIX64"\n", opcode, avio_tell(pb) - 1); return AVERROR(EIO); } } break; } return ret; } AVInputFormat ff_ivr_demuxer = { .name = "ivr", .long_name = NULL_IF_CONFIG_SMALL("IVR (Internet Video Recording)"), .priv_data_size = sizeof(RMDemuxContext), .read_probe = ivr_probe, .read_header = ivr_read_header, .read_packet = ivr_read_packet, .read_close = rm_read_close, .extensions = "ivr", };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2761_0
crossvul-cpp_data_good_2783_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/channel.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/constitute.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/registry.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *,ExceptionInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image,ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->alpha_trait != BlendPixelTrait || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringFalse(option) != MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; register ssize_t i; gamma=QuantumScale*GetPixelAlpha(image, q); if (gamma != 0.0 && gamma != 1.0) { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (channel != AlphaPixelChannel) q[i]=ClampToQuantum((q[i]-((1.0-gamma)*QuantumRange))/gamma); } } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == OpaqueAlpha) return(MagickTrue); image->alpha_trait=BlendPixelTrait; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(image,(Quantum) (QuantumScale*(GetPixelAlpha(image,q))* opacity),q); else if (opacity > 0) SetPixelAlpha(image,(Quantum) (QuantumRange*(GetPixelAlpha(image,q)/ (MagickRealType) opacity)),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; PixelInfo color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->alpha_trait=BlendPixelTrait; GetPixelInfo(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color,exception); status=CompositeImage(complete_mask,mask,OverCompositeOp,MagickTrue, mask->page.x-image->page.x,mask->page.y-image->page.y,exception); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->alpha_trait=BlendPixelTrait; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register Quantum *magick_restrict q; register Quantum *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (Quantum *) NULL) || (p == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(image,q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(image,ClampToQuantum(intensity*(QuantumScale*alpha)),q); else if (intensity > 0) SetPixelAlpha(image,ClampToQuantum((alpha/intensity)*QuantumRange),q); q+=GetPixelChannels(image); p+=GetPixelChannels(complete_mask); } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static MagickBooleanType NegateCMYK(Image *image,ExceptionInfo *exception) { ChannelType channel_mask; MagickBooleanType status; channel_mask=SetImageChannelMask(image,(ChannelType)(AllChannels &~ AlphaChannel)); status=NegateImage(image,MagickFalse,exception); (void) SetImageChannelMask(image,channel_mask); return(status); } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image,ExceptionInfo *exception) { const unsigned char *p; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const unsigned char *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile,exception); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if ((name_length % 2) == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) return; p=PushLongPixel(MSBEndian,p,&count); if ((p+count) > (blocks+length)) return; switch (id) { case 0x03ed: { char value[MagickPathExtent]; unsigned short resolution; /* Resolution info. */ if (count < 16) return; p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.x=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.x); (void) SetImageProperty(image,"tiff:XResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->resolution.y=(double) resolution; (void) FormatLocaleString(value,MagickPathExtent,"%g", image->resolution.y); (void) SetImageProperty(image,"tiff:YResolution",value,exception); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((count > 3) && (*(p+4) == 0)) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel,Quantum *q, ExceptionInfo *exception) { if (image->storage_class == PseudoClass) { PixelInfo *color; if (type == 0) { if (packet_size == 1) SetPixelIndex(image,ScaleQuantumToChar(pixel),q); else SetPixelIndex(image,ScaleQuantumToShort(pixel),q); } color=image->colormap+(ssize_t) ConstrainColormapIndex(image, GetPixelIndex(image,q),exception); if ((type == 0) && (channels > 1)) return; else color->alpha=(MagickRealType) pixel; SetPixelViaPixelInfo(image,color,q); return; } switch (type) { case -1: { SetPixelAlpha(image,pixel,q); break; } case -2: case 0: { SetPixelRed(image,pixel,q); break; } case 1: { SetPixelGreen(image,pixel,q); break; } case 2: { SetPixelBlue(image,pixel,q); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelBlack(image,pixel,q); else if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->alpha_trait != UndefinedPixelTrait) SetPixelAlpha(image,pixel,q); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image, const size_t channels,const size_t row,const ssize_t type, const unsigned char *pixels,ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register Quantum *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (Quantum *) NULL) return MagickFalse; packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q,exception); q+=GetPixelChannels(image); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit = 0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q,exception); q+=GetPixelChannels(image); x++; } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; if (length > row_size + 256) // arbitrary number { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"InvalidLength",image->filename); } compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream,Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { SetImageType(mask,GrayscaleType,exception); channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MagickPathExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image,exception); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) layer_info->image->compose=NoCompositeOp; if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace,exception); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace,exception); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MagickPathExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name, exception); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->alpha_trait=BlendPixelTrait; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateCMYK(layer_info->image,exception); if ((status != MagickFalse) && (layer_info->mask.image != (Image *) NULL)) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->alpha_trait=BlendPixelTrait; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } count=ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width,(double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info,exception); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickFalse); return(ReadPSDLayersInternal(image,image_info,psd_info,skip_layers, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image *image,const PSDInfo *psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateCMYK(image,exception); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); if (SetImageBackgroundColor(image,exception) == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace,exception); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace,exception); if (psd_info.channels > 4) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536, exception); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace,exception); if (psd_info.channels > 1) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); } else if (psd_info.channels > 3) SetImageAlphaChannel(image,ActivateAlphaChannel,exception); /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->alpha_trait=UndefinedPixelTrait; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image, exception); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if ((has_merged_image != MagickFalse) || (GetImageListLength(image) == 1)) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel,exception); image->background_color.alpha=TransparentAlpha; image->background_color.alpha_trait=BlendPixelTrait; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("PSD","PSB","Adobe Large Document Format"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("PSD","PSD","Adobe Photoshop bitmap"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->flags|=CoderDecoderSeekableStreamFlag; entry->flags|=CoderEncoderSeekableStreamFlag; (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels, ExceptionInfo *exception) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const Quantum *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=(unsigned char *) GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,exception); if (p == (const Quantum *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels, exception); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(const Image *image, ExceptionInfo *exception) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); } return(compact_pixels); } static size_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate, ExceptionInfo *exception) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsImageGray(next_image) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->alpha_trait != UndefinedPixelTrait) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsImageGray(next_image) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->alpha_trait != UndefinedPixelTrait) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate,exception); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateCMYK(next_image,exception); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask,exception); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue,exception); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->resolution.x+0.5; y_resolution=2.54*65536.0*image->resolution.y+0.5; units=2; } else { x_resolution=65536.0*image->resolution.x+0.5; y_resolution=65536.0*image->resolution.y+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info,exception); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { char layer_name[MagickPathExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->alpha_trait != UndefinedPixelTrait) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,exception) != MagickFalse)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorAlphaType) && (image->storage_class == PseudoClass)) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass,exception); if (image->colorspace != CMYKColorspace) num_channels=(image->alpha_trait != UndefinedPixelTrait ? 4UL : 3UL); else num_channels=(image->alpha_trait != UndefinedPixelTrait ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsImageGray(image) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsImageMonochrome(image) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace,exception); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace,exception); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsImageGray(image) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } base_image=GetNextImageInList(image); if (base_image == (Image *) NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->alpha_trait != UndefinedPixelTrait) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property,exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsImageGray(next_image) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->alpha_trait != UndefinedPixelTrait) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->alpha_trait != UndefinedPixelTrait) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue,exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image,exception); property=(const char *) GetImageProperty(next_image,"label",exception); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MagickPathExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+ mask->page.y); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+ mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue,exception); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0,MagickFalse, exception) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-834/c/good_2783_0
crossvul-cpp_data_bad_2784_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS DDDD % % P P SS D D % % PPPP SSS D D % % P SS D D % % P SSSSS DDDD % % % % % % Read/Write Adobe Photoshop Image Format % % % % Software Design % % Cristy % % Leonard Rosenthol % % July 1992 % % Dirk Lemstra % % December 2013 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/channel.h" #include "magick/colormap.h" #include "magick/colormap-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/pixel.h" #include "magick/pixel-accessor.h" #include "magick/policy.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/registry.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #ifdef MAGICKCORE_ZLIB_DELEGATE #include <zlib.h> #endif #include "psd-private.h" /* Define declaractions. */ #define MaxPSDChannels 56 #define PSDQuantum(x) (((ssize_t) (x)+1) & -2) /* Enumerated declaractions. */ typedef enum { Raw = 0, RLE = 1, ZipWithoutPrediction = 2, ZipWithPrediction = 3 } PSDCompressionType; typedef enum { BitmapMode = 0, GrayscaleMode = 1, IndexedMode = 2, RGBMode = 3, CMYKMode = 4, MultichannelMode = 7, DuotoneMode = 8, LabMode = 9 } PSDImageType; /* Typedef declaractions. */ typedef struct _ChannelInfo { short int type; size_t size; } ChannelInfo; typedef struct _MaskInfo { Image *image; RectangleInfo page; unsigned char background, flags; } MaskInfo; typedef struct _LayerInfo { ChannelInfo channel_info[MaxPSDChannels]; char blendkey[4]; Image *image; MaskInfo mask; Quantum opacity; RectangleInfo page; size_t offset_x, offset_y; unsigned char clipping, flags, name[256], visible; unsigned short channels; StringInfo *info; } LayerInfo; /* Forward declarations. */ static MagickBooleanType WritePSDImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S D % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPSD()() returns MagickTrue if the image format type, identified by the % magick string, is PSD. % % The format of the IsPSD method is: % % MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPSD(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((const char *) magick,"8BPS",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSDImage() reads an Adobe Photoshop image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadPSDImage method is: % % Image *ReadPSDImage(image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static const char *CompositeOperatorToPSDBlendMode(CompositeOperator op) { const char *blend_mode; switch (op) { case ColorBurnCompositeOp: blend_mode = "idiv"; break; case ColorDodgeCompositeOp: blend_mode = "div "; break; case ColorizeCompositeOp: blend_mode = "colr"; break; case DarkenCompositeOp: blend_mode = "dark"; break; case DifferenceCompositeOp: blend_mode = "diff"; break; case DissolveCompositeOp: blend_mode = "diss"; break; case ExclusionCompositeOp: blend_mode = "smud"; break; case HardLightCompositeOp: blend_mode = "hLit"; break; case HardMixCompositeOp: blend_mode = "hMix"; break; case HueCompositeOp: blend_mode = "hue "; break; case LightenCompositeOp: blend_mode = "lite"; break; case LinearBurnCompositeOp: blend_mode = "lbrn"; break; case LinearDodgeCompositeOp:blend_mode = "lddg"; break; case LinearLightCompositeOp:blend_mode = "lLit"; break; case LuminizeCompositeOp: blend_mode = "lum "; break; case MultiplyCompositeOp: blend_mode = "mul "; break; case OverCompositeOp: blend_mode = "norm"; break; case OverlayCompositeOp: blend_mode = "over"; break; case PinLightCompositeOp: blend_mode = "pLit"; break; case SaturateCompositeOp: blend_mode = "sat "; break; case ScreenCompositeOp: blend_mode = "scrn"; break; case SoftLightCompositeOp: blend_mode = "sLit"; break; case VividLightCompositeOp: blend_mode = "vLit"; break; default: blend_mode = "norm"; break; } return(blend_mode); } /* For some reason Photoshop seems to blend semi-transparent pixels with white. This method reverts the blending. This can be disabled by setting the option 'psd:alpha-unblend' to off. */ static MagickBooleanType CorrectPSDAlphaBlend(const ImageInfo *image_info, Image *image, ExceptionInfo* exception) { const char *option; MagickBooleanType status; ssize_t y; if (image->matte == MagickFalse || image->colorspace != sRGBColorspace) return(MagickTrue); option=GetImageOption(image_info,"psd:alpha-unblend"); if (IsStringNotFalse(option) == MagickFalse) return(MagickTrue); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { double gamma; gamma=QuantumScale*GetPixelAlpha(q); if (gamma != 0.0 && gamma != 1.0) { SetPixelRed(q,(GetPixelRed(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelGreen(q,(GetPixelGreen(q)-((1.0-gamma)*QuantumRange))/gamma); SetPixelBlue(q,(GetPixelBlue(q)-((1.0-gamma)*QuantumRange))/gamma); } q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static inline CompressionType ConvertPSDCompression( PSDCompressionType compression) { switch (compression) { case RLE: return RLECompression; case ZipWithPrediction: case ZipWithoutPrediction: return ZipCompression; default: return NoCompression; } } static MagickBooleanType ApplyPSDLayerOpacity(Image *image,Quantum opacity, MagickBooleanType revert,ExceptionInfo *exception) { MagickBooleanType status; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying layer opacity %.20g", (double) opacity); if (opacity == QuantumRange) return(MagickTrue); image->matte=MagickTrue; status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if (revert == MagickFalse) SetPixelAlpha(q,(Quantum) (QuantumScale*(GetPixelAlpha(q)*opacity))); else if (opacity > 0) SetPixelAlpha(q,(Quantum) (QuantumRange*(GetPixelAlpha(q)/ (MagickRealType) opacity))); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } return(status); } static MagickBooleanType ApplyPSDOpacityMask(Image *image,const Image *mask, Quantum background,MagickBooleanType revert,ExceptionInfo *exception) { Image *complete_mask; MagickBooleanType status; MagickPixelPacket color; ssize_t y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " applying opacity mask"); complete_mask=CloneImage(image,image->columns,image->rows,MagickTrue, exception); complete_mask->matte=MagickTrue; GetMagickPixelPacket(complete_mask,&color); color.red=background; SetImageColor(complete_mask,&color); status=CompositeImage(complete_mask,OverCompositeOp,mask, mask->page.x-image->page.x,mask->page.y-image->page.y); if (status == MagickFalse) { complete_mask=DestroyImage(complete_mask); return(status); } image->matte=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register PixelPacket *magick_restrict q; register PixelPacket *p; register ssize_t x; if (status == MagickFalse) continue; q=GetAuthenticPixels(image,0,y,image->columns,1,exception); p=GetAuthenticPixels(complete_mask,0,y,complete_mask->columns,1,exception); if ((q == (PixelPacket *) NULL) || (p == (PixelPacket *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { MagickRealType alpha, intensity; alpha=GetPixelAlpha(q); intensity=GetPixelIntensity(complete_mask,p); if (revert == MagickFalse) SetPixelAlpha(q,ClampToQuantum(intensity*(QuantumScale*alpha))); else if (intensity > 0) SetPixelAlpha(q,ClampToQuantum((alpha/intensity)*QuantumRange)); q++; p++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) status=MagickFalse; } complete_mask=DestroyImage(complete_mask); return(status); } static void PreservePSDOpacityMask(Image *image,LayerInfo* layer_info, ExceptionInfo *exception) { char *key; RandomInfo *random_info; StringInfo *key_info; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " preserving opacity mask"); random_info=AcquireRandomInfo(); key_info=GetRandomKey(random_info,2+1); key=(char *) GetStringInfoDatum(key_info); key[8]=layer_info->mask.background; key[9]='\0'; layer_info->mask.image->page.x+=layer_info->page.x; layer_info->mask.image->page.y+=layer_info->page.y; (void) SetImageRegistry(ImageRegistryType,(const char *) key, layer_info->mask.image,exception); (void) SetImageArtifact(layer_info->image,"psd:opacity-mask", (const char *) key); key_info=DestroyStringInfo(key_info); random_info=DestroyRandomInfo(random_info); } static ssize_t DecodePSDPixels(const size_t number_compact_pixels, const unsigned char *compact_pixels,const ssize_t depth, const size_t number_pixels,unsigned char *pixels) { #define CheckNumberCompactPixels \ if (packets == 0) \ return(i); \ packets-- #define CheckNumberPixels(count) \ if (((ssize_t) i + count) > (ssize_t) number_pixels) \ return(i); \ i+=count int pixel; register ssize_t i, j; size_t length; ssize_t packets; packets=(ssize_t) number_compact_pixels; for (i=0; (packets > 1) && (i < (ssize_t) number_pixels); ) { packets--; length=(size_t) (*compact_pixels++); if (length == 128) continue; if (length > 128) { length=256-length+1; CheckNumberCompactPixels; pixel=(*compact_pixels++); for (j=0; j < (ssize_t) length; j++) { switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(pixel >> 7) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 6) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 5) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 4) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 3) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 2) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 1) & 0x01 ? 0U : 255U; *pixels++=(pixel >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(unsigned char) ((pixel >> 6) & 0x03); *pixels++=(unsigned char) ((pixel >> 4) & 0x03); *pixels++=(unsigned char) ((pixel >> 2) & 0x03); *pixels++=(unsigned char) ((pixel & 0x03) & 0x03); break; } case 4: { CheckNumberPixels(2); *pixels++=(unsigned char) ((pixel >> 4) & 0xff); *pixels++=(unsigned char) ((pixel & 0x0f) & 0xff); break; } default: { CheckNumberPixels(1); *pixels++=(unsigned char) pixel; break; } } } continue; } length++; for (j=0; j < (ssize_t) length; j++) { CheckNumberCompactPixels; switch (depth) { case 1: { CheckNumberPixels(8); *pixels++=(*compact_pixels >> 7) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 6) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 5) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 4) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 3) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 2) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 1) & 0x01 ? 0U : 255U; *pixels++=(*compact_pixels >> 0) & 0x01 ? 0U : 255U; break; } case 2: { CheckNumberPixels(4); *pixels++=(*compact_pixels >> 6) & 0x03; *pixels++=(*compact_pixels >> 4) & 0x03; *pixels++=(*compact_pixels >> 2) & 0x03; *pixels++=(*compact_pixels & 0x03) & 0x03; break; } case 4: { CheckNumberPixels(2); *pixels++=(*compact_pixels >> 4) & 0xff; *pixels++=(*compact_pixels & 0x0f) & 0xff; break; } default: { CheckNumberPixels(1); *pixels++=(*compact_pixels); break; } } compact_pixels++; } } return(i); } static inline LayerInfo *DestroyLayerInfo(LayerInfo *layer_info, const ssize_t number_layers) { ssize_t i; for (i=0; i<number_layers; i++) { if (layer_info[i].image != (Image *) NULL) layer_info[i].image=DestroyImage(layer_info[i].image); if (layer_info[i].mask.image != (Image *) NULL) layer_info[i].mask.image=DestroyImage(layer_info[i].mask.image); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); } return (LayerInfo *) RelinquishMagickMemory(layer_info); } static inline size_t GetPSDPacketSize(Image *image) { if (image->storage_class == PseudoClass) { if (image->colors > 256) return(2); else if (image->depth > 8) return(2); } else if (image->depth > 8) return(2); return(1); } static inline MagickSizeType GetPSDSize(const PSDInfo *psd_info,Image *image) { if (psd_info->version == 1) return((MagickSizeType) ReadBlobLong(image)); return((MagickSizeType) ReadBlobLongLong(image)); } static inline size_t GetPSDRowSize(Image *image) { if (image->depth == 1) return(((image->columns+7)/8)*GetPSDPacketSize(image)); else return(image->columns*GetPSDPacketSize(image)); } static const char *ModeToString(PSDImageType type) { switch (type) { case BitmapMode: return "Bitmap"; case GrayscaleMode: return "Grayscale"; case IndexedMode: return "Indexed"; case RGBMode: return "RGB"; case CMYKMode: return "CMYK"; case MultichannelMode: return "Multichannel"; case DuotoneMode: return "Duotone"; case LabMode: return "L*A*B"; default: return "unknown"; } } static void ParseImageResourceBlocks(Image *image, const unsigned char *blocks,size_t length, MagickBooleanType *has_merged_image) { const unsigned char *p; StringInfo *profile; unsigned char name_length; unsigned int count; unsigned short id, short_sans; if (length < 16) return; profile=BlobToStringInfo((const void *) NULL,length); SetStringInfoDatum(profile,blocks); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); for (p=blocks; (p >= blocks) && (p < (blocks+length-7)); ) { if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p+=4; p=PushShortPixel(MSBEndian,p,&id); p=PushCharPixel(p,&name_length); if (name_length % 2 == 0) name_length++; p+=name_length; if (p > (blocks+length-4)) return; p=PushLongPixel(MSBEndian,p,&count); if ((p+count) > (blocks+length)) return; switch (id) { case 0x03ed: { char value[MaxTextExtent]; unsigned short resolution; /* Resolution info. */ if (count < 16) return; p=PushShortPixel(MSBEndian,p,&resolution); image->x_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->x_resolution); (void) SetImageProperty(image,"tiff:XResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&resolution); image->y_resolution=(double) resolution; (void) FormatLocaleString(value,MaxTextExtent,"%g", image->y_resolution); (void) SetImageProperty(image,"tiff:YResolution",value); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushShortPixel(MSBEndian,p,&short_sans); image->units=PixelsPerInchResolution; break; } case 0x0421: { if ((count > 3) && (*(p+4) == 0)) *has_merged_image=MagickFalse; p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } return; } static CompositeOperator PSDBlendModeToCompositeOperator(const char *mode) { if (mode == (const char *) NULL) return(OverCompositeOp); if (LocaleNCompare(mode,"norm",4) == 0) return(OverCompositeOp); if (LocaleNCompare(mode,"mul ",4) == 0) return(MultiplyCompositeOp); if (LocaleNCompare(mode,"diss",4) == 0) return(DissolveCompositeOp); if (LocaleNCompare(mode,"diff",4) == 0) return(DifferenceCompositeOp); if (LocaleNCompare(mode,"dark",4) == 0) return(DarkenCompositeOp); if (LocaleNCompare(mode,"lite",4) == 0) return(LightenCompositeOp); if (LocaleNCompare(mode,"hue ",4) == 0) return(HueCompositeOp); if (LocaleNCompare(mode,"sat ",4) == 0) return(SaturateCompositeOp); if (LocaleNCompare(mode,"colr",4) == 0) return(ColorizeCompositeOp); if (LocaleNCompare(mode,"lum ",4) == 0) return(LuminizeCompositeOp); if (LocaleNCompare(mode,"scrn",4) == 0) return(ScreenCompositeOp); if (LocaleNCompare(mode,"over",4) == 0) return(OverlayCompositeOp); if (LocaleNCompare(mode,"hLit",4) == 0) return(HardLightCompositeOp); if (LocaleNCompare(mode,"sLit",4) == 0) return(SoftLightCompositeOp); if (LocaleNCompare(mode,"smud",4) == 0) return(ExclusionCompositeOp); if (LocaleNCompare(mode,"div ",4) == 0) return(ColorDodgeCompositeOp); if (LocaleNCompare(mode,"idiv",4) == 0) return(ColorBurnCompositeOp); if (LocaleNCompare(mode,"lbrn",4) == 0) return(LinearBurnCompositeOp); if (LocaleNCompare(mode,"lddg",4) == 0) return(LinearDodgeCompositeOp); if (LocaleNCompare(mode,"lLit",4) == 0) return(LinearLightCompositeOp); if (LocaleNCompare(mode,"vLit",4) == 0) return(VividLightCompositeOp); if (LocaleNCompare(mode,"pLit",4) == 0) return(PinLightCompositeOp); if (LocaleNCompare(mode,"hMix",4) == 0) return(HardMixCompositeOp); return(OverCompositeOp); } static inline void ReversePSDString(Image *image,char *p,size_t length) { char *q; if (image->endian == MSBEndian) return; q=p+length; for(--q; p < q; ++p, --q) { *p = *p ^ *q, *q = *p ^ *q, *p = *p ^ *q; } } static inline void SetPSDPixel(Image *image,const size_t channels, const ssize_t type,const size_t packet_size,const Quantum pixel, PixelPacket *q,IndexPacket *indexes,ssize_t x) { if (image->storage_class == PseudoClass) { PixelPacket *color; if (type == 0) { if (packet_size == 1) SetPixelIndex(indexes+x,ScaleQuantumToChar(pixel)); else SetPixelIndex(indexes+x,ScaleQuantumToShort(pixel)); } color=image->colormap+(ssize_t) ConstrainColormapIndex(image, GetPixelIndex(indexes+x)); if ((type == 0) && (channels > 1)) return; else SetPixelAlpha(color,pixel); SetPixelRGBO(q,color); return; } switch (type) { case -1: { SetPixelAlpha(q,pixel); break; } case -2: case 0: { SetPixelRed(q,pixel); if (channels < 3 || type == -2) { SetPixelGreen(q,GetPixelRed(q)); SetPixelBlue(q,GetPixelRed(q)); } break; } case 1: { SetPixelGreen(q,pixel); break; } case 2: { SetPixelBlue(q,pixel); break; } case 3: { if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,pixel); else if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } case 4: { if ((IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) && (channels > 3)) break; if (image->matte != MagickFalse) SetPixelAlpha(q,pixel); break; } } } static MagickBooleanType ReadPSDChannelPixels(Image *image,const size_t channels, const size_t row,const ssize_t type,const unsigned char *pixels, ExceptionInfo *exception) { Quantum pixel; register const unsigned char *p; register IndexPacket *indexes; register PixelPacket *q; register ssize_t x; size_t packet_size; unsigned short nibble; p=pixels; q=GetAuthenticPixels(image,0,row,image->columns,1,exception); if (q == (PixelPacket *) NULL) return MagickFalse; indexes=GetAuthenticIndexQueue(image); packet_size=GetPSDPacketSize(image); for (x=0; x < (ssize_t) image->columns; x++) { if (packet_size == 1) pixel=ScaleCharToQuantum(*p++); else { p=PushShortPixel(MSBEndian,p,&nibble); pixel=ScaleShortToQuantum(nibble); } if (image->depth > 1) { SetPSDPixel(image,channels,type,packet_size,pixel,q++,indexes,x); } else { ssize_t bit, number_bits; number_bits=image->columns-x; if (number_bits > 8) number_bits=8; for (bit=0; bit < number_bits; bit++) { SetPSDPixel(image,channels,type,packet_size,(((unsigned char) pixel) & (0x01 << (7-bit))) != 0 ? 0 : QuantumRange,q++,indexes,x++); } if (x != (ssize_t) image->columns) x--; continue; } } return(SyncAuthenticPixels(image,exception)); } static MagickBooleanType ReadPSDChannelRaw(Image *image,const size_t channels, const ssize_t type,ExceptionInfo *exception) { MagickBooleanType status; size_t count, row_size; ssize_t y; unsigned char *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RAW"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,row_size,pixels); if (count != row_size) break; status=ReadPSDChannelPixels(image,channels,y,type,pixels,exception); if (status == MagickFalse) break; } pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } static inline MagickOffsetType *ReadPSDRLESizes(Image *image, const PSDInfo *psd_info,const size_t size) { MagickOffsetType *sizes; ssize_t y; sizes=(MagickOffsetType *) AcquireQuantumMemory(size,sizeof(*sizes)); if(sizes != (MagickOffsetType *) NULL) { for (y=0; y < (ssize_t) size; y++) { if (psd_info->version == 1) sizes[y]=(MagickOffsetType) ReadBlobShort(image); else sizes[y]=(MagickOffsetType) ReadBlobLong(image); } } return sizes; } static MagickBooleanType ReadPSDChannelRLE(Image *image,const PSDInfo *psd_info, const ssize_t type,MagickOffsetType *sizes,ExceptionInfo *exception) { MagickBooleanType status; size_t length, row_size; ssize_t count, y; unsigned char *compact_pixels, *pixels; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is RLE compressed"); row_size=GetPSDRowSize(image); pixels=(unsigned char *) AcquireQuantumMemory(row_size,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); length=0; for (y=0; y < (ssize_t) image->rows; y++) if ((MagickOffsetType) length < sizes[y]) length=(size_t) sizes[y]; compact_pixels=(unsigned char *) AcquireQuantumMemory(length,sizeof(*pixels)); if (compact_pixels == (unsigned char *) NULL) { pixels=(unsigned char *) RelinquishMagickMemory(pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(compact_pixels,0,length*sizeof(*compact_pixels)); status=MagickTrue; for (y=0; y < (ssize_t) image->rows; y++) { status=MagickFalse; count=ReadBlob(image,(size_t) sizes[y],compact_pixels); if (count != (ssize_t) sizes[y]) break; count=DecodePSDPixels((size_t) sizes[y],compact_pixels, (ssize_t) (image->depth == 1 ? 123456 : image->depth),row_size,pixels); if (count != (ssize_t) row_size) break; status=ReadPSDChannelPixels(image,psd_info->channels,y,type,pixels, exception); if (status == MagickFalse) break; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #ifdef MAGICKCORE_ZLIB_DELEGATE static MagickBooleanType ReadPSDChannelZip(Image *image,const size_t channels, const ssize_t type,const PSDCompressionType compression, const size_t compact_size,ExceptionInfo *exception) { MagickBooleanType status; register unsigned char *p; size_t count, length, packet_size, row_size; ssize_t y; unsigned char *compact_pixels, *pixels; z_stream stream; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is ZIP compressed"); compact_pixels=(unsigned char *) AcquireQuantumMemory(compact_size, sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); packet_size=GetPSDPacketSize(image); row_size=image->columns*packet_size; count=image->rows*row_size; pixels=(unsigned char *) AcquireQuantumMemory(count,sizeof(*pixels)); if (pixels == (unsigned char *) NULL) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (ReadBlob(image,compact_size,compact_pixels) != (ssize_t) compact_size) { compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; stream.next_in=(Bytef *)compact_pixels; stream.avail_in=(uInt) compact_size; stream.next_out=(Bytef *)pixels; stream.avail_out=(uInt) count; if (inflateInit(&stream) == Z_OK) { int ret; while (stream.avail_out > 0) { ret=inflate(&stream, Z_SYNC_FLUSH); if ((ret != Z_OK) && (ret != Z_STREAM_END)) { (void) inflateEnd(&stream); compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(MagickFalse); } } (void) inflateEnd(&stream); } if (compression == ZipWithPrediction) { p=pixels; while (count > 0) { length=image->columns; while (--length) { if (packet_size == 2) { p[2]+=p[0]+((p[1]+p[3]) >> 8); p[3]+=p[1]; } else *(p+1)+=*p; p+=packet_size; } p+=packet_size; count-=row_size; } } status=MagickTrue; p=pixels; for (y=0; y < (ssize_t) image->rows; y++) { status=ReadPSDChannelPixels(image,channels,y,type,p,exception); if (status == MagickFalse) break; p+=row_size; } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); pixels=(unsigned char *) RelinquishMagickMemory(pixels); return(status); } #endif static MagickBooleanType ReadPSDChannel(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info,LayerInfo* layer_info, const size_t channel,const PSDCompressionType compression, ExceptionInfo *exception) { Image *channel_image, *mask; MagickOffsetType offset; MagickBooleanType status; channel_image=image; mask=(Image *) NULL; if ((layer_info->channel_info[channel].type < -1) && (layer_info->mask.page.width > 0) && (layer_info->mask.page.height > 0)) { const char *option; /* Ignore mask that is not a user supplied layer mask, if the mask is disabled or if the flags have unsupported values. */ option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if ((layer_info->channel_info[channel].type != -2) || (layer_info->mask.flags > 2) || ((layer_info->mask.flags & 0x02) && (IsStringTrue(option) == MagickFalse))) { SeekBlob(image,layer_info->channel_info[channel].size-2,SEEK_CUR); return(MagickTrue); } mask=CloneImage(image,layer_info->mask.page.width, layer_info->mask.page.height,MagickFalse,exception); if (mask != (Image *) NULL) { mask->matte=MagickFalse; channel_image=mask; } } offset=TellBlob(image); status=MagickFalse; switch(compression) { case Raw: status=ReadPSDChannelRaw(channel_image,psd_info->channels, layer_info->channel_info[channel].type,exception); break; case RLE: { MagickOffsetType *sizes; sizes=ReadPSDRLESizes(channel_image,psd_info,channel_image->rows); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ReadPSDChannelRLE(channel_image,psd_info, layer_info->channel_info[channel].type,sizes,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); } break; case ZipWithPrediction: case ZipWithoutPrediction: #ifdef MAGICKCORE_ZLIB_DELEGATE status=ReadPSDChannelZip(channel_image,layer_info->channels, layer_info->channel_info[channel].type,compression, layer_info->channel_info[channel].size-2,exception); #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (ZLIB)",image->filename); #endif break; default: (void) ThrowMagickException(exception,GetMagickModule(),TypeWarning, "CompressionNotSupported","'%.20g'",(double) compression); break; } SeekBlob(image,offset+layer_info->channel_info[channel].size-2,SEEK_SET); if (status == MagickFalse) { if (mask != (Image *) NULL) DestroyImage(mask); ThrowBinaryException(CoderError,"UnableToDecompressImage", image->filename); } layer_info->mask.image=mask; return(status); } static MagickBooleanType ReadPSDLayer(Image *image,const ImageInfo *image_info, const PSDInfo *psd_info,LayerInfo* layer_info,ExceptionInfo *exception) { char message[MaxTextExtent]; MagickBooleanType status; PSDCompressionType compression; ssize_t j; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " setting up new layer image"); if (psd_info->mode != IndexedMode) (void) SetImageBackgroundColor(layer_info->image); layer_info->image->compose=PSDBlendModeToCompositeOperator( layer_info->blendkey); if (layer_info->visible == MagickFalse) { layer_info->image->compose=NoCompositeOp; (void) SetImageArtifact(layer_info->image,"psd:layer.invisible","true"); } if (psd_info->mode == CMYKMode) SetImageColorspace(layer_info->image,CMYKColorspace); else if ((psd_info->mode == BitmapMode) || (psd_info->mode == DuotoneMode) || (psd_info->mode == GrayscaleMode)) SetImageColorspace(layer_info->image,GRAYColorspace); /* Set up some hidden attributes for folks that need them. */ (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.x); (void) SetImageArtifact(layer_info->image,"psd:layer.x",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g", (double) layer_info->page.y); (void) SetImageArtifact(layer_info->image,"psd:layer.y",message); (void) FormatLocaleString(message,MaxTextExtent,"%.20g",(double) layer_info->opacity); (void) SetImageArtifact(layer_info->image,"psd:layer.opacity",message); (void) SetImageProperty(layer_info->image,"label",(char *) layer_info->name); status=MagickTrue; for (j=0; j < (ssize_t) layer_info->channels; j++) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for channel %.20g",(double) j); compression=(PSDCompressionType) ReadBlobShort(layer_info->image); layer_info->image->compression=ConvertPSDCompression(compression); if (layer_info->channel_info[j].type == -1) layer_info->image->matte=MagickTrue; status=ReadPSDChannel(layer_info->image,image_info,psd_info,layer_info,j, compression,exception); InheritException(exception,&layer_info->image->exception); if (status == MagickFalse) break; } if (status != MagickFalse) status=ApplyPSDLayerOpacity(layer_info->image,layer_info->opacity, MagickFalse,exception); if ((status != MagickFalse) && (layer_info->image->colorspace == CMYKColorspace)) status=NegateImage(layer_info->image,MagickFalse); if (status != MagickFalse && layer_info->mask.image != (Image *) NULL) { const char *option; layer_info->mask.image->page.x=layer_info->mask.page.x; layer_info->mask.image->page.y=layer_info->mask.page.y; /* Do not composite the mask when it is disabled */ if ((layer_info->mask.flags & 0x02) == 0x02) layer_info->mask.image->compose=NoCompositeOp; else status=ApplyPSDOpacityMask(layer_info->image,layer_info->mask.image, layer_info->mask.background == 0 ? 0 : QuantumRange,MagickFalse, exception); option=GetImageOption(image_info,"psd:preserve-opacity-mask"); if (IsStringTrue(option) != MagickFalse) PreservePSDOpacityMask(image,layer_info,exception); layer_info->mask.image=DestroyImage(layer_info->mask.image); } return(status); } static MagickBooleanType ReadPSDLayersInternal(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { char type[4]; LayerInfo *layer_info; MagickSizeType size; MagickBooleanType status; register ssize_t i; ssize_t count, j, number_layers; size=GetPSDSize(psd_info,image); if (size == 0) { /* Skip layers & masks. */ (void) ReadBlobLong(image); count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); status=MagickFalse; if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) return(MagickTrue); else { count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count != 0) && (LocaleNCompare(type,"Lr16",4) == 0)) size=GetPSDSize(psd_info,image); else return(MagickTrue); } } status=MagickTrue; if (size != 0) { layer_info=(LayerInfo *) NULL; number_layers=(short) ReadBlobShort(image); if (number_layers < 0) { /* The first alpha channel in the merged result contains the transparency data for the merged result. */ number_layers=MagickAbsoluteValue(number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " negative layer count corrected for"); image->matte=MagickTrue; } /* We only need to know if the image has an alpha channel */ if (skip_layers != MagickFalse) return(MagickTrue); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image contains %.20g layers",(double) number_layers); if (number_layers == 0) ThrowBinaryException(CorruptImageError,"InvalidNumberOfLayers", image->filename); layer_info=(LayerInfo *) AcquireQuantumMemory((size_t) number_layers, sizeof(*layer_info)); if (layer_info == (LayerInfo *) NULL) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of LayerInfo failed"); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } (void) ResetMagickMemory(layer_info,0,(size_t) number_layers* sizeof(*layer_info)); for (i=0; i < number_layers; i++) { ssize_t x, y; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading layer #%.20g",(double) i+1); layer_info[i].page.y=ReadBlobSignedLong(image); layer_info[i].page.x=ReadBlobSignedLong(image); y=ReadBlobSignedLong(image); x=ReadBlobSignedLong(image); layer_info[i].page.width=(size_t) (x-layer_info[i].page.x); layer_info[i].page.height=(size_t) (y-layer_info[i].page.y); layer_info[i].channels=ReadBlobShort(image); if (layer_info[i].channels > MaxPSDChannels) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"MaximumChannelsExceeded", image->filename); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " offset(%.20g,%.20g), size(%.20g,%.20g), channels=%.20g", (double) layer_info[i].page.x,(double) layer_info[i].page.y, (double) layer_info[i].page.height,(double) layer_info[i].page.width,(double) layer_info[i].channels); for (j=0; j < (ssize_t) layer_info[i].channels; j++) { layer_info[i].channel_info[j].type=(short) ReadBlobShort(image); layer_info[i].channel_info[j].size=(size_t) GetPSDSize(psd_info, image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " channel[%.20g]: type=%.20g, size=%.20g",(double) j, (double) layer_info[i].channel_info[j].type, (double) layer_info[i].channel_info[j].size); } count=ReadBlob(image,4,(unsigned char *) type); ReversePSDString(image,type,4); if ((count == 0) || (LocaleNCompare(type,"8BIM",4) != 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer type was %.4s instead of 8BIM", type); layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"ImproperImageHeader", image->filename); } (void) ReadBlob(image,4,(unsigned char *) layer_info[i].blendkey); ReversePSDString(image,layer_info[i].blendkey,4); layer_info[i].opacity=(Quantum) ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); layer_info[i].clipping=(unsigned char) ReadBlobByte(image); layer_info[i].flags=(unsigned char) ReadBlobByte(image); layer_info[i].visible=!(layer_info[i].flags & 0x02); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " blend=%.4s, opacity=%.20g, clipping=%s, flags=%d, visible=%s", layer_info[i].blendkey,(double) layer_info[i].opacity, layer_info[i].clipping ? "true" : "false",layer_info[i].flags, layer_info[i].visible ? "true" : "false"); (void) ReadBlobByte(image); /* filler */ size=ReadBlobLong(image); if (size != 0) { MagickSizeType combined_length, length; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer contains additional info"); length=ReadBlobLong(image); combined_length=length+4; if (length != 0) { /* Layer mask info. */ layer_info[i].mask.page.y=ReadBlobSignedLong(image); layer_info[i].mask.page.x=ReadBlobSignedLong(image); layer_info[i].mask.page.height=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.y); layer_info[i].mask.page.width=(size_t) (ReadBlobSignedLong(image)- layer_info[i].mask.page.x); layer_info[i].mask.background=(unsigned char) ReadBlobByte( image); layer_info[i].mask.flags=(unsigned char) ReadBlobByte(image); if (!(layer_info[i].mask.flags & 0x01)) { layer_info[i].mask.page.y=layer_info[i].mask.page.y- layer_info[i].page.y; layer_info[i].mask.page.x=layer_info[i].mask.page.x- layer_info[i].page.x; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer mask: offset(%.20g,%.20g), size(%.20g,%.20g), length=%.20g", (double) layer_info[i].mask.page.x,(double) layer_info[i].mask.page.y,(double) layer_info[i].mask.page.width, (double) layer_info[i].mask.page.height,(double) ((MagickOffsetType) length)-18); /* Skip over the rest of the layer mask information. */ if (DiscardBlobBytes(image,(MagickSizeType) (length-18)) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError,"UnexpectedEndOfFile", image->filename); } } length=ReadBlobLong(image); combined_length+=length+4; if (length != 0) { /* Layer blending ranges info. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer blending ranges: length=%.20g",(double) ((MagickOffsetType) length)); /* We read it, but don't use it... */ for (j=0; j < (ssize_t) length; j+=8) { size_t blend_source=ReadBlobLong(image); size_t blend_dest=ReadBlobLong(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " source(%x), dest(%x)",(unsigned int) blend_source,(unsigned int) blend_dest); } } /* Layer name. */ length=(MagickSizeType) (unsigned char) ReadBlobByte(image); combined_length+=length+1; if (length > 0) (void) ReadBlob(image,(size_t) length++,layer_info[i].name); layer_info[i].name[length]='\0'; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer name: %s",layer_info[i].name); if ((length % 4) != 0) { length=4-(length % 4); combined_length+=length; /* Skip over the padding of the layer name */ if (DiscardBlobBytes(image,length) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } length=(MagickSizeType) size-combined_length; if (length > 0) { unsigned char *info; if (length > GetBlobSize(image)) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "InsufficientImageDataInFile",image->filename); } layer_info[i].info=AcquireStringInfo((const size_t) length); info=GetStringInfoDatum(layer_info[i].info); (void) ReadBlob(image,(const size_t) length,info); } } } for (i=0; i < number_layers; i++) { if ((layer_info[i].page.width == 0) || (layer_info[i].page.height == 0)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " layer data is empty"); if (layer_info[i].info != (StringInfo *) NULL) layer_info[i].info=DestroyStringInfo(layer_info[i].info); continue; } /* Allocate layered image. */ layer_info[i].image=CloneImage(image,layer_info[i].page.width, layer_info[i].page.height,MagickFalse,exception); if (layer_info[i].image == (Image *) NULL) { layer_info=DestroyLayerInfo(layer_info,number_layers); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " allocation of image for layer %.20g failed",(double) i); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } if (layer_info[i].info != (StringInfo *) NULL) { (void) SetImageProfile(layer_info[i].image,"psd:additional-info", layer_info[i].info); layer_info[i].info=DestroyStringInfo(layer_info[i].info); } } if (image_info->ping == MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=0; j < layer_info[i].channels; j++) { if (DiscardBlobBytes(image,(MagickSizeType) layer_info[i].channel_info[j].size) == MagickFalse) { layer_info=DestroyLayerInfo(layer_info,number_layers); ThrowBinaryException(CorruptImageError, "UnexpectedEndOfFile",image->filename); } } continue; } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading data for layer %.20g",(double) i); status=ReadPSDLayer(image,image_info,psd_info,&layer_info[i], exception); if (status == MagickFalse) break; status=SetImageProgress(image,LoadImagesTag,i,(MagickSizeType) number_layers); if (status == MagickFalse) break; } } if (status != MagickFalse) { for (i=0; i < number_layers; i++) { if (layer_info[i].image == (Image *) NULL) { for (j=i; j < number_layers - 1; j++) layer_info[j] = layer_info[j+1]; number_layers--; i--; } } if (number_layers > 0) { for (i=0; i < number_layers; i++) { if (i > 0) layer_info[i].image->previous=layer_info[i-1].image; if (i < (number_layers-1)) layer_info[i].image->next=layer_info[i+1].image; layer_info[i].image->page=layer_info[i].page; } image->next=layer_info[0].image; layer_info[0].image->previous=image; } layer_info=(LayerInfo *) RelinquishMagickMemory(layer_info); } else layer_info=DestroyLayerInfo(layer_info,number_layers); } return(status); } ModuleExport MagickBooleanType ReadPSDLayers(Image *image, const ImageInfo *image_info,const PSDInfo *psd_info, const MagickBooleanType skip_layers,ExceptionInfo *exception) { PolicyDomain domain; PolicyRights rights; domain=CoderPolicyDomain; rights=ReadPolicyRights; if (IsRightsAuthorized(domain,rights,"PSD") == MagickFalse) return(MagickFalse); return(ReadPSDLayersInternal(image,image_info,psd_info,skip_layers, exception)); } static MagickBooleanType ReadPSDMergedImage(const ImageInfo *image_info, Image* image,const PSDInfo* psd_info,ExceptionInfo *exception) { MagickOffsetType *sizes; MagickBooleanType status; PSDCompressionType compression; register ssize_t i; compression=(PSDCompressionType) ReadBlobMSBShort(image); image->compression=ConvertPSDCompression(compression); if (compression != Raw && compression != RLE) { (void) ThrowMagickException(exception,GetMagickModule(), TypeWarning,"CompressionNotSupported","'%.20g'",(double) compression); return(MagickFalse); } sizes=(MagickOffsetType *) NULL; if (compression == RLE) { sizes=ReadPSDRLESizes(image,psd_info,image->rows*psd_info->channels); if (sizes == (MagickOffsetType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=MagickTrue; for (i=0; i < (ssize_t) psd_info->channels; i++) { if (compression == RLE) status=ReadPSDChannelRLE(image,psd_info,i,sizes+(i*image->rows), exception); else status=ReadPSDChannelRaw(image,psd_info->channels,i,exception); if (status != MagickFalse) status=SetImageProgress(image,LoadImagesTag,i,psd_info->channels); if (status == MagickFalse) break; } if ((status != MagickFalse) && (image->colorspace == CMYKColorspace)) status=NegateImage(image,MagickFalse); if (status != MagickFalse) status=CorrectPSDAlphaBlend(image_info,image,exception); sizes=(MagickOffsetType *) RelinquishMagickMemory(sizes); return(status); } static Image *ReadPSDImage(const ImageInfo *image_info,ExceptionInfo *exception) { Image *image; MagickBooleanType has_merged_image, skip_layers; MagickOffsetType offset; MagickSizeType length; MagickBooleanType status; PSDInfo psd_info; register ssize_t i; ssize_t count; unsigned char *data; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read image header. */ image->endian=MSBEndian; count=ReadBlob(image,4,(unsigned char *) psd_info.signature); psd_info.version=ReadBlobMSBShort(image); if ((count == 0) || (LocaleNCompare(psd_info.signature,"8BPS",4) != 0) || ((psd_info.version != 1) && (psd_info.version != 2))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); (void) ReadBlob(image,6,psd_info.reserved); psd_info.channels=ReadBlobMSBShort(image); if (psd_info.channels > MaxPSDChannels) ThrowReaderException(CorruptImageError,"MaximumChannelsExceeded"); psd_info.rows=ReadBlobMSBLong(image); psd_info.columns=ReadBlobMSBLong(image); if ((psd_info.version == 1) && ((psd_info.rows > 30000) || (psd_info.columns > 30000))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.depth=ReadBlobMSBShort(image); if ((psd_info.depth != 1) && (psd_info.depth != 8) && (psd_info.depth != 16)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); psd_info.mode=ReadBlobMSBShort(image); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image is %.20g x %.20g with channels=%.20g, depth=%.20g, mode=%s", (double) psd_info.columns,(double) psd_info.rows,(double) psd_info.channels,(double) psd_info.depth,ModeToString((PSDImageType) psd_info.mode)); /* Initialize image. */ image->depth=psd_info.depth; image->columns=psd_info.columns; image->rows=psd_info.rows; status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if (SetImageBackgroundColor(image) == MagickFalse) { InheritException(exception,&image->exception); image=DestroyImageList(image); return((Image *) NULL); } if (psd_info.mode == LabMode) SetImageColorspace(image,LabColorspace); if (psd_info.mode == CMYKMode) { SetImageColorspace(image,CMYKColorspace); image->matte=psd_info.channels > 4 ? MagickTrue : MagickFalse; } else if ((psd_info.mode == BitmapMode) || (psd_info.mode == GrayscaleMode) || (psd_info.mode == DuotoneMode)) { status=AcquireImageColormap(image,psd_info.depth != 16 ? 256 : 65536); if (status == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Image colormap allocated"); SetImageColorspace(image,GRAYColorspace); image->matte=psd_info.channels > 1 ? MagickTrue : MagickFalse; } else image->matte=psd_info.channels > 3 ? MagickTrue : MagickFalse; /* Read PSD raster colormap only present for indexed and duotone images. */ length=ReadBlobMSBLong(image); if (length != 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading colormap"); if (psd_info.mode == DuotoneMode) { /* Duotone image data; the format of this data is undocumented. */ data=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ReadBlob(image,(size_t) length,data); data=(unsigned char *) RelinquishMagickMemory(data); } else { size_t number_colors; /* Read PSD raster colormap. */ number_colors=length/3; if (number_colors > 65536) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); if (AcquireImageColormap(image,number_colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].red=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].green=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].blue=ScaleCharToQuantum((unsigned char) ReadBlobByte(image)); image->matte=MagickFalse; } } if ((image->depth == 1) && (image->storage_class != PseudoClass)) ThrowReaderException(CorruptImageError, "ImproperImageHeader"); has_merged_image=MagickTrue; length=ReadBlobMSBLong(image); if (length != 0) { unsigned char *blocks; /* Image resources block. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading image resource blocks - %.20g bytes",(double) ((MagickOffsetType) length)); if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); blocks=(unsigned char *) AcquireQuantumMemory((size_t) length, sizeof(*blocks)); if (blocks == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); count=ReadBlob(image,(size_t) length,blocks); if ((count != (ssize_t) length) || (length < 4) || (LocaleNCompare((char *) blocks,"8BIM",4) != 0)) { blocks=(unsigned char *) RelinquishMagickMemory(blocks); ThrowReaderException(CorruptImageError,"ImproperImageHeader"); } ParseImageResourceBlocks(image,blocks,(size_t) length,&has_merged_image); blocks=(unsigned char *) RelinquishMagickMemory(blocks); } /* Layer and mask block. */ length=GetPSDSize(&psd_info,image); if (length == 8) { length=ReadBlobMSBLong(image); length=ReadBlobMSBLong(image); } offset=TellBlob(image); skip_layers=MagickFalse; if ((image_info->number_scenes == 1) && (image_info->scene == 0) && (has_merged_image != MagickFalse)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " read composite only"); skip_layers=MagickTrue; } if (length == 0) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " image has no layers"); } else { if (ReadPSDLayersInternal(image,image_info,&psd_info,skip_layers, exception) != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } /* Skip the rest of the layer and mask information. */ SeekBlob(image,offset+length,SEEK_SET); } /* If we are only "pinging" the image, then we're done - so return. */ if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* Read the precombined layer, present for PSD < 4 compatibility. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " reading the precombined layer"); if (has_merged_image != MagickFalse || GetImageListLength(image) == 1) has_merged_image=(MagickBooleanType) ReadPSDMergedImage(image_info,image, &psd_info,exception); if ((has_merged_image == MagickFalse) && (GetImageListLength(image) == 1) && (length != 0)) { SeekBlob(image,offset,SEEK_SET); status=ReadPSDLayersInternal(image,image_info,&psd_info,MagickFalse, exception); if (status != MagickTrue) { (void) CloseBlob(image); image=DestroyImageList(image); return((Image *) NULL); } } if (has_merged_image == MagickFalse) { Image *merged; if (GetImageListLength(image) == 1) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); SetImageAlphaChannel(image,TransparentAlphaChannel); image->background_color.opacity=TransparentOpacity; merged=MergeImageLayers(image,FlattenLayer,exception); ReplaceImageInList(&image,merged); } (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSDImage() adds properties for the PSD image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSDImage method is: % % size_t RegisterPSDImage(void) % */ ModuleExport size_t RegisterPSDImage(void) { MagickInfo *entry; entry=SetMagickInfo("PSB"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Large Document Format"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PSD"); entry->decoder=(DecodeImageHandler *) ReadPSDImage; entry->encoder=(EncodeImageHandler *) WritePSDImage; entry->magick=(IsImageFormatHandler *) IsPSD; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Adobe Photoshop bitmap"); entry->module=ConstantString("PSD"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSDImage() removes format registrations made by the % PSD module from the list of supported formats. % % The format of the UnregisterPSDImage method is: % % UnregisterPSDImage(void) % */ ModuleExport void UnregisterPSDImage(void) { (void) UnregisterMagickInfo("PSB"); (void) UnregisterMagickInfo("PSD"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S D I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSDImage() writes an image in the Adobe Photoshop encoded image format. % % The format of the WritePSDImage method is: % % MagickBooleanType WritePSDImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % */ static inline ssize_t SetPSDOffset(const PSDInfo *psd_info,Image *image, const size_t offset) { if (psd_info->version == 1) return(WriteBlobMSBShort(image,(unsigned short) offset)); return(WriteBlobMSBLong(image,(unsigned short) offset)); } static inline ssize_t WritePSDOffset(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBShort(image,(unsigned short) size); else result=(WriteBlobMSBLong(image,(unsigned short) size)); SeekBlob(image,current_offset,SEEK_SET); return(result); } static inline ssize_t SetPSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size) { if (psd_info->version == 1) return(WriteBlobMSBLong(image,(unsigned int) size)); return(WriteBlobMSBLongLong(image,size)); } static inline ssize_t WritePSDSize(const PSDInfo *psd_info,Image *image, const MagickSizeType size,const MagickSizeType offset) { MagickSizeType current_offset; ssize_t result; current_offset=TellBlob(image); SeekBlob(image,offset,SEEK_SET); if (psd_info->version == 1) result=WriteBlobMSBLong(image,(unsigned int) size); else result=WriteBlobMSBLongLong(image,size); SeekBlob(image,current_offset,SEEK_SET); return(result); } static size_t PSDPackbitsEncodeImage(Image *image,const size_t length, const unsigned char *pixels,unsigned char *compact_pixels) { int count; register ssize_t i, j; register unsigned char *q; unsigned char *packbits; /* Compress pixels with Packbits encoding. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(pixels != (unsigned char *) NULL); assert(compact_pixels != (unsigned char *) NULL); packbits=(unsigned char *) AcquireQuantumMemory(128UL,sizeof(*packbits)); if (packbits == (unsigned char *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); q=compact_pixels; for (i=(ssize_t) length; i != 0; ) { switch (i) { case 1: { i--; *q++=(unsigned char) 0; *q++=(*pixels); break; } case 2: { i-=2; *q++=(unsigned char) 1; *q++=(*pixels); *q++=pixels[1]; break; } case 3: { i-=3; if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { *q++=(unsigned char) ((256-3)+1); *q++=(*pixels); break; } *q++=(unsigned char) 2; *q++=(*pixels); *q++=pixels[1]; *q++=pixels[2]; break; } default: { if ((*pixels == *(pixels+1)) && (*(pixels+1) == *(pixels+2))) { /* Packed run. */ count=3; while (((ssize_t) count < i) && (*pixels == *(pixels+count))) { count++; if (count >= 127) break; } i-=count; *q++=(unsigned char) ((256-count)+1); *q++=(*pixels); pixels+=count; break; } /* Literal run. */ count=0; while ((*(pixels+count) != *(pixels+count+1)) || (*(pixels+count+1) != *(pixels+count+2))) { packbits[count+1]=pixels[count]; count++; if (((ssize_t) count >= (i-3)) || (count >= 127)) break; } i-=count; *packbits=(unsigned char) (count-1); for (j=0; j <= (ssize_t) count; j++) *q++=packbits[j]; pixels+=count; break; } } } *q++=(unsigned char) 128; /* EOD marker */ packbits=(unsigned char *) RelinquishMagickMemory(packbits); return((size_t) (q-compact_pixels)); } static size_t WriteCompressionStart(const PSDInfo *psd_info,Image *image, const Image *next_image,const ssize_t channels) { size_t length; ssize_t i, y; if (next_image->compression == RLECompression) { length=WriteBlobMSBShort(image,RLE); for (i=0; i < channels; i++) for (y=0; y < (ssize_t) next_image->rows; y++) length+=SetPSDOffset(psd_info,image,0); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) length=WriteBlobMSBShort(image,ZipWithoutPrediction); #endif else length=WriteBlobMSBShort(image,Raw); return(length); } static size_t WritePSDChannel(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, const QuantumType quantum_type, unsigned char *compact_pixels, MagickOffsetType size_offset,const MagickBooleanType separate) { int y; MagickBooleanType monochrome; QuantumInfo *quantum_info; register const PixelPacket *p; register ssize_t i; size_t count, length; unsigned char *pixels; #ifdef MAGICKCORE_ZLIB_DELEGATE #define CHUNK 16384 int flush, level; unsigned char *compressed_pixels; z_stream stream; compressed_pixels=(unsigned char *) NULL; flush=Z_NO_FLUSH; #endif count=0; if (separate != MagickFalse) { size_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,1); } if (next_image->depth > 8) next_image->depth=16; monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; quantum_info=AcquireQuantumInfo(image_info,next_image); if (quantum_info == (QuantumInfo *) NULL) return(0); pixels=GetQuantumPixels(quantum_info); #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { compressed_pixels=(unsigned char *) AcquireQuantumMemory(CHUNK, sizeof(*compressed_pixels)); if (compressed_pixels == (unsigned char *) NULL) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } ResetMagickMemory(&stream,0,sizeof(stream)); stream.data_type=Z_BINARY; level=Z_DEFAULT_COMPRESSION; if ((image_info->quality > 0 && image_info->quality < 10)) level=(int) image_info->quality; if (deflateInit(&stream,level) != Z_OK) { quantum_info=DestroyQuantumInfo(quantum_info); return(0); } } #endif for (y=0; y < (ssize_t) next_image->rows; y++) { p=GetVirtualPixels(next_image,0,y,next_image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; length=ExportQuantumPixels(next_image,(CacheView *) NULL,quantum_info, quantum_type,pixels,&image->exception); if (monochrome != MagickFalse) for (i=0; i < (ssize_t) length; i++) pixels[i]=(~pixels[i]); if (next_image->compression == RLECompression) { length=PSDPackbitsEncodeImage(image,length,pixels,compact_pixels); count+=WriteBlob(image,length,compact_pixels); size_offset+=WritePSDOffset(psd_info,image,length,size_offset); } #ifdef MAGICKCORE_ZLIB_DELEGATE else if (next_image->compression == ZipCompression) { stream.avail_in=(uInt) length; stream.next_in=(Bytef *) pixels; if (y == (ssize_t) next_image->rows-1) flush=Z_FINISH; do { stream.avail_out=(uInt) CHUNK; stream.next_out=(Bytef *) compressed_pixels; if (deflate(&stream,flush) == Z_STREAM_ERROR) break; length=(size_t) CHUNK-stream.avail_out; if (length > 0) count+=WriteBlob(image,length,compressed_pixels); } while (stream.avail_out == 0); } #endif else count+=WriteBlob(image,length,pixels); } #ifdef MAGICKCORE_ZLIB_DELEGATE if (next_image->compression == ZipCompression) { (void) deflateEnd(&stream); compressed_pixels=(unsigned char *) RelinquishMagickMemory( compressed_pixels); } #endif quantum_info=DestroyQuantumInfo(quantum_info); return(count); } static unsigned char *AcquireCompactPixels(Image *image) { size_t packet_size; unsigned char *compact_pixels; packet_size=image->depth > 8UL ? 2UL : 1UL; compact_pixels=(unsigned char *) AcquireQuantumMemory((9* image->columns)+1,packet_size*sizeof(*compact_pixels)); if (compact_pixels == (unsigned char *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); } return(compact_pixels); } static ssize_t WritePSDChannels(const PSDInfo *psd_info, const ImageInfo *image_info,Image *image,Image *next_image, MagickOffsetType size_offset,const MagickBooleanType separate) { Image *mask; MagickOffsetType rows_offset; size_t channels, count, length, offset_length; unsigned char *compact_pixels; count=0; offset_length=0; rows_offset=0; compact_pixels=(unsigned char *) NULL; if (next_image->compression == RLECompression) { compact_pixels=AcquireCompactPixels(next_image); if (compact_pixels == (unsigned char *) NULL) return(0); } channels=1; if (separate == MagickFalse) { if (next_image->storage_class != PseudoClass) { if (IsGrayImage(next_image,&next_image->exception) == MagickFalse) channels=next_image->colorspace == CMYKColorspace ? 4 : 3; if (next_image->matte != MagickFalse) channels++; } rows_offset=TellBlob(image)+2; count+=WriteCompressionStart(psd_info,image,next_image,channels); offset_length=(next_image->rows*(psd_info->version == 1 ? 2 : 4)); } size_offset+=2; if (next_image->storage_class == PseudoClass) { length=WritePSDChannel(psd_info,image_info,image,next_image, IndexQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (IsGrayImage(next_image,&next_image->exception) != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, GrayQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } else { if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); length=WritePSDChannel(psd_info,image_info,image,next_image, RedQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, GreenQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; length=WritePSDChannel(psd_info,image_info,image,next_image, BlueQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; if (next_image->colorspace == CMYKColorspace) { length=WritePSDChannel(psd_info,image_info,image,next_image, BlackQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } if (next_image->matte != MagickFalse) { length=WritePSDChannel(psd_info,image_info,image,next_image, AlphaQuantum,compact_pixels,rows_offset,separate); if (separate != MagickFalse) size_offset+=WritePSDSize(psd_info,image,length,size_offset)+2; else rows_offset+=offset_length; count+=length; } } compact_pixels=(unsigned char *) RelinquishMagickMemory(compact_pixels); if (next_image->colorspace == CMYKColorspace) (void) NegateImage(next_image,MagickFalse); if (separate != MagickFalse) { const char *property; property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); if (mask != (Image *) NULL) { if (mask->compression == RLECompression) { compact_pixels=AcquireCompactPixels(mask); if (compact_pixels == (unsigned char *) NULL) return(0); } length=WritePSDChannel(psd_info,image_info,image,mask, RedQuantum,compact_pixels,rows_offset,MagickTrue); (void) WritePSDSize(psd_info,image,length,size_offset); count+=length; compact_pixels=(unsigned char *) RelinquishMagickMemory( compact_pixels); } } } return(count); } static size_t WritePascalString(Image *image,const char *value,size_t padding) { size_t count, length; register ssize_t i; /* Max length is 255. */ count=0; length=(strlen(value) > 255UL ) ? 255UL : strlen(value); if (length == 0) count+=WriteBlobByte(image,0); else { count+=WriteBlobByte(image,(unsigned char) length); count+=WriteBlob(image,length,(const unsigned char *) value); } length++; if ((length % padding) == 0) return(count); for (i=0; i < (ssize_t) (padding-(length % padding)); i++) count+=WriteBlobByte(image,0); return(count); } static void WriteResolutionResourceBlock(Image *image) { double x_resolution, y_resolution; unsigned short units; if (image->units == PixelsPerCentimeterResolution) { x_resolution=2.54*65536.0*image->x_resolution+0.5; y_resolution=2.54*65536.0*image->y_resolution+0.5; units=2; } else { x_resolution=65536.0*image->x_resolution+0.5; y_resolution=65536.0*image->y_resolution+0.5; units=1; } (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x03ED); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,16); /* resource size */ (void) WriteBlobMSBLong(image,(unsigned int) (x_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* horizontal resolution unit */ (void) WriteBlobMSBShort(image,units); /* width unit */ (void) WriteBlobMSBLong(image,(unsigned int) (y_resolution+0.5)); (void) WriteBlobMSBShort(image,units); /* vertical resolution unit */ (void) WriteBlobMSBShort(image,units); /* height unit */ } static inline size_t WriteChannelSize(const PSDInfo *psd_info,Image *image, const signed short channel) { size_t count; count=WriteBlobMSBSignedShort(image,channel); count+=SetPSDSize(psd_info,image,0); return(count); } static void RemoveICCProfileFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) break; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); if (id == 0x0000040f) { ssize_t quantum; quantum=PSDQuantum(count)+12; if ((quantum >= 12) && (quantum < (ssize_t) length)) { if ((q+quantum < (datum+length-16))) (void) CopyMagickMemory(q,q+quantum,length-quantum-(q-datum)); SetStringInfoLength(bim_profile,length-quantum); } break; } p+=count; if ((count & 0x01) != 0) p++; } } static void RemoveResolutionFromResourceBlock(StringInfo *bim_profile) { register const unsigned char *p; size_t length; unsigned char *datum; unsigned int count, long_sans; unsigned short id, short_sans; length=GetStringInfoLength(bim_profile); if (length < 16) return; datum=GetStringInfoDatum(bim_profile); for (p=datum; (p >= datum) && (p < (datum+length-16)); ) { register unsigned char *q; ssize_t cnt; q=(unsigned char *) p; if (LocaleNCompare((const char *) p,"8BIM",4) != 0) return; p=PushLongPixel(MSBEndian,p,&long_sans); p=PushShortPixel(MSBEndian,p,&id); p=PushShortPixel(MSBEndian,p,&short_sans); p=PushLongPixel(MSBEndian,p,&count); cnt=PSDQuantum(count); if (cnt < 0) return; if ((id == 0x000003ed) && (cnt < (ssize_t) (length-12))) { (void) CopyMagickMemory(q,q+cnt+12,length-(cnt+12)-(q-datum)); SetStringInfoLength(bim_profile,length-(cnt+12)); break; } p+=count; if ((count & 0x01) != 0) p++; } } static const StringInfo *GetAdditionalInformation(const ImageInfo *image_info, Image *image) { #define PSDKeySize 5 #define PSDAllowedLength 36 char key[PSDKeySize]; /* Whitelist of keys from: https://www.adobe.com/devnet-apps/photoshop/fileformatashtml/ */ const char allowed[PSDAllowedLength][PSDKeySize] = { "blnc", "blwh", "brit", "brst", "clbl", "clrL", "curv", "expA", "FMsk", "GdFl", "grdm", "hue ", "hue2", "infx", "knko", "lclr", "levl", "lnsr", "lfx2", "luni", "lrFX", "lspf", "lyid", "lyvr", "mixr", "nvrt", "phfl", "post", "PtFl", "selc", "shpa", "sn2P", "SoCo", "thrs", "tsly", "vibA" }, *option; const StringInfo *info; MagickBooleanType found; register size_t i; size_t remaining_length, length; StringInfo *profile; unsigned char *p; unsigned int size; info=GetImageProfile(image,"psd:additional-info"); if (info == (const StringInfo *) NULL) return((const StringInfo *) NULL); option=GetImageOption(image_info,"psd:additional-info"); if (LocaleCompare(option,"all") == 0) return(info); if (LocaleCompare(option,"selective") != 0) { profile=RemoveImageProfile(image,"psd:additional-info"); return(DestroyStringInfo(profile)); } length=GetStringInfoLength(info); p=GetStringInfoDatum(info); remaining_length=length; length=0; while (remaining_length >= 12) { /* skip over signature */ p+=4; key[0]=(*p++); key[1]=(*p++); key[2]=(*p++); key[3]=(*p++); key[4]='\0'; size=(unsigned int) (*p++) << 24; size|=(unsigned int) (*p++) << 16; size|=(unsigned int) (*p++) << 8; size|=(unsigned int) (*p++); size=size & 0xffffffff; remaining_length-=12; if ((size_t) size > remaining_length) return((const StringInfo *) NULL); found=MagickFalse; for (i=0; i < PSDAllowedLength; i++) { if (LocaleNCompare(key,allowed[i],PSDKeySize) != 0) continue; found=MagickTrue; break; } remaining_length-=(size_t) size; if (found == MagickFalse) { if (remaining_length > 0) p=(unsigned char *) CopyMagickMemory(p-12,p+size,remaining_length); continue; } length+=(size_t) size+12; p+=size; } profile=RemoveImageProfile(image,"psd:additional-info"); if (length == 0) return(DestroyStringInfo(profile)); SetStringInfoLength(profile,(const size_t) length); SetImageProfile(image,"psd:additional-info",info); return(profile); } static MagickBooleanType WritePSDImage(const ImageInfo *image_info, Image *image) { char layer_name[MaxTextExtent]; const char *property; const StringInfo *icc_profile, *info; Image *base_image, *next_image; MagickBooleanType status; MagickOffsetType *layer_size_offsets, size_offset; PSDInfo psd_info; register ssize_t i; size_t layer_count, layer_index, length, name_length, num_channels, packet_size, rounded_size, size; StringInfo *bim_profile; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); packet_size=(size_t) (image->depth > 8 ? 6 : 3); if (image->matte != MagickFalse) packet_size+=image->depth > 8 ? 2 : 1; psd_info.version=1; if ((LocaleCompare(image_info->magick,"PSB") == 0) || (image->columns > 30000) || (image->rows > 30000)) psd_info.version=2; (void) WriteBlob(image,4,(const unsigned char *) "8BPS"); (void) WriteBlobMSBShort(image,psd_info.version); /* version */ for (i=1; i <= 6; i++) (void) WriteBlobByte(image, 0); /* 6 bytes of reserved */ /* When the image has a color profile it won't be converted to gray scale */ if ((GetImageProfile(image,"icc") == (StringInfo *) NULL) && (SetImageGray(image,&image->exception) != MagickFalse)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else if ((image_info->type != TrueColorType) && (image_info->type != TrueColorMatteType) && (image->storage_class == PseudoClass)) num_channels=(image->matte != MagickFalse ? 2UL : 1UL); else { if (image->storage_class == PseudoClass) (void) SetImageStorageClass(image,DirectClass); if (image->colorspace != CMYKColorspace) num_channels=(image->matte != MagickFalse ? 4UL : 3UL); else num_channels=(image->matte != MagickFalse ? 5UL : 4UL); } (void) WriteBlobMSBShort(image,(unsigned short) num_channels); (void) WriteBlobMSBLong(image,(unsigned int) image->rows); (void) WriteBlobMSBLong(image,(unsigned int) image->columns); if (IsGrayImage(image,&image->exception) != MagickFalse) { MagickBooleanType monochrome; /* Write depth & mode. */ monochrome=IsMonochromeImage(image,&image->exception) && (image->depth == 1) ? MagickTrue : MagickFalse; (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? 1 : image->depth > 8 ? 16 : 8)); (void) WriteBlobMSBShort(image,(unsigned short) (monochrome != MagickFalse ? BitmapMode : GrayscaleMode)); } else { (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? 8 : image->depth > 8 ? 16 : 8)); if (((image_info->colorspace != UndefinedColorspace) || (image->colorspace != CMYKColorspace)) && (image_info->colorspace != CMYKColorspace)) { (void) TransformImageColorspace(image,sRGBColorspace); (void) WriteBlobMSBShort(image,(unsigned short) (image->storage_class == PseudoClass ? IndexedMode : RGBMode)); } else { if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,CMYKColorspace); (void) WriteBlobMSBShort(image,CMYKMode); } } if ((IsGrayImage(image,&image->exception) != MagickFalse) || (image->storage_class == DirectClass) || (image->colors > 256)) (void) WriteBlobMSBLong(image,0); else { /* Write PSD raster colormap. */ (void) WriteBlobMSBLong(image,768); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].red)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar( image->colormap[i].green)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); for (i=0; i < (ssize_t) image->colors; i++) (void) WriteBlobByte(image,ScaleQuantumToChar(image->colormap[i].blue)); for ( ; i < 256; i++) (void) WriteBlobByte(image,0); } /* Image resource block. */ length=28; /* 0x03EB */ bim_profile=(StringInfo *) GetImageProfile(image,"8bim"); icc_profile=GetImageProfile(image,"icc"); if (bim_profile != (StringInfo *) NULL) { bim_profile=CloneStringInfo(bim_profile); if (icc_profile != (StringInfo *) NULL) RemoveICCProfileFromResourceBlock(bim_profile); RemoveResolutionFromResourceBlock(bim_profile); length+=PSDQuantum(GetStringInfoLength(bim_profile)); } if (icc_profile != (const StringInfo *) NULL) length+=PSDQuantum(GetStringInfoLength(icc_profile))+12; (void) WriteBlobMSBLong(image,(unsigned int) length); WriteResolutionResourceBlock(image); if (bim_profile != (StringInfo *) NULL) { (void) WriteBlob(image,GetStringInfoLength(bim_profile), GetStringInfoDatum(bim_profile)); bim_profile=DestroyStringInfo(bim_profile); } if (icc_profile != (StringInfo *) NULL) { (void) WriteBlob(image,4,(const unsigned char *) "8BIM"); (void) WriteBlobMSBShort(image,0x0000040F); (void) WriteBlobMSBShort(image,0); (void) WriteBlobMSBLong(image,(unsigned int) GetStringInfoLength( icc_profile)); (void) WriteBlob(image,GetStringInfoLength(icc_profile), GetStringInfoDatum(icc_profile)); if ((MagickOffsetType) GetStringInfoLength(icc_profile) != PSDQuantum(GetStringInfoLength(icc_profile))) (void) WriteBlobByte(image,0); } base_image=GetNextImageInList(image); if (base_image == (Image *)NULL) base_image=image; size=0; size_offset=TellBlob(image); SetPSDSize(&psd_info,image,0); SetPSDSize(&psd_info,image,0); layer_count=0; for (next_image=base_image; next_image != NULL; ) { layer_count++; next_image=GetNextImageInList(next_image); } if (image->matte != MagickFalse) size+=WriteBlobMSBShort(image,-(unsigned short) layer_count); else size+=WriteBlobMSBShort(image,(unsigned short) layer_count); layer_size_offsets=(MagickOffsetType *) AcquireQuantumMemory( (size_t) layer_count,sizeof(MagickOffsetType)); if (layer_size_offsets == (MagickOffsetType *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); layer_index=0; for (next_image=base_image; next_image != NULL; ) { Image *mask; unsigned char default_color; unsigned short channels, total_channels; mask=(Image *) NULL; property=GetImageArtifact(next_image,"psd:opacity-mask"); default_color=0; if (property != (const char *) NULL) { mask=(Image *) GetImageRegistry(ImageRegistryType,property, &image->exception); default_color=strlen(property) == 9 ? 255 : 0; } size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.y); size+=WriteBlobMSBLong(image,(unsigned int) next_image->page.x); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.y+ next_image->rows)); size+=WriteBlobMSBLong(image,(unsigned int) (next_image->page.x+ next_image->columns)); channels=1U; if ((next_image->storage_class != PseudoClass) && (IsGrayImage(next_image,&next_image->exception) == MagickFalse)) channels=next_image->colorspace == CMYKColorspace ? 4U : 3U; total_channels=channels; if (next_image->matte != MagickFalse) total_channels++; if (mask != (Image *) NULL) total_channels++; size+=WriteBlobMSBShort(image,total_channels); layer_size_offsets[layer_index++]=TellBlob(image); for (i=0; i < (ssize_t) channels; i++) size+=WriteChannelSize(&psd_info,image,(signed short) i); if (next_image->matte != MagickFalse) size+=WriteChannelSize(&psd_info,image,-1); if (mask != (Image *) NULL) size+=WriteChannelSize(&psd_info,image,-2); size+=WriteBlob(image,4,(const unsigned char *) "8BIM"); size+=WriteBlob(image,4,(const unsigned char *) CompositeOperatorToPSDBlendMode(next_image->compose)); property=GetImageArtifact(next_image,"psd:layer.opacity"); if (property != (const char *) NULL) { Quantum opacity; opacity=(Quantum) StringToInteger(property); size+=WriteBlobByte(image,ScaleQuantumToChar(opacity)); (void) ApplyPSDLayerOpacity(next_image,opacity,MagickTrue, &image->exception); } else size+=WriteBlobByte(image,255); size+=WriteBlobByte(image,0); size+=WriteBlobByte(image,next_image->compose==NoCompositeOp ? 1 << 0x02 : 1); /* layer properties - visible, etc. */ size+=WriteBlobByte(image,0); info=GetAdditionalInformation(image_info,next_image); property=(const char *) GetImageProperty(next_image,"label"); if (property == (const char *) NULL) { (void) FormatLocaleString(layer_name,MaxTextExtent,"L%.20g", (double) layer_index); property=layer_name; } name_length=strlen(property)+1; if ((name_length % 4) != 0) name_length+=(4-(name_length % 4)); if (info != (const StringInfo *) NULL) name_length+=GetStringInfoLength(info); name_length+=8; if (mask != (Image *) NULL) name_length+=20; size+=WriteBlobMSBLong(image,(unsigned int) name_length); if (mask == (Image *) NULL) size+=WriteBlobMSBLong(image,0); else { if (mask->compose != NoCompositeOp) (void) ApplyPSDOpacityMask(next_image,mask,ScaleCharToQuantum( default_color),MagickTrue,&image->exception); mask->page.y+=image->page.y; mask->page.x+=image->page.x; size+=WriteBlobMSBLong(image,20); size+=WriteBlobMSBSignedLong(image,mask->page.y); size+=WriteBlobMSBSignedLong(image,mask->page.x); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->rows+ mask->page.y); size+=WriteBlobMSBSignedLong(image,(const signed int) mask->columns+ mask->page.x); size+=WriteBlobByte(image,default_color); size+=WriteBlobByte(image,mask->compose == NoCompositeOp ? 2 : 0); size+=WriteBlobMSBShort(image,0); } size+=WriteBlobMSBLong(image,0); size+=WritePascalString(image,property,4); if (info != (const StringInfo *) NULL) size+=WriteBlob(image,GetStringInfoLength(info), GetStringInfoDatum(info)); next_image=GetNextImageInList(next_image); } /* Now the image data! */ next_image=base_image; layer_index=0; while (next_image != NULL) { length=WritePSDChannels(&psd_info,image_info,image,next_image, layer_size_offsets[layer_index++],MagickTrue); if (length == 0) { status=MagickFalse; break; } size+=length; next_image=GetNextImageInList(next_image); } (void) WriteBlobMSBLong(image,0); /* user mask data */ /* Remove the opacity mask from the registry */ next_image=base_image; while (next_image != (Image *) NULL) { property=GetImageArtifact(next_image,"psd:opacity-mask"); if (property != (const char *) NULL) DeleteImageRegistry(property); next_image=GetNextImageInList(next_image); } /* Write the total size */ size_offset+=WritePSDSize(&psd_info,image,size+ (psd_info.version == 1 ? 8 : 16),size_offset); if ((size/2) != ((size+1)/2)) rounded_size=size+1; else rounded_size=size; (void) WritePSDSize(&psd_info,image,rounded_size,size_offset); layer_size_offsets=(MagickOffsetType *) RelinquishMagickMemory( layer_size_offsets); /* Write composite image. */ if (status != MagickFalse) { CompressionType compression; compression=image->compression; if (image->compression == ZipCompression) image->compression=RLECompression; if (WritePSDChannels(&psd_info,image_info,image,image,0, MagickFalse) == 0) status=MagickFalse; image->compression=compression; } (void) CloseBlob(image); return(status); }
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2784_0
crossvul-cpp_data_bad_2763_0
/* * RL2 Format Demuxer * Copyright (c) 2008 Sascha Sommer (saschasommer@freenet.de) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * RL2 file demuxer * @file * @author Sascha Sommer (saschasommer@freenet.de) * @see http://wiki.multimedia.cx/index.php?title=RL2 * * extradata: * 2 byte le initial drawing offset within 320x200 viewport * 4 byte le number of used colors * 256 * 3 bytes rgb palette * optional background_frame */ #include <stdint.h> #include "libavutil/intreadwrite.h" #include "libavutil/mathematics.h" #include "avformat.h" #include "internal.h" #define EXTRADATA1_SIZE (6 + 256 * 3) ///< video base, clr, palette #define FORM_TAG MKBETAG('F', 'O', 'R', 'M') #define RLV2_TAG MKBETAG('R', 'L', 'V', '2') #define RLV3_TAG MKBETAG('R', 'L', 'V', '3') typedef struct Rl2DemuxContext { unsigned int index_pos[2]; ///< indexes in the sample tables } Rl2DemuxContext; /** * check if the file is in rl2 format * @param p probe buffer * @return 0 when the probe buffer does not contain rl2 data, > 0 otherwise */ static int rl2_probe(AVProbeData *p) { if(AV_RB32(&p->buf[0]) != FORM_TAG) return 0; if(AV_RB32(&p->buf[8]) != RLV2_TAG && AV_RB32(&p->buf[8]) != RLV3_TAG) return 0; return AVPROBE_SCORE_MAX; } /** * read rl2 header data and setup the avstreams * @param s demuxer context * @return 0 on success, AVERROR otherwise */ static av_cold int rl2_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVStream *st; unsigned int frame_count; unsigned int audio_frame_counter = 0; unsigned int video_frame_counter = 0; unsigned int back_size; unsigned short sound_rate; unsigned short rate; unsigned short channels; unsigned short def_sound_size; unsigned int signature; unsigned int pts_den = 11025; /* video only case */ unsigned int pts_num = 1103; unsigned int* chunk_offset = NULL; int* chunk_size = NULL; int* audio_size = NULL; int i; int ret = 0; avio_skip(pb,4); /* skip FORM tag */ back_size = avio_rl32(pb); /**< get size of the background frame */ signature = avio_rb32(pb); avio_skip(pb, 4); /* data size */ frame_count = avio_rl32(pb); /* disallow back_sizes and frame_counts that may lead to overflows later */ if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t)) return AVERROR_INVALIDDATA; avio_skip(pb, 2); /* encoding method */ sound_rate = avio_rl16(pb); rate = avio_rl16(pb); channels = avio_rl16(pb); def_sound_size = avio_rl16(pb); /** setup video stream */ st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RL2; st->codecpar->codec_tag = 0; /* no fourcc */ st->codecpar->width = 320; st->codecpar->height = 200; /** allocate and fill extradata */ st->codecpar->extradata_size = EXTRADATA1_SIZE; if(signature == RLV3_TAG && back_size > 0) st->codecpar->extradata_size += back_size; if(ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); /** setup audio stream if present */ if(sound_rate){ if (!channels || channels > 42) { av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels); return AVERROR_INVALIDDATA; } pts_num = def_sound_size; pts_den = rate; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_PCM_U8; st->codecpar->codec_tag = 1; st->codecpar->channels = channels; st->codecpar->bits_per_coded_sample = 8; st->codecpar->sample_rate = rate; st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample; st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8; avpriv_set_pts_info(st,32,1,rate); } avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den); chunk_size = av_malloc(frame_count * sizeof(uint32_t)); audio_size = av_malloc(frame_count * sizeof(uint32_t)); chunk_offset = av_malloc(frame_count * sizeof(uint32_t)); if(!chunk_size || !audio_size || !chunk_offset){ av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return AVERROR(ENOMEM); } /** read offset and size tables */ for(i=0; i < frame_count;i++) chunk_size[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) chunk_offset[i] = avio_rl32(pb); for(i=0; i < frame_count;i++) audio_size[i] = avio_rl32(pb) & 0xFFFF; /** build the sample index */ for(i=0;i<frame_count;i++){ if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){ ret = AVERROR_INVALIDDATA; break; } if(sound_rate && audio_size[i]){ av_add_index_entry(s->streams[1], chunk_offset[i], audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME); audio_frame_counter += audio_size[i] / channels; } av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i], video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME); ++video_frame_counter; } av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return ret; } /** * read a single audio or video packet * @param s demuxer context * @param pkt the packet to be filled * @return 0 on success, AVERROR otherwise */ static int rl2_read_packet(AVFormatContext *s, AVPacket *pkt) { Rl2DemuxContext *rl2 = s->priv_data; AVIOContext *pb = s->pb; AVIndexEntry *sample = NULL; int i; int ret = 0; int stream_id = -1; int64_t pos = INT64_MAX; /** check if there is a valid video or audio entry that can be used */ for(i=0; i<s->nb_streams; i++){ if(rl2->index_pos[i] < s->streams[i]->nb_index_entries && s->streams[i]->index_entries[ rl2->index_pos[i] ].pos < pos){ sample = &s->streams[i]->index_entries[ rl2->index_pos[i] ]; pos= sample->pos; stream_id= i; } } if(stream_id == -1) return AVERROR_EOF; ++rl2->index_pos[stream_id]; /** position the stream (will probably be there anyway) */ avio_seek(pb, sample->pos, SEEK_SET); /** fill the packet */ ret = av_get_packet(pb, pkt, sample->size); if(ret != sample->size){ av_packet_unref(pkt); return AVERROR(EIO); } pkt->stream_index = stream_id; pkt->pts = sample->timestamp; return ret; } /** * seek to a new timestamp * @param s demuxer context * @param stream_index index of the stream that should be seeked * @param timestamp wanted timestamp * @param flags direction and seeking mode * @return 0 on success, -1 otherwise */ static int rl2_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { AVStream *st = s->streams[stream_index]; Rl2DemuxContext *rl2 = s->priv_data; int i; int index = av_index_search_timestamp(st, timestamp, flags); if(index < 0) return -1; rl2->index_pos[stream_index] = index; timestamp = st->index_entries[index].timestamp; for(i=0; i < s->nb_streams; i++){ AVStream *st2 = s->streams[i]; index = av_index_search_timestamp(st2, av_rescale_q(timestamp, st->time_base, st2->time_base), flags | AVSEEK_FLAG_BACKWARD); if(index < 0) index = 0; rl2->index_pos[i] = index; } return 0; } AVInputFormat ff_rl2_demuxer = { .name = "rl2", .long_name = NULL_IF_CONFIG_SMALL("RL2"), .priv_data_size = sizeof(Rl2DemuxContext), .read_probe = rl2_probe, .read_header = rl2_read_header, .read_packet = rl2_read_packet, .read_seek = rl2_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2763_0
crossvul-cpp_data_good_2763_0
/* * RL2 Format Demuxer * Copyright (c) 2008 Sascha Sommer (saschasommer@freenet.de) * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * RL2 file demuxer * @file * @author Sascha Sommer (saschasommer@freenet.de) * @see http://wiki.multimedia.cx/index.php?title=RL2 * * extradata: * 2 byte le initial drawing offset within 320x200 viewport * 4 byte le number of used colors * 256 * 3 bytes rgb palette * optional background_frame */ #include <stdint.h> #include "libavutil/intreadwrite.h" #include "libavutil/mathematics.h" #include "avformat.h" #include "internal.h" #define EXTRADATA1_SIZE (6 + 256 * 3) ///< video base, clr, palette #define FORM_TAG MKBETAG('F', 'O', 'R', 'M') #define RLV2_TAG MKBETAG('R', 'L', 'V', '2') #define RLV3_TAG MKBETAG('R', 'L', 'V', '3') typedef struct Rl2DemuxContext { unsigned int index_pos[2]; ///< indexes in the sample tables } Rl2DemuxContext; /** * check if the file is in rl2 format * @param p probe buffer * @return 0 when the probe buffer does not contain rl2 data, > 0 otherwise */ static int rl2_probe(AVProbeData *p) { if(AV_RB32(&p->buf[0]) != FORM_TAG) return 0; if(AV_RB32(&p->buf[8]) != RLV2_TAG && AV_RB32(&p->buf[8]) != RLV3_TAG) return 0; return AVPROBE_SCORE_MAX; } /** * read rl2 header data and setup the avstreams * @param s demuxer context * @return 0 on success, AVERROR otherwise */ static av_cold int rl2_read_header(AVFormatContext *s) { AVIOContext *pb = s->pb; AVStream *st; unsigned int frame_count; unsigned int audio_frame_counter = 0; unsigned int video_frame_counter = 0; unsigned int back_size; unsigned short sound_rate; unsigned short rate; unsigned short channels; unsigned short def_sound_size; unsigned int signature; unsigned int pts_den = 11025; /* video only case */ unsigned int pts_num = 1103; unsigned int* chunk_offset = NULL; int* chunk_size = NULL; int* audio_size = NULL; int i; int ret = 0; avio_skip(pb,4); /* skip FORM tag */ back_size = avio_rl32(pb); /**< get size of the background frame */ signature = avio_rb32(pb); avio_skip(pb, 4); /* data size */ frame_count = avio_rl32(pb); /* disallow back_sizes and frame_counts that may lead to overflows later */ if(back_size > INT_MAX/2 || frame_count > INT_MAX / sizeof(uint32_t)) return AVERROR_INVALIDDATA; avio_skip(pb, 2); /* encoding method */ sound_rate = avio_rl16(pb); rate = avio_rl16(pb); channels = avio_rl16(pb); def_sound_size = avio_rl16(pb); /** setup video stream */ st = avformat_new_stream(s, NULL); if(!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RL2; st->codecpar->codec_tag = 0; /* no fourcc */ st->codecpar->width = 320; st->codecpar->height = 200; /** allocate and fill extradata */ st->codecpar->extradata_size = EXTRADATA1_SIZE; if(signature == RLV3_TAG && back_size > 0) st->codecpar->extradata_size += back_size; if(ff_get_extradata(s, st->codecpar, pb, st->codecpar->extradata_size) < 0) return AVERROR(ENOMEM); /** setup audio stream if present */ if(sound_rate){ if (!channels || channels > 42) { av_log(s, AV_LOG_ERROR, "Invalid number of channels: %d\n", channels); return AVERROR_INVALIDDATA; } pts_num = def_sound_size; pts_den = rate; st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; st->codecpar->codec_id = AV_CODEC_ID_PCM_U8; st->codecpar->codec_tag = 1; st->codecpar->channels = channels; st->codecpar->bits_per_coded_sample = 8; st->codecpar->sample_rate = rate; st->codecpar->bit_rate = st->codecpar->channels * st->codecpar->sample_rate * st->codecpar->bits_per_coded_sample; st->codecpar->block_align = st->codecpar->channels * st->codecpar->bits_per_coded_sample / 8; avpriv_set_pts_info(st,32,1,rate); } avpriv_set_pts_info(s->streams[0], 32, pts_num, pts_den); chunk_size = av_malloc(frame_count * sizeof(uint32_t)); audio_size = av_malloc(frame_count * sizeof(uint32_t)); chunk_offset = av_malloc(frame_count * sizeof(uint32_t)); if(!chunk_size || !audio_size || !chunk_offset){ av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return AVERROR(ENOMEM); } /** read offset and size tables */ for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; chunk_size[i] = avio_rl32(pb); } for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; chunk_offset[i] = avio_rl32(pb); } for(i=0; i < frame_count;i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; audio_size[i] = avio_rl32(pb) & 0xFFFF; } /** build the sample index */ for(i=0;i<frame_count;i++){ if(chunk_size[i] < 0 || audio_size[i] > chunk_size[i]){ ret = AVERROR_INVALIDDATA; break; } if(sound_rate && audio_size[i]){ av_add_index_entry(s->streams[1], chunk_offset[i], audio_frame_counter,audio_size[i], 0, AVINDEX_KEYFRAME); audio_frame_counter += audio_size[i] / channels; } av_add_index_entry(s->streams[0], chunk_offset[i] + audio_size[i], video_frame_counter,chunk_size[i]-audio_size[i],0,AVINDEX_KEYFRAME); ++video_frame_counter; } av_free(chunk_size); av_free(audio_size); av_free(chunk_offset); return ret; } /** * read a single audio or video packet * @param s demuxer context * @param pkt the packet to be filled * @return 0 on success, AVERROR otherwise */ static int rl2_read_packet(AVFormatContext *s, AVPacket *pkt) { Rl2DemuxContext *rl2 = s->priv_data; AVIOContext *pb = s->pb; AVIndexEntry *sample = NULL; int i; int ret = 0; int stream_id = -1; int64_t pos = INT64_MAX; /** check if there is a valid video or audio entry that can be used */ for(i=0; i<s->nb_streams; i++){ if(rl2->index_pos[i] < s->streams[i]->nb_index_entries && s->streams[i]->index_entries[ rl2->index_pos[i] ].pos < pos){ sample = &s->streams[i]->index_entries[ rl2->index_pos[i] ]; pos= sample->pos; stream_id= i; } } if(stream_id == -1) return AVERROR_EOF; ++rl2->index_pos[stream_id]; /** position the stream (will probably be there anyway) */ avio_seek(pb, sample->pos, SEEK_SET); /** fill the packet */ ret = av_get_packet(pb, pkt, sample->size); if(ret != sample->size){ av_packet_unref(pkt); return AVERROR(EIO); } pkt->stream_index = stream_id; pkt->pts = sample->timestamp; return ret; } /** * seek to a new timestamp * @param s demuxer context * @param stream_index index of the stream that should be seeked * @param timestamp wanted timestamp * @param flags direction and seeking mode * @return 0 on success, -1 otherwise */ static int rl2_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags) { AVStream *st = s->streams[stream_index]; Rl2DemuxContext *rl2 = s->priv_data; int i; int index = av_index_search_timestamp(st, timestamp, flags); if(index < 0) return -1; rl2->index_pos[stream_index] = index; timestamp = st->index_entries[index].timestamp; for(i=0; i < s->nb_streams; i++){ AVStream *st2 = s->streams[i]; index = av_index_search_timestamp(st2, av_rescale_q(timestamp, st->time_base, st2->time_base), flags | AVSEEK_FLAG_BACKWARD); if(index < 0) index = 0; rl2->index_pos[i] = index; } return 0; } AVInputFormat ff_rl2_demuxer = { .name = "rl2", .long_name = NULL_IF_CONFIG_SMALL("RL2"), .priv_data_size = sizeof(Rl2DemuxContext), .read_probe = rl2_probe, .read_header = rl2_read_header, .read_packet = rl2_read_packet, .read_seek = rl2_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2763_0
crossvul-cpp_data_bad_2762_0
/* * Silicon Graphics Movie demuxer * Copyright (c) 2012 Peter Ross * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Silicon Graphics Movie demuxer */ #include "libavutil/channel_layout.h" #include "libavutil/eval.h" #include "libavutil/intreadwrite.h" #include "libavutil/rational.h" #include "avformat.h" #include "internal.h" typedef struct MvContext { int nb_video_tracks; int nb_audio_tracks; int eof_count; ///< number of streams that have finished int stream_index; ///< current stream index int frame[2]; ///< frame nb for current stream int acompression; ///< compression level for audio stream int aformat; ///< audio format } MvContext; #define AUDIO_FORMAT_SIGNED 401 static int mv_probe(AVProbeData *p) { if (AV_RB32(p->buf) == MKBETAG('M', 'O', 'V', 'I') && AV_RB16(p->buf + 4) < 3) return AVPROBE_SCORE_MAX; return 0; } static char *var_read_string(AVIOContext *pb, int size) { int n; char *str; if (size < 0 || size == INT_MAX) return NULL; str = av_malloc(size + 1); if (!str) return NULL; n = avio_get_str(pb, size, str, size + 1); if (n < size) avio_skip(pb, size - n); return str; } static int var_read_int(AVIOContext *pb, int size) { int v; char *s = var_read_string(pb, size); if (!s) return 0; v = strtol(s, NULL, 10); av_free(s); return v; } static AVRational var_read_float(AVIOContext *pb, int size) { AVRational v; char *s = var_read_string(pb, size); if (!s) return (AVRational) { 0, 0 }; v = av_d2q(av_strtod(s, NULL), INT_MAX); av_free(s); return v; } static void var_read_metadata(AVFormatContext *avctx, const char *tag, int size) { char *value = var_read_string(avctx->pb, size); if (value) av_dict_set(&avctx->metadata, tag, value, AV_DICT_DONT_STRDUP_VAL); } static int set_channels(AVFormatContext *avctx, AVStream *st, int channels) { if (channels <= 0) { av_log(avctx, AV_LOG_ERROR, "Channel count %d invalid.\n", channels); return AVERROR_INVALIDDATA; } st->codecpar->channels = channels; st->codecpar->channel_layout = (st->codecpar->channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO; return 0; } /** * Parse global variable * @return < 0 if unknown */ static int parse_global_var(AVFormatContext *avctx, AVStream *st, const char *name, int size) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; if (!strcmp(name, "__NUM_I_TRACKS")) { mv->nb_video_tracks = var_read_int(pb, size); } else if (!strcmp(name, "__NUM_A_TRACKS")) { mv->nb_audio_tracks = var_read_int(pb, size); } else if (!strcmp(name, "COMMENT") || !strcmp(name, "TITLE")) { var_read_metadata(avctx, name, size); } else if (!strcmp(name, "LOOP_MODE") || !strcmp(name, "NUM_LOOPS") || !strcmp(name, "OPTIMIZED")) { avio_skip(pb, size); // ignore } else return AVERROR_INVALIDDATA; return 0; } /** * Parse audio variable * @return < 0 if unknown */ static int parse_audio_var(AVFormatContext *avctx, AVStream *st, const char *name, int size) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; if (!strcmp(name, "__DIR_COUNT")) { st->nb_frames = var_read_int(pb, size); } else if (!strcmp(name, "AUDIO_FORMAT")) { mv->aformat = var_read_int(pb, size); } else if (!strcmp(name, "COMPRESSION")) { mv->acompression = var_read_int(pb, size); } else if (!strcmp(name, "DEFAULT_VOL")) { var_read_metadata(avctx, name, size); } else if (!strcmp(name, "NUM_CHANNELS")) { return set_channels(avctx, st, var_read_int(pb, size)); } else if (!strcmp(name, "SAMPLE_RATE")) { st->codecpar->sample_rate = var_read_int(pb, size); avpriv_set_pts_info(st, 33, 1, st->codecpar->sample_rate); } else if (!strcmp(name, "SAMPLE_WIDTH")) { st->codecpar->bits_per_coded_sample = var_read_int(pb, size) * 8; } else return AVERROR_INVALIDDATA; return 0; } /** * Parse video variable * @return < 0 if unknown */ static int parse_video_var(AVFormatContext *avctx, AVStream *st, const char *name, int size) { AVIOContext *pb = avctx->pb; if (!strcmp(name, "__DIR_COUNT")) { st->nb_frames = st->duration = var_read_int(pb, size); } else if (!strcmp(name, "COMPRESSION")) { char *str = var_read_string(pb, size); if (!str) return AVERROR_INVALIDDATA; if (!strcmp(str, "1")) { st->codecpar->codec_id = AV_CODEC_ID_MVC1; } else if (!strcmp(str, "2")) { st->codecpar->format = AV_PIX_FMT_ABGR; st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; } else if (!strcmp(str, "3")) { st->codecpar->codec_id = AV_CODEC_ID_SGIRLE; } else if (!strcmp(str, "10")) { st->codecpar->codec_id = AV_CODEC_ID_MJPEG; } else if (!strcmp(str, "MVC2")) { st->codecpar->codec_id = AV_CODEC_ID_MVC2; } else { avpriv_request_sample(avctx, "Video compression %s", str); } av_free(str); } else if (!strcmp(name, "FPS")) { AVRational fps = var_read_float(pb, size); avpriv_set_pts_info(st, 64, fps.den, fps.num); st->avg_frame_rate = fps; } else if (!strcmp(name, "HEIGHT")) { st->codecpar->height = var_read_int(pb, size); } else if (!strcmp(name, "PIXEL_ASPECT")) { st->sample_aspect_ratio = var_read_float(pb, size); av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, INT_MAX); } else if (!strcmp(name, "WIDTH")) { st->codecpar->width = var_read_int(pb, size); } else if (!strcmp(name, "ORIENTATION")) { if (var_read_int(pb, size) == 1101) { st->codecpar->extradata = av_strdup("BottomUp"); st->codecpar->extradata_size = 9; } } else if (!strcmp(name, "Q_SPATIAL") || !strcmp(name, "Q_TEMPORAL")) { var_read_metadata(avctx, name, size); } else if (!strcmp(name, "INTERLACING") || !strcmp(name, "PACKING")) { avio_skip(pb, size); // ignore } else return AVERROR_INVALIDDATA; return 0; } static int read_table(AVFormatContext *avctx, AVStream *st, int (*parse)(AVFormatContext *avctx, AVStream *st, const char *name, int size)) { int count, i; AVIOContext *pb = avctx->pb; avio_skip(pb, 4); count = avio_rb32(pb); avio_skip(pb, 4); for (i = 0; i < count; i++) { char name[17]; int size; avio_read(pb, name, 16); name[sizeof(name) - 1] = 0; size = avio_rb32(pb); if (size < 0) { av_log(avctx, AV_LOG_ERROR, "entry size %d is invalid\n", size); return AVERROR_INVALIDDATA; } if (parse(avctx, st, name, size) < 0) { avpriv_request_sample(avctx, "Variable %s", name); avio_skip(pb, size); } } return 0; } static void read_index(AVIOContext *pb, AVStream *st) { uint64_t timestamp = 0; int i; for (i = 0; i < st->nb_frames; i++) { uint32_t pos = avio_rb32(pb); uint32_t size = avio_rb32(pb); avio_skip(pb, 8); av_add_index_entry(st, pos, timestamp, size, 0, AVINDEX_KEYFRAME); if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { timestamp += size / (st->codecpar->channels * 2); } else { timestamp++; } } } static int mv_read_header(AVFormatContext *avctx) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; AVStream *ast = NULL, *vst = NULL; //initialization to suppress warning int version, i; int ret; avio_skip(pb, 4); version = avio_rb16(pb); if (version == 2) { uint64_t timestamp; int v; avio_skip(pb, 22); /* allocate audio track first to prevent unnecessary seeking * (audio packet always precede video packet for a given frame) */ ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); avpriv_set_pts_info(vst, 64, 1, 15); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; vst->avg_frame_rate = av_inv_q(vst->time_base); vst->nb_frames = avio_rb32(pb); v = avio_rb32(pb); switch (v) { case 1: vst->codecpar->codec_id = AV_CODEC_ID_MVC1; break; case 2: vst->codecpar->format = AV_PIX_FMT_ARGB; vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; break; default: avpriv_request_sample(avctx, "Video compression %i", v); break; } vst->codecpar->codec_tag = 0; vst->codecpar->width = avio_rb32(pb); vst->codecpar->height = avio_rb32(pb); avio_skip(pb, 12); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; ast->nb_frames = vst->nb_frames; ast->codecpar->sample_rate = avio_rb32(pb); if (ast->codecpar->sample_rate <= 0) { av_log(avctx, AV_LOG_ERROR, "Invalid sample rate %d\n", ast->codecpar->sample_rate); return AVERROR_INVALIDDATA; } avpriv_set_pts_info(ast, 33, 1, ast->codecpar->sample_rate); if (set_channels(avctx, ast, avio_rb32(pb)) < 0) return AVERROR_INVALIDDATA; v = avio_rb32(pb); if (v == AUDIO_FORMAT_SIGNED) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression (format %i)", v); } avio_skip(pb, 12); var_read_metadata(avctx, "title", 0x80); var_read_metadata(avctx, "comment", 0x100); avio_skip(pb, 0x80); timestamp = 0; for (i = 0; i < vst->nb_frames; i++) { uint32_t pos = avio_rb32(pb); uint32_t asize = avio_rb32(pb); uint32_t vsize = avio_rb32(pb); avio_skip(pb, 8); av_add_index_entry(ast, pos, timestamp, asize, 0, AVINDEX_KEYFRAME); av_add_index_entry(vst, pos + asize, i, vsize, 0, AVINDEX_KEYFRAME); timestamp += asize / (ast->codecpar->channels * 2); } } else if (!version && avio_rb16(pb) == 3) { avio_skip(pb, 4); if ((ret = read_table(avctx, NULL, parse_global_var)) < 0) return ret; if (mv->nb_audio_tracks > 1) { avpriv_request_sample(avctx, "Multiple audio streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_audio_tracks) { ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; if ((read_table(avctx, ast, parse_audio_var)) < 0) return ret; if (mv->acompression == 100 && mv->aformat == AUDIO_FORMAT_SIGNED && ast->codecpar->bits_per_coded_sample == 16) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression %i (format %i, sr %i)", mv->acompression, mv->aformat, ast->codecpar->bits_per_coded_sample); ast->codecpar->codec_id = AV_CODEC_ID_NONE; } if (ast->codecpar->channels <= 0) { av_log(avctx, AV_LOG_ERROR, "No valid channel count found.\n"); return AVERROR_INVALIDDATA; } } if (mv->nb_video_tracks > 1) { avpriv_request_sample(avctx, "Multiple video streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_video_tracks) { vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; if ((ret = read_table(avctx, vst, parse_video_var))<0) return ret; } if (mv->nb_audio_tracks) read_index(pb, ast); if (mv->nb_video_tracks) read_index(pb, vst); } else { avpriv_request_sample(avctx, "Version %i", version); return AVERROR_PATCHWELCOME; } return 0; } static int mv_read_packet(AVFormatContext *avctx, AVPacket *pkt) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; AVStream *st = avctx->streams[mv->stream_index]; const AVIndexEntry *index; int frame = mv->frame[mv->stream_index]; int64_t ret; uint64_t pos; if (frame < st->nb_index_entries) { index = &st->index_entries[frame]; pos = avio_tell(pb); if (index->pos > pos) avio_skip(pb, index->pos - pos); else if (index->pos < pos) { if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) return AVERROR(EIO); ret = avio_seek(pb, index->pos, SEEK_SET); if (ret < 0) return ret; } ret = av_get_packet(pb, pkt, index->size); if (ret < 0) return ret; pkt->stream_index = mv->stream_index; pkt->pts = index->timestamp; pkt->flags |= AV_PKT_FLAG_KEY; mv->frame[mv->stream_index]++; mv->eof_count = 0; } else { mv->eof_count++; if (mv->eof_count >= avctx->nb_streams) return AVERROR_EOF; // avoid returning 0 without a packet return AVERROR(EAGAIN); } mv->stream_index++; if (mv->stream_index >= avctx->nb_streams) mv->stream_index = 0; return 0; } static int mv_read_seek(AVFormatContext *avctx, int stream_index, int64_t timestamp, int flags) { MvContext *mv = avctx->priv_data; AVStream *st = avctx->streams[stream_index]; int frame, i; if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE)) return AVERROR(ENOSYS); if (!(avctx->pb->seekable & AVIO_SEEKABLE_NORMAL)) return AVERROR(EIO); frame = av_index_search_timestamp(st, timestamp, flags); if (frame < 0) return AVERROR_INVALIDDATA; for (i = 0; i < avctx->nb_streams; i++) mv->frame[i] = frame; return 0; } AVInputFormat ff_mv_demuxer = { .name = "mv", .long_name = NULL_IF_CONFIG_SMALL("Silicon Graphics Movie"), .priv_data_size = sizeof(MvContext), .read_probe = mv_probe, .read_header = mv_read_header, .read_packet = mv_read_packet, .read_seek = mv_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2762_0
crossvul-cpp_data_good_2785_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % X X BBBB M M % % X X B B MM MM % % X BBBB M M M % % X X B B M M % % X X BBBB M M % % % % % % Read/Write X Windows System Bitmap Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/pixel-accessor.h" #include "magick/quantum-private.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/utility.h" /* Forward declarations. */ static MagickBooleanType WriteXBMImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s X B M % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsXBM() returns MagickTrue if the image format type, identified by the % magick string, is XBM. % % The format of the IsXBM method is: % % MagickBooleanType IsXBM(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsXBM(const unsigned char *magick,const size_t length) { if (length < 7) return(MagickFalse); if (memcmp(magick,"#define",7) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadXBMImage() reads an X11 bitmap image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadXBMImage method is: % % Image *ReadXBMImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static int XBMInteger(Image *image,short int *hex_digits) { int c; unsigned int value; /* Skip any leading whitespace. */ do { c=ReadBlobByte(image); if (c == EOF) return(-1); } while ((c == ' ') || (c == '\t') || (c == '\n') || (c == '\r')); /* Evaluate number. */ value=0; while (hex_digits[c] >= 0) { if (value > (unsigned int) (INT_MAX/10)) break; value*=16; c&=0xff; if (value > (unsigned int) (INT_MAX-hex_digits[c])) break; value+=hex_digits[c]; c=ReadBlobByte(image); if (c == EOF) return(-1); } return((int) value); } static Image *ReadXBMImage(const ImageInfo *image_info,ExceptionInfo *exception) { char buffer[MaxTextExtent], name[MaxTextExtent]; Image *image; int c; MagickBooleanType status; register IndexPacket *indexes; register ssize_t i, x; register PixelPacket *q; register unsigned char *p; short int hex_digits[256]; ssize_t y; unsigned char *data; unsigned int bit, byte, bytes_per_line, height, length, padding, version, width; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Read X bitmap header. */ width=0; height=0; while (ReadBlobString(image,buffer) != (char *) NULL) if (sscanf(buffer,"#define %32s %u",name,&width) == 2) if ((strlen(name) >= 6) && (LocaleCompare(name+strlen(name)-6,"_width") == 0)) break; while (ReadBlobString(image,buffer) != (char *) NULL) if (sscanf(buffer,"#define %32s %u",name,&height) == 2) if ((strlen(name) >= 7) && (LocaleCompare(name+strlen(name)-7,"_height") == 0)) break; image->columns=width; image->rows=height; image->depth=8; image->storage_class=PseudoClass; image->colors=2; /* Scan until hex digits. */ version=11; while (ReadBlobString(image,buffer) != (char *) NULL) { if (sscanf(buffer,"static short %32s = {",name) == 1) version=10; else if (sscanf(buffer,"static unsigned char %s = {",name) == 1) version=11; else if (sscanf(buffer,"static char %32s = {",name) == 1) version=11; else continue; p=(unsigned char *) strrchr(name,'_'); if (p == (unsigned char *) NULL) p=(unsigned char *) name; else p++; if (LocaleCompare("bits[]",(char *) p) == 0) break; } if ((image->columns == 0) || (image->rows == 0) || (EOFBlob(image) != MagickFalse)) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); /* Initialize image structure. */ if (AcquireImageColormap(image,image->colors) == MagickFalse) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); /* Initialize colormap. */ image->colormap[0].red=QuantumRange; image->colormap[0].green=QuantumRange; image->colormap[0].blue=QuantumRange; image->colormap[1].red=(Quantum) 0; image->colormap[1].green=(Quantum) 0; image->colormap[1].blue=(Quantum) 0; if (image_info->ping != MagickFalse) { (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } /* Initialize hex values. */ hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'x']=0; hex_digits[(int) ' ']=(-1); hex_digits[(int) ',']=(-1); hex_digits[(int) '}']=(-1); hex_digits[(int) '\n']=(-1); hex_digits[(int) '\t']=(-1); /* Read hex image data. */ padding=0; if (((image->columns % 16) != 0) && ((image->columns % 16) < 9) && (version == 10)) padding=1; bytes_per_line=(unsigned int) (image->columns+7)/8+padding; length=(unsigned int) image->rows; data=(unsigned char *) AcquireQuantumMemory(length,bytes_per_line* sizeof(*data)); if (data == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); p=data; if (version == 10) for (i=0; i < (ssize_t) (bytes_per_line*image->rows); (i+=2)) { c=XBMInteger(image,hex_digits); if (c < 0) break; *p++=(unsigned char) c; if ((padding == 0) || (((i+2) % bytes_per_line) != 0)) *p++=(unsigned char) (c >> 8); } else for (i=0; i < (ssize_t) (bytes_per_line*image->rows); i++) { value=XBMInteger(image,hex_digits); if (c < 0) break; *p++=(unsigned char) c; } if (EOFBlob(image) != MagickFalse) { data=(unsigned char *) RelinquishMagickMemory(data); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } /* Convert X bitmap image to pixel packets. */ p=data; for (y=0; y < (ssize_t) image->rows; y++) { q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { if (bit == 0) byte=(unsigned int) (*p++); SetPixelIndex(indexes+x,(byte & 0x01) != 0 ? 0x01 : 0x00); bit++; byte>>=1; if (bit == 8) bit=0; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } data=(unsigned char *) RelinquishMagickMemory(data); (void) SyncImage(image); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterXBMImage() adds attributes for the XBM image format to % the list of supported formats. The attributes include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterXBMImage method is: % % size_t RegisterXBMImage(void) % */ ModuleExport size_t RegisterXBMImage(void) { MagickInfo *entry; entry=SetMagickInfo("XBM"); entry->decoder=(DecodeImageHandler *) ReadXBMImage; entry->encoder=(EncodeImageHandler *) WriteXBMImage; entry->magick=(IsImageFormatHandler *) IsXBM; entry->adjoin=MagickFalse; entry->description=ConstantString( "X Windows system bitmap (black and white)"); entry->module=ConstantString("XBM"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterXBMImage() removes format registrations made by the % XBM module from the list of supported formats. % % The format of the UnregisterXBMImage method is: % % UnregisterXBMImage(void) % */ ModuleExport void UnregisterXBMImage(void) { (void) UnregisterMagickInfo("XBM"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e X B M I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Procedure WriteXBMImage() writes an image to a file in the X bitmap format. % % The format of the WriteXBMImage method is: % % MagickBooleanType WriteXBMImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % */ static MagickBooleanType WriteXBMImage(const ImageInfo *image_info,Image *image) { char basename[MaxTextExtent], buffer[MaxTextExtent]; MagickBooleanType status; register const PixelPacket *p; register ssize_t x; size_t bit, byte; ssize_t count, y; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) TransformImageColorspace(image,sRGBColorspace); /* Write X bitmap header. */ GetPathComponent(image->filename,BasePath,basename); (void) FormatLocaleString(buffer,MaxTextExtent,"#define %s_width %.20g\n", basename,(double) image->columns); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) FormatLocaleString(buffer,MaxTextExtent,"#define %s_height %.20g\n", basename,(double) image->rows); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "static char %s_bits[] = {\n",basename); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) CopyMagickString(buffer," ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); /* Convert MIFF to X bitmap pixels. */ (void) SetImageType(image,BilevelType); bit=0; byte=0; count=0; x=0; y=0; (void) CopyMagickString(buffer," ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { byte>>=1; if (GetPixelLuma(image,p) < (QuantumRange/2.0)) byte|=0x80; bit++; if (bit == 8) { /* Write a bitmap byte to the image file. */ (void) FormatLocaleString(buffer,MaxTextExtent,"0x%02X, ", (unsigned int) (byte & 0xff)); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count++; if (count == 12) { (void) CopyMagickString(buffer,"\n ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count=0; }; bit=0; byte=0; } p++; } if (bit != 0) { /* Write a bitmap byte to the image file. */ byte>>=(8-bit); (void) FormatLocaleString(buffer,MaxTextExtent,"0x%02X, ", (unsigned int) (byte & 0xff)); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count++; if (count == 12) { (void) CopyMagickString(buffer,"\n ",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); count=0; }; bit=0; byte=0; }; status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } (void) CopyMagickString(buffer,"};\n",MaxTextExtent); (void) WriteBlob(image,strlen(buffer),(unsigned char *) buffer); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-834/c/good_2785_0
crossvul-cpp_data_bad_2781_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS % % P P SS % % PPPP SSS % % P SS % % P SSSSS % % % % % % Read/Write Postscript Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/delegate.h" #include "magick/delegate-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/profile.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/token.h" #include "magick/transform.h" #include "magick/utility.h" /* Forward declarations. */ static MagickBooleanType WritePSImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v o k e P o s t s r i p t D e l e g a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InvokePostscriptDelegate() executes the Postscript interpreter with the % specified command. % % The format of the InvokePostscriptDelegate method is: % % MagickBooleanType InvokePostscriptDelegate( % const MagickBooleanType verbose,const char *command, % ExceptionInfo *exception) % % A description of each parameter follows: % % o verbose: A value other than zero displays the command prior to % executing it. % % o command: the address of a character string containing the command to % execute. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) static int MagickDLLCall PostscriptDelegateMessage(void *handle, const char *message,int length) { char **messages; ssize_t offset; offset=0; messages=(char **) handle; if (*messages == (char *) NULL) *messages=(char *) AcquireQuantumMemory(length+1,sizeof(char *)); else { offset=strlen(*messages); *messages=(char *) ResizeQuantumMemory(*messages,offset+length+1, sizeof(char *)); } (void) memcpy(*messages+offset,message,length); (*messages)[length+offset] ='\0'; return(length); } #endif static MagickBooleanType InvokePostscriptDelegate( const MagickBooleanType verbose,const char *command,char *message, ExceptionInfo *exception) { int status; #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) #define SetArgsStart(command,args_start) \ if (args_start == (const char *) NULL) \ { \ if (*command != '"') \ args_start=strchr(command,' '); \ else \ { \ args_start=strchr(command+1,'"'); \ if (args_start != (const char *) NULL) \ args_start++; \ } \ } #define ExecuteGhostscriptCommand(command,status) \ { \ status=ExternalDelegateCommand(MagickFalse,verbose,command,message, \ exception); \ if (status == 0) \ return(MagickTrue); \ if (status < 0) \ return(MagickFalse); \ (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \ "FailedToExecuteCommand","`%s' (%d)",command,status); \ return(MagickFalse); \ } char **argv, *errors; const char *args_start = (const char *) NULL; const GhostInfo *ghost_info; gs_main_instance *interpreter; gsapi_revision_t revision; int argc, code; register ssize_t i; #if defined(MAGICKCORE_WINDOWS_SUPPORT) ghost_info=NTGhostscriptDLLVectors(); #else GhostInfo ghost_info_struct; ghost_info=(&ghost_info_struct); (void) ResetMagickMemory(&ghost_info_struct,0,sizeof(ghost_info_struct)); ghost_info_struct.delete_instance=(void (*)(gs_main_instance *)) gsapi_delete_instance; ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit; ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *)) gsapi_new_instance; ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **)) gsapi_init_with_args; ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int, int *)) gsapi_run_string; ghost_info_struct.set_stdio=(int (*)(gs_main_instance *,int(*)(void *,char *, int),int(*)(void *,const char *,int),int(*)(void *, const char *, int))) gsapi_set_stdio; ghost_info_struct.revision=(int (*)(gsapi_revision_t *,int)) gsapi_revision; #endif if (ghost_info == (GhostInfo *) NULL) ExecuteGhostscriptCommand(command,status); if ((ghost_info->revision)(&revision,sizeof(revision)) != 0) revision.revision=0; if (verbose != MagickFalse) { (void) fprintf(stdout,"[ghostscript library %.2f]",(double) revision.revision/100.0); SetArgsStart(command,args_start); (void) fputs(args_start,stdout); } errors=(char *) NULL; status=(ghost_info->new_instance)(&interpreter,(void *) &errors); if (status < 0) ExecuteGhostscriptCommand(command,status); code=0; argv=StringToArgv(command,&argc); if (argv == (char **) NULL) { (ghost_info->delete_instance)(interpreter); return(MagickFalse); } (void) (ghost_info->set_stdio)(interpreter,(int(MagickDLLCall *)(void *, char *,int)) NULL,PostscriptDelegateMessage,PostscriptDelegateMessage); status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1); if (status == 0) status=(ghost_info->run_string)(interpreter,"systemdict /start get exec\n", 0,&code); (ghost_info->exit)(interpreter); (ghost_info->delete_instance)(interpreter); for (i=0; i < (ssize_t) argc; i++) argv[i]=DestroyString(argv[i]); argv=(char **) RelinquishMagickMemory(argv); if (status != 0) { SetArgsStart(command,args_start); if (status == -101) /* quit */ (void) FormatLocaleString(message,MaxTextExtent, "[ghostscript library %.2f]%s: %s",(double)revision.revision / 100, args_start,errors); else { (void) ThrowMagickException(exception,GetMagickModule(), DelegateError,"PostscriptDelegateFailed", "`[ghostscript library %.2f]%s': %s", (double)revision.revision / 100,args_start,errors); if (errors != (char *) NULL) errors=DestroyString(errors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Ghostscript returns status %d, exit code %d",status,code); return(MagickFalse); } } if (errors != (char *) NULL) errors=DestroyString(errors); return(MagickTrue); #else status=ExternalDelegateCommand(MagickFalse,verbose,command,(char *) NULL, exception); return(status == 0 ? MagickTrue : MagickFalse); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPS() returns MagickTrue if the image format type, identified by the % magick string, is PS. % % The format of the IsPS method is: % % MagickBooleanType IsPS(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPS(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"%!",2) == 0) return(MagickTrue); if (memcmp(magick,"\004%!",3) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSImage() reads a Postscript image file and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer % to the new image. % % The format of the ReadPSImage method is: % % Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsPostscriptRendered(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if ((status != MagickFalse) && S_ISREG(attributes.st_mode) && (attributes.st_size > 0)) return(MagickTrue); return(MagickFalse); } static inline int ProfileInteger(Image *image,short int *hex_digits) { int c, l, value; register ssize_t i; l=0; value=0; for (i=0; i < 2; ) { c=ReadBlobByte(image); if ((c == EOF) || ((c == '%') && (l == '%'))) { value=(-1); break; } l=c; c&=0xff; if (isxdigit(c) == MagickFalse) continue; value=(int) ((size_t) value << 4)+hex_digits[c]; i++; } return(value); } static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "BoundingBox:" #define BeginDocument "BeginDocument:" #define BeginXMPPacket "<?xpacket begin=" #define EndXMPPacket "<?xpacket end=" #define ICCProfile "BeginICCProfile:" #define CMYKCustomColor "CMYKCustomColor:" #define CMYKProcessColor "CMYKProcessColor:" #define DocumentMedia "DocumentMedia:" #define DocumentCustomColors "DocumentCustomColors:" #define DocumentProcessColors "DocumentProcessColors:" #define EndDocument "EndDocument:" #define HiResBoundingBox "HiResBoundingBox:" #define ImageData "ImageData:" #define PageBoundingBox "PageBoundingBox:" #define LanguageLevel "LanguageLevel:" #define PageMedia "PageMedia:" #define Pages "Pages:" #define PhotoshopProfile "BeginPhotoshop:" #define PostscriptLevel "!PS-" #define RenderPostscriptText " Rendering Postscript... " #define SpotColor "+ " char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], input_filename[MaxTextExtent], message[MaxTextExtent], *options, postscript_filename[MaxTextExtent]; const char *option; const DelegateInfo *delegate_info; GeometryInfo geometry_info; Image *image, *next, *postscript_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, fitPage, skip, status; MagickStatusType flags; PointInfo delta, resolution; RectangleInfo page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; short int hex_digits[256]; size_t length, priority; ssize_t count; StringInfo *profile; unsigned long columns, extent, language_level, pages, rows, scene, spotcolor; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) ResetMagickMemory(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution.x=image->x_resolution; resolution.y=image->y_resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds)); priority=0; columns=0; rows=0; extent=0; spotcolor=0; language_level=1; skip=MagickFalse; pages=(~0UL); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,"ps:Level",command+4); if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel " %lu",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages " %lu",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData " %lu %lu",&columns,&rows); if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MaxTextExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *p; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent); if (count != 1) continue; length=extent; profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *p++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { register size_t i; /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,i+1); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,i); (void) SetImageProfile(image,"xmp",profile); profile=DestroyStringInfo(profile); continue; } /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MaxTextExtent], *value; register char *p; /* Note spot names. */ (void) FormatLocaleString(property,MaxTextExtent,"ps:SpotColor-%.20g", (double) (spotcolor++)); for (p=command; *p != '\0'; p++) if (isspace((int) (unsigned char) *p) != 0) break; value=AcquireString(p); (void) SubstituteString(&value,"(",""); (void) SubstituteString(&value,")",""); (void) StripString(value); (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"ps:HiResBoundingBox",geometry); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"eps:fit-page"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width,&page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/ delta.y) -0.5); geometry=DestroyString(geometry); fitPage=MagickTrue; } (void) CloseBlob(image); if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {" "dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n" "<</UseCIEColor true>>setpagedevice\n",MaxTextExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MaxTextExtent]; (void) FormatLocaleString(translate_geometry,MaxTextExtent, "%g %g translate\n",-hires_bounds.x1,-hires_bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",resolution.x, resolution.y); (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g ",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,"eps:use-cropbox"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,"-dEPSCrop ",MaxTextExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dEPSFitPage ",MaxTextExtent); } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command," -c showpage",MaxTextExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PostscriptDelegateFailed","`%s'",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } if (image_info->number_scenes != 0) { Image *clone_image; register ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename,MaxTextExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MaxTextExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSImage() adds properties for the PS image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSImage method is: % % size_t RegisterPSImage(void) % */ ModuleExport size_t RegisterPSImage(void) { MagickInfo *entry; entry=SetMagickInfo("EPI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSF"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("PostScript"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSImage() removes format registrations made by the % PS module from the list of supported formats. % % The format of the UnregisterPSImage method is: % % UnregisterPSImage(void) % */ ModuleExport void UnregisterPSImage(void) { (void) UnregisterMagickInfo("EPI"); (void) UnregisterMagickInfo("EPS"); (void) UnregisterMagickInfo("EPSF"); (void) UnregisterMagickInfo("EPSI"); (void) UnregisterMagickInfo("PS"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSImage translates an image to encapsulated Postscript % Level I for printing. If the supplied geometry is null, the image is % centered on the Postscript page. Otherwise, the image is positioned as % specified by the geometry. % % The format of the WritePSImage method is: % % MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ static inline unsigned char *PopHexPixel(const char *const *hex_digits, const size_t pixel,unsigned char *pixels) { register const char *hex; hex=hex_digits[pixel]; *pixels++=(unsigned char) (*hex++); *pixels++=(unsigned char) (*hex); return(pixels); } static MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image) { #define WriteRunlengthPacket(image,pixel,length,p) \ { \ if ((image->matte != MagickFalse) && (length != 0) &&\ (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) \ { \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ } \ else \ { \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.red),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.green),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.blue),q); \ } \ q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); \ } static const char *const hex_digits[] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF", (const char *) NULL }, *const PostscriptProlog[]= { "%%BeginProlog", "%", "% Display a color image. The image is displayed in color on", "% Postscript viewers or printers that support color, otherwise", "% it is displayed as grayscale.", "%", "/DirectClassPacket", "{", " %", " % Get a DirectClass packet.", " %", " % Parameters:", " % red.", " % green.", " % blue.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/DirectClassImage", "{", " %", " % Display a DirectClass image.", " %", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { DirectClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayDirectClassPacket } image", " } ifelse", "} bind def", "", "/GrayDirectClassPacket", "{", " %", " % Get a DirectClass packet; convert to grayscale.", " %", " % Parameters:", " % red", " % green", " % blue", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/GrayPseudoClassPacket", "{", " %", " % Get a PseudoClass packet; convert to grayscale.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassPacket", "{", " %", " % Get a PseudoClass packet.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassImage", "{", " %", " % Display a PseudoClass image.", " %", " % Parameters:", " % class: 0-PseudoClass or 1-Grayscale.", " %", " currentfile buffer readline pop", " token pop /class exch def pop", " class 0 gt", " {", " currentfile buffer readline pop", " token pop /depth exch def pop", " /grays columns 8 add depth sub depth mul 8 idiv string def", " columns rows depth", " [", " columns 0 0", " rows neg 0 rows", " ]", " { currentfile grays readhexstring pop } image", " }", " {", " %", " % Parameters:", " % colors: number of colors in the colormap.", " % colormap: red, green, blue color packets.", " %", " currentfile buffer readline pop", " token pop /colors exch def pop", " /colors colors 3 mul def", " /colormap colors string def", " currentfile colormap readhexstring pop pop", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { PseudoClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayPseudoClassPacket } image", " } ifelse", " } ifelse", "} bind def", "", "/DisplayImage", "{", " %", " % Display a DirectClass or PseudoClass image.", " %", " % Parameters:", " % x & y translation.", " % x & y scale.", " % label pointsize.", " % image label.", " % image columns & rows.", " % class: 0-DirectClass or 1-PseudoClass.", " % compression: 0-none or 1-RunlengthEncoded.", " % hex color packets.", " %", " gsave", " /buffer 512 string def", " /byte 1 string def", " /color_packet 3 string def", " /pixels 768 string def", "", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " x y translate", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " currentfile buffer readline pop", " token pop /pointsize exch def pop", (const char *) NULL }, *const PostscriptEpilog[]= { " x y scale", " currentfile buffer readline pop", " token pop /columns exch def", " token pop /rows exch def pop", " currentfile buffer readline pop", " token pop /class exch def pop", " currentfile buffer readline pop", " token pop /compression exch def pop", " class 0 gt { PseudoClassImage } { DirectClassImage } ifelse", " grestore", (const char *) NULL }; char buffer[MaxTextExtent], date[MaxTextExtent], **labels, page_geometry[MaxTextExtent]; CompressionType compression; const char *const *s, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; MagickStatusType flags; PixelPacket pixel; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; SegmentInfo bounds; size_t bit, byte, length, page, text_size; ssize_t j, y; time_t timer; unsigned char pixels[2048]; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; page=1; scene=0; do { /* Scale relative to dots-per-inch. */ if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,sRGBColorspace); delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); if (page == 1) { /* Output Postscript header. */ if (LocaleCompare(image_info->magick,"PS") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Title: (%s)\n", image->filename); (void) WriteBlobString(image,buffer); timer=time((time_t *) NULL); (void) FormatMagickTime(timer,MaxTextExtent,date); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%CreationDate: (%s)\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+scale.x; bounds.y2=(double) geometry.y+(geometry.height+text_size); if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) (void) CopyMagickString(buffer,"%%%%BoundingBox: (atend)\n", MaxTextExtent); else { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); } (void) WriteBlobString(image,buffer); profile=GetImageProfile(image,"8bim"); if (profile != (StringInfo *) NULL) { /* Embed Photoshop profile. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%%BeginPhotoshop: %.20g",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) { if ((i % 32) == 0) (void) WriteBlobString(image,"\n% "); (void) FormatLocaleString(buffer,MaxTextExtent,"%02X", (unsigned int) (GetStringInfoDatum(profile)[i] & 0xff)); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"\n%EndPhotoshop\n"); } profile=GetImageProfile(image,"xmp"); DisableMSCWarning(4127) if (0 && (profile != (StringInfo *) NULL)) RestoreMSCWarning { /* Embed XML profile. */ (void) WriteBlobString(image,"\n%begin_xml_code\n"); (void) FormatLocaleString(buffer,MaxTextExtent, "\n%%begin_xml_packet: %.20g\n",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) (void) WriteBlobByte(image,GetStringInfoDatum(profile)[i]); (void) WriteBlobString(image,"\n%end_xml_packet\n%end_xml_code\n"); } value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Times-Roman\n"); (void) WriteBlobString(image,"%%DocumentData: Clean7Bit\n"); (void) WriteBlobString(image,"%%LanguageLevel: 1\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { /* Compute the number of pages. */ (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Pages: %.20g\n", image_info->adjoin != MagickFalse ? (double) GetImageListLength(image) : 1.0); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EndComments\n"); (void) WriteBlobString(image,"\n%%BeginDefaults\n"); (void) WriteBlobString(image,"%%EndDefaults\n\n"); if ((LocaleCompare(image_info->magick,"EPI") == 0) || (LocaleCompare(image_info->magick,"EPSI") == 0) || (LocaleCompare(image_info->magick,"EPT") == 0)) { Image *preview_image; Quantum pixel; register ssize_t x; ssize_t y; /* Create preview image. */ preview_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (preview_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BeginPreview: %.20g %.20g %.20g %.20g\n%% ",(double) preview_image->columns,(double) preview_image->rows,1.0, (double) ((((preview_image->columns+7) >> 3)*preview_image->rows+ 35)/36)); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(preview_image,0,y,preview_image->columns,1, &preview_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(preview_image); bit=0; byte=0; for (x=0; x < (ssize_t) preview_image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; bit=0; byte=0; } } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; }; } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } (void) WriteBlobString(image,"\n%%EndPreview\n"); preview_image=DestroyImage(preview_image); } /* Output Postscript commands. */ for (s=PostscriptProlog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } value=GetImageProperty(image,"label"); if (value != (const char *) NULL) { (void) WriteBlobString(image, " /Times-Roman findfont pointsize scalefont setfont\n"); for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--) { (void) WriteBlobString(image," /label 512 string def\n"); (void) WriteBlobString(image, " currentfile label readline pop\n"); (void) FormatLocaleString(buffer,MaxTextExtent, " 0 y %g add moveto label show pop\n",j*pointsize+12); (void) WriteBlobString(image,buffer); } } for (s=PostscriptEpilog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } if (LocaleCompare(image_info->magick,"PS") == 0) (void) WriteBlobString(image," showpage\n"); (void) WriteBlobString(image,"} bind def\n"); (void) WriteBlobString(image,"%%EndProlog\n"); } (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Page: 1 %.20g\n", (double) (page++)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x, (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+geometry.width-1) > bounds.x2) bounds.x2=(double) geometry.x+geometry.width-1; if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2) bounds.y2=(double) geometry.y+(geometry.height+text_size)-1; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%%%PageResources: font Times-Roman\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"userdict begin\n"); (void) WriteBlobString(image,"DisplayImage\n"); /* Output image data. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n%g %g\n%g\n", (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s \n", labels[i]); (void) WriteBlobString(image,buffer); labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); pixel.opacity=(Quantum) TransparentOpacity; index=(IndexPacket) 0; x=0; if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { if (SetImageMonochrome(image,&image->exception) == MagickFalse) { Quantum pixel; /* Dump image as grayscale. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n1\n1\n1\n8\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); q=PopHexPixel(hex_digits,(size_t) pixel,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } else { ssize_t y; Quantum pixel; /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n1\n1\n1\n1\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; }; bit=0; byte=0; } p++; } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } }; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (image->matte != MagickFalse)) { /* Dump DirectClass image. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n0\n%d\n", (double) image->columns,(double) image->rows, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); switch (compression) { case RLECompression: { /* Dump runlength-encoded DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; pixel=(*p); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((GetPixelRed(p) == pixel.red) && (GetPixelGreen(p) == pixel.green) && (GetPixelBlue(p) == pixel.blue) && (GetPixelOpacity(p) == pixel.opacity) && (length < 255) && (x < (ssize_t) (image->columns-1))) length++; else { if (x > 0) { WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } pixel=(*p); p++; } WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((image->matte != MagickFalse) && (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) { q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); } else { q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelRed(p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelGreen(p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelBlue(p)),q); } if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } else { /* Dump PseudoClass image. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n%d\n%d\n0\n",(double) image->columns,(double) image->rows,image->storage_class == PseudoClass ? 1 : 0, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); /* Dump number of colors and colormap. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) image->colors); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%02X%02X%02X\n", ScaleQuantumToChar(image->colormap[i].red), ScaleQuantumToChar(image->colormap[i].green), ScaleQuantumToChar(image->colormap[i].blue)); (void) WriteBlobString(image,buffer); } switch (compression) { case RLECompression: { /* Dump runlength-encoded PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); index=GetPixelIndex(indexes); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((index == GetPixelIndex(indexes+x)) && (length < 255) && (x < ((ssize_t) image->columns-1))) length++; else { if (x > 0) { q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); i++; if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } index=GetPixelIndex(indexes+x); pixel.red=GetPixelRed(p); pixel.green=GetPixelGreen(p); pixel.blue=GetPixelBlue(p); pixel.opacity=GetPixelOpacity(p); p++; } q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { q=PopHexPixel(hex_digits,(size_t) GetPixelIndex( indexes+x),q); if ((q-pixels+4) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 2) { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2781_0
crossvul-cpp_data_bad_2786_0
/* * MOV demuxer * Copyright (c) 2001 Fabrice Bellard * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * first version by Francois Revol <revol@free.fr> * seek function by Gael Chardon <gael.dev@4now.net> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include <limits.h> #include <stdint.h> #include "libavutil/attributes.h" #include "libavutil/channel_layout.h" #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/time_internal.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/dict.h" #include "libavutil/display.h" #include "libavutil/opt.h" #include "libavutil/aes.h" #include "libavutil/aes_ctr.h" #include "libavutil/pixdesc.h" #include "libavutil/sha.h" #include "libavutil/spherical.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavcodec/ac3tab.h" #include "libavcodec/flac.h" #include "libavcodec/mpegaudiodecheader.h" #include "avformat.h" #include "internal.h" #include "avio_internal.h" #include "riff.h" #include "isom.h" #include "libavcodec/get_bits.h" #include "id3v1.h" #include "mov_chan.h" #include "replaygain.h" #if CONFIG_ZLIB #include <zlib.h> #endif #include "qtpalette.h" /* those functions parse an atom */ /* links atom IDs to parse functions */ typedef struct MOVParseTableEntry { uint32_t type; int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom); } MOVParseTableEntry; static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom); static int mov_read_mfra(MOVContext *c, AVIOContext *f); static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size, int count, int duration); static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { char buf[16]; short current, total = 0; avio_rb16(pb); // unknown current = avio_rb16(pb); if (len >= 6) total = avio_rb16(pb); if (!total) snprintf(buf, sizeof(buf), "%d", current); else snprintf(buf, sizeof(buf), "%d/%d", current, total); c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set(&c->fc->metadata, key, buf, 0); return 0; } static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { /* bypass padding bytes */ avio_r8(pb); avio_r8(pb); avio_r8(pb); c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0); return 0; } static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0); return 0; } static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { short genre; avio_r8(pb); // unknown genre = avio_r8(pb); if (genre < 1 || genre > ID3v1_GENRE_MAX) return 0; c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0); return 0; } static const uint32_t mac_to_unicode[128] = { 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1, 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8, 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3, 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC, 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF, 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8, 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211, 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8, 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB, 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153, 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA, 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02, 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1, 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4, 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC, 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7, }; static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len, char *dst, int dstlen) { char *p = dst; char *end = dst+dstlen-1; int i; for (i = 0; i < len; i++) { uint8_t t, c = avio_r8(pb); if (p >= end) continue; if (c < 0x80) *p++ = c; else if (p < end) PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;); } *p = 0; return p - dst; } static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len) { AVPacket pkt; AVStream *st; MOVStreamContext *sc; enum AVCodecID id; int ret; switch (type) { case 0xd: id = AV_CODEC_ID_MJPEG; break; case 0xe: id = AV_CODEC_ID_PNG; break; case 0x1b: id = AV_CODEC_ID_BMP; break; default: av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type); avio_skip(pb, len); return 0; } st = avformat_new_stream(c->fc, NULL); if (!st) return AVERROR(ENOMEM); sc = av_mallocz(sizeof(*sc)); if (!sc) return AVERROR(ENOMEM); st->priv_data = sc; ret = av_get_packet(pb, &pkt, len); if (ret < 0) return ret; if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) { if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) { id = AV_CODEC_ID_PNG; } else { id = AV_CODEC_ID_MJPEG; } } st->disposition |= AV_DISPOSITION_ATTACHED_PIC; st->attached_pic = pkt; st->attached_pic.stream_index = st->index; st->attached_pic.flags |= AV_PKT_FLAG_KEY; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = id; return 0; } // 3GPP TS 26.244 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len) { char language[4] = { 0 }; char buf[200], place[100]; uint16_t langcode = 0; double longitude, latitude, altitude; const char *key = "location"; if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) { av_log(c->fc, AV_LOG_ERROR, "loci too short\n"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); // version+flags langcode = avio_rb16(pb); ff_mov_lang_to_iso639(langcode, language); len -= 6; len -= avio_get_str(pb, len, place, sizeof(place)); if (len < 1) { av_log(c->fc, AV_LOG_ERROR, "place name too long\n"); return AVERROR_INVALIDDATA; } avio_skip(pb, 1); // role len -= 1; if (len < 12) { av_log(c->fc, AV_LOG_ERROR, "loci too short (%u bytes left, need at least %d)\n", len, 12); return AVERROR_INVALIDDATA; } longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16); latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16); altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16); // Try to output in the same format as the ?xyz field snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude); if (altitude) av_strlcatf(buf, sizeof(buf), "%+f", altitude); av_strlcatf(buf, sizeof(buf), "/%s", place); if (*language && strcmp(language, "und")) { char key2[16]; snprintf(key2, sizeof(key2), "%s-%s", key, language); av_dict_set(&c->fc->metadata, key2, buf, 0); } c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; return av_dict_set(&c->fc->metadata, key, buf, 0); } static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len) { int i, n_hmmt; if (len < 2) return 0; if (c->ignore_chapters) return 0; n_hmmt = avio_rb32(pb); for (i = 0; i < n_hmmt && !pb->eof_reached; i++) { int moment_time = avio_rb32(pb); avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL); } return 0; } static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom) { char tmp_key[5]; char key2[32], language[4] = {0}; char *str = NULL; const char *key = NULL; uint16_t langcode = 0; uint32_t data_type = 0, str_size, str_size_alloc; int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL; int raw = 0; int num = 0; switch (atom.type) { case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break; case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break; case MKTAG( 'X','M','P','_'): if (c->export_xmp) { key = "xmp"; raw = 1; } break; case MKTAG( 'a','A','R','T'): key = "album_artist"; break; case MKTAG( 'a','k','I','D'): key = "account_type"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'a','p','I','D'): key = "account_id"; break; case MKTAG( 'c','a','t','g'): key = "category"; break; case MKTAG( 'c','p','i','l'): key = "compilation"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'c','p','r','t'): key = "copyright"; break; case MKTAG( 'd','e','s','c'): key = "description"; break; case MKTAG( 'd','i','s','k'): key = "disc"; parse = mov_metadata_track_or_disc_number; break; case MKTAG( 'e','g','i','d'): key = "episode_uid"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break; case MKTAG( 'g','n','r','e'): key = "genre"; parse = mov_metadata_gnre; break; case MKTAG( 'h','d','v','d'): key = "hd_video"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'H','M','M','T'): return mov_metadata_hmmt(c, pb, atom.size); case MKTAG( 'k','e','y','w'): key = "keywords"; break; case MKTAG( 'l','d','e','s'): key = "synopsis"; break; case MKTAG( 'l','o','c','i'): return mov_metadata_loci(c, pb, atom.size); case MKTAG( 'p','c','s','t'): key = "podcast"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'p','g','a','p'): key = "gapless_playback"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'p','u','r','d'): key = "purchase_date"; break; case MKTAG( 'r','t','n','g'): key = "rating"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break; case MKTAG( 's','o','a','l'): key = "sort_album"; break; case MKTAG( 's','o','a','r'): key = "sort_artist"; break; case MKTAG( 's','o','c','o'): key = "sort_composer"; break; case MKTAG( 's','o','n','m'): key = "sort_name"; break; case MKTAG( 's','o','s','n'): key = "sort_show"; break; case MKTAG( 's','t','i','k'): key = "media_type"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 't','r','k','n'): key = "track"; parse = mov_metadata_track_or_disc_number; break; case MKTAG( 't','v','e','n'): key = "episode_id"; break; case MKTAG( 't','v','e','s'): key = "episode_sort"; parse = mov_metadata_int8_bypass_padding; break; case MKTAG( 't','v','n','n'): key = "network"; break; case MKTAG( 't','v','s','h'): key = "show"; break; case MKTAG( 't','v','s','n'): key = "season_number"; parse = mov_metadata_int8_bypass_padding; break; case MKTAG(0xa9,'A','R','T'): key = "artist"; break; case MKTAG(0xa9,'P','R','D'): key = "producer"; break; case MKTAG(0xa9,'a','l','b'): key = "album"; break; case MKTAG(0xa9,'a','u','t'): key = "artist"; break; case MKTAG(0xa9,'c','h','p'): key = "chapter"; break; case MKTAG(0xa9,'c','m','t'): key = "comment"; break; case MKTAG(0xa9,'c','o','m'): key = "composer"; break; case MKTAG(0xa9,'c','p','y'): key = "copyright"; break; case MKTAG(0xa9,'d','a','y'): key = "date"; break; case MKTAG(0xa9,'d','i','r'): key = "director"; break; case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break; case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break; case MKTAG(0xa9,'e','n','c'): key = "encoder"; break; case MKTAG(0xa9,'f','m','t'): key = "original_format"; break; case MKTAG(0xa9,'g','e','n'): key = "genre"; break; case MKTAG(0xa9,'g','r','p'): key = "grouping"; break; case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break; case MKTAG(0xa9,'i','n','f'): key = "comment"; break; case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break; case MKTAG(0xa9,'m','a','k'): key = "make"; break; case MKTAG(0xa9,'m','o','d'): key = "model"; break; case MKTAG(0xa9,'n','a','m'): key = "title"; break; case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break; case MKTAG(0xa9,'p','r','d'): key = "producer"; break; case MKTAG(0xa9,'p','r','f'): key = "performers"; break; case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break; case MKTAG(0xa9,'s','r','c'): key = "original_source"; break; case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break; case MKTAG(0xa9,'s','w','r'): key = "encoder"; break; case MKTAG(0xa9,'t','o','o'): key = "encoder"; break; case MKTAG(0xa9,'t','r','k'): key = "track"; break; case MKTAG(0xa9,'u','r','l'): key = "URL"; break; case MKTAG(0xa9,'w','r','n'): key = "warning"; break; case MKTAG(0xa9,'w','r','t'): key = "composer"; break; case MKTAG(0xa9,'x','y','z'): key = "location"; break; } retry: if (c->itunes_metadata && atom.size > 8) { int data_size = avio_rb32(pb); int tag = avio_rl32(pb); if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) { data_type = avio_rb32(pb); // type avio_rb32(pb); // unknown str_size = data_size - 16; atom.size -= 16; if (atom.type == MKTAG('c', 'o', 'v', 'r')) { int ret = mov_read_covr(c, pb, data_type, str_size); if (ret < 0) { av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n"); } return ret; } else if (!key && c->found_hdlr_mdta && c->meta_keys) { uint32_t index = AV_RB32(&atom.type); if (index < c->meta_keys_count && index > 0) { key = c->meta_keys[index]; } else { av_log(c->fc, AV_LOG_WARNING, "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n", index, c->meta_keys_count); } } } else return 0; } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) { str_size = avio_rb16(pb); // string length if (str_size > atom.size) { raw = 1; avio_seek(pb, -2, SEEK_CUR); av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n"); goto retry; } langcode = avio_rb16(pb); ff_mov_lang_to_iso639(langcode, language); atom.size -= 4; } else str_size = atom.size; if (c->export_all && !key) { snprintf(tmp_key, 5, "%.4s", (char*)&atom.type); key = tmp_key; } if (!key) return 0; if (atom.size < 0 || str_size >= INT_MAX/2) return AVERROR_INVALIDDATA; // Allocates enough space if data_type is a int32 or float32 number, otherwise // worst-case requirement for output string in case of utf8 coded input num = (data_type >= 21 && data_type <= 23); str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1; str = av_mallocz(str_size_alloc); if (!str) return AVERROR(ENOMEM); if (parse) parse(c, pb, str_size, key); else { if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded mov_read_mac_string(c, pb, str_size, str, str_size_alloc); } else if (data_type == 21) { // BE signed integer, variable size int val = 0; if (str_size == 1) val = (int8_t)avio_r8(pb); else if (str_size == 2) val = (int16_t)avio_rb16(pb); else if (str_size == 3) val = ((int32_t)(avio_rb24(pb)<<8))>>8; else if (str_size == 4) val = (int32_t)avio_rb32(pb); if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) { av_log(c->fc, AV_LOG_ERROR, "Failed to store the number (%d) in string.\n", val); av_free(str); return AVERROR_INVALIDDATA; } } else if (data_type == 22) { // BE unsigned integer, variable size unsigned int val = 0; if (str_size == 1) val = avio_r8(pb); else if (str_size == 2) val = avio_rb16(pb); else if (str_size == 3) val = avio_rb24(pb); else if (str_size == 4) val = avio_rb32(pb); if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) { av_log(c->fc, AV_LOG_ERROR, "Failed to store the number (%u) in string.\n", val); av_free(str); return AVERROR_INVALIDDATA; } } else if (data_type == 23 && str_size >= 4) { // BE float32 float val = av_int2float(avio_rb32(pb)); if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) { av_log(c->fc, AV_LOG_ERROR, "Failed to store the float32 number (%f) in string.\n", val); av_free(str); return AVERROR_INVALIDDATA; } } else { int ret = ffio_read_size(pb, str, str_size); if (ret < 0) { av_free(str); return ret; } str[str_size] = 0; } c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set(&c->fc->metadata, key, str, 0); if (*language && strcmp(language, "und")) { snprintf(key2, sizeof(key2), "%s-%s", key, language); av_dict_set(&c->fc->metadata, key2, str, 0); } if (!strcmp(key, "encoder")) { int major, minor, micro; if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) { c->handbrake_version = 1000000*major + 1000*minor + micro; } } } av_freep(&str); return 0; } static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t start; int i, nb_chapters, str_len, version; char str[256+1]; int ret; if (c->ignore_chapters) return 0; if ((atom.size -= 5) < 0) return 0; version = avio_r8(pb); avio_rb24(pb); if (version) avio_rb32(pb); // ??? nb_chapters = avio_r8(pb); for (i = 0; i < nb_chapters; i++) { if (atom.size < 9) return 0; start = avio_rb64(pb); str_len = avio_r8(pb); if ((atom.size -= 9+str_len) < 0) return 0; ret = ffio_read_size(pb, str, str_len); if (ret < 0) return ret; str[str_len] = 0; avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str); } return 0; } #define MIN_DATA_ENTRY_BOX_SIZE 12 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int entries, i, j; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (!entries || entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 || entries >= UINT_MAX / sizeof(*sc->drefs)) return AVERROR_INVALIDDATA; sc->drefs_count = 0; av_free(sc->drefs); sc->drefs_count = 0; sc->drefs = av_mallocz(entries * sizeof(*sc->drefs)); if (!sc->drefs) return AVERROR(ENOMEM); sc->drefs_count = entries; for (i = 0; i < entries; i++) { MOVDref *dref = &sc->drefs[i]; uint32_t size = avio_rb32(pb); int64_t next = avio_tell(pb) + size - 4; if (size < 12) return AVERROR_INVALIDDATA; dref->type = avio_rl32(pb); avio_rb32(pb); // version + flags if (dref->type == MKTAG('a','l','i','s') && size > 150) { /* macintosh alias record */ uint16_t volume_len, len; int16_t type; int ret; avio_skip(pb, 10); volume_len = avio_r8(pb); volume_len = FFMIN(volume_len, 27); ret = ffio_read_size(pb, dref->volume, 27); if (ret < 0) return ret; dref->volume[volume_len] = 0; av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len); avio_skip(pb, 12); len = avio_r8(pb); len = FFMIN(len, 63); ret = ffio_read_size(pb, dref->filename, 63); if (ret < 0) return ret; dref->filename[len] = 0; av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len); avio_skip(pb, 16); /* read next level up_from_alias/down_to_target */ dref->nlvl_from = avio_rb16(pb); dref->nlvl_to = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n", dref->nlvl_from, dref->nlvl_to); avio_skip(pb, 16); for (type = 0; type != -1 && avio_tell(pb) < next; ) { if(avio_feof(pb)) return AVERROR_EOF; type = avio_rb16(pb); len = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len); if (len&1) len += 1; if (type == 2) { // absolute path av_free(dref->path); dref->path = av_mallocz(len+1); if (!dref->path) return AVERROR(ENOMEM); ret = ffio_read_size(pb, dref->path, len); if (ret < 0) { av_freep(&dref->path); return ret; } if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) { len -= volume_len; memmove(dref->path, dref->path+volume_len, len); dref->path[len] = 0; } // trim string of any ending zeros for (j = len - 1; j >= 0; j--) { if (dref->path[j] == 0) len--; else break; } for (j = 0; j < len; j++) if (dref->path[j] == ':' || dref->path[j] == 0) dref->path[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path); } else if (type == 0) { // directory name av_free(dref->dir); dref->dir = av_malloc(len+1); if (!dref->dir) return AVERROR(ENOMEM); ret = ffio_read_size(pb, dref->dir, len); if (ret < 0) { av_freep(&dref->dir); return ret; } dref->dir[len] = 0; for (j = 0; j < len; j++) if (dref->dir[j] == ':') dref->dir[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir); } else avio_skip(pb, len); } } else { av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n", dref->type, size); entries--; i--; } avio_seek(pb, next, SEEK_SET); } return 0; } static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint32_t type; uint32_t ctype; int64_t title_size; char *title_str; int ret; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ /* component type */ ctype = avio_rl32(pb); type = avio_rl32(pb); /* component subtype */ av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype)); av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type)); if (c->trak_index < 0) { // meta not inside a trak if (type == MKTAG('m','d','t','a')) { c->found_hdlr_mdta = 1; } return 0; } st = c->fc->streams[c->fc->nb_streams-1]; if (type == MKTAG('v','i','d','e')) st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; else if (type == MKTAG('s','o','u','n')) st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; else if (type == MKTAG('m','1','a',' ')) st->codecpar->codec_id = AV_CODEC_ID_MP2; else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p'))) st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; avio_rb32(pb); /* component manufacture */ avio_rb32(pb); /* component flags */ avio_rb32(pb); /* component flags mask */ title_size = atom.size - 24; if (title_size > 0) { if (title_size > FFMIN(INT_MAX, SIZE_MAX-1)) return AVERROR_INVALIDDATA; title_str = av_malloc(title_size + 1); /* Add null terminator */ if (!title_str) return AVERROR(ENOMEM); ret = ffio_read_size(pb, title_str, title_size); if (ret < 0) { av_freep(&title_str); return ret; } title_str[title_size] = 0; if (title_str[0]) { int off = (!c->isom && title_str[0] == title_size - 1); av_dict_set(&st->metadata, "handler_name", title_str + off, 0); } av_freep(&title_str); } return 0; } int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb) { AVStream *st; int tag; if (fc->nb_streams < 1) return 0; st = fc->streams[fc->nb_streams-1]; avio_rb32(pb); /* version + flags */ ff_mp4_read_descr(fc, pb, &tag); if (tag == MP4ESDescrTag) { ff_mp4_parse_es_descr(pb, NULL); } else avio_rb16(pb); /* ID */ ff_mp4_read_descr(fc, pb, &tag); if (tag == MP4DecConfigDescrTag) ff_mp4_read_dec_config_descr(fc, st, pb); return 0; } static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return ff_mov_read_esds(c->fc, pb); } static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; enum AVAudioServiceType *ast; int ac3info, acmod, lfeon, bsmod; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE, sizeof(*ast)); if (!ast) return AVERROR(ENOMEM); ac3info = avio_rb24(pb); bsmod = (ac3info >> 14) & 0x7; acmod = (ac3info >> 11) & 0x7; lfeon = (ac3info >> 10) & 0x1; st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon; st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod]; if (lfeon) st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY; *ast = bsmod; if (st->codecpar->channels > 1 && bsmod == 0x7) *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->audio_service_type = *ast; FF_ENABLE_DEPRECATION_WARNINGS #endif return 0; } static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; enum AVAudioServiceType *ast; int eac3info, acmod, lfeon, bsmod; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE, sizeof(*ast)); if (!ast) return AVERROR(ENOMEM); /* No need to parse fields for additional independent substreams and its * associated dependent substreams since libavcodec's E-AC-3 decoder * does not support them yet. */ avio_rb16(pb); /* data_rate and num_ind_sub */ eac3info = avio_rb24(pb); bsmod = (eac3info >> 12) & 0x1f; acmod = (eac3info >> 9) & 0x7; lfeon = (eac3info >> 8) & 0x1; st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod]; if (lfeon) st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY; st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout); *ast = bsmod; if (st->codecpar->channels > 1 && bsmod == 0x7) *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->audio_service_type = *ast; FF_ENABLE_DEPRECATION_WARNINGS #endif return 0; } static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { const uint32_t ddts_size = 20; AVStream *st = NULL; uint8_t *buf = NULL; uint32_t frame_duration_code = 0; uint32_t channel_layout_code = 0; GetBitContext gb; buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!buf) { return AVERROR(ENOMEM); } if (avio_read(pb, buf, ddts_size) < ddts_size) { av_free(buf); return AVERROR_INVALIDDATA; } init_get_bits(&gb, buf, 8*ddts_size); if (c->fc->nb_streams < 1) { av_free(buf); return 0; } st = c->fc->streams[c->fc->nb_streams-1]; st->codecpar->sample_rate = get_bits_long(&gb, 32); if (st->codecpar->sample_rate <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate); av_free(buf); return AVERROR_INVALIDDATA; } skip_bits_long(&gb, 32); /* max bitrate */ st->codecpar->bit_rate = get_bits_long(&gb, 32); st->codecpar->bits_per_coded_sample = get_bits(&gb, 8); frame_duration_code = get_bits(&gb, 2); skip_bits(&gb, 30); /* various fields */ channel_layout_code = get_bits(&gb, 16); st->codecpar->frame_size = (frame_duration_code == 0) ? 512 : (frame_duration_code == 1) ? 1024 : (frame_duration_code == 2) ? 2048 : (frame_duration_code == 3) ? 4096 : 0; if (channel_layout_code > 0xff) { av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout"); } st->codecpar->channel_layout = ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) | ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) | ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) | ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) | ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) | ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0); st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout); av_free(buf); return 0; } static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size < 16) return 0; /* skip version and flags */ avio_skip(pb, 4); ff_mov_read_chan(c->fc, pb, st, atom.size - 4); return 0; } static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0) av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n"); return ret; } static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { const int num = avio_rb32(pb); const int den = avio_rb32(pb); AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) { av_log(c->fc, AV_LOG_WARNING, "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n", st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, num, den); } else if (den != 0) { av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, num, den, 32767); } return 0; } /* this atom contains actual media data */ static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (atom.size == 0) /* wrong one (MP4) */ return 0; c->found_mdat=1; return 0; /* now go for moov */ } #define DRM_BLOB_SIZE 56 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint8_t intermediate_key[20]; uint8_t intermediate_iv[20]; uint8_t input[64]; uint8_t output[64]; uint8_t file_checksum[20]; uint8_t calculated_checksum[20]; struct AVSHA *sha; int i; int ret = 0; uint8_t *activation_bytes = c->activation_bytes; uint8_t *fixed_key = c->audible_fixed_key; c->aax_mode = 1; sha = av_sha_alloc(); if (!sha) return AVERROR(ENOMEM); c->aes_decrypt = av_aes_alloc(); if (!c->aes_decrypt) { ret = AVERROR(ENOMEM); goto fail; } /* drm blob processing */ avio_read(pb, output, 8); // go to offset 8, absolute position 0x251 avio_read(pb, input, DRM_BLOB_SIZE); avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d avio_read(pb, file_checksum, 20); av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools for (i = 0; i < 20; i++) av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]); av_log(c->fc, AV_LOG_INFO, "\n"); /* verify activation data */ if (!activation_bytes) { av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n"); ret = 0; /* allow ffprobe to continue working on .aax files */ goto fail; } if (c->activation_bytes_size != 4) { av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n"); ret = AVERROR(EINVAL); goto fail; } /* verify fixed key */ if (c->audible_fixed_key_size != 16) { av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n"); ret = AVERROR(EINVAL); goto fail; } /* AAX (and AAX+) key derivation */ av_sha_init(sha, 160); av_sha_update(sha, fixed_key, 16); av_sha_update(sha, activation_bytes, 4); av_sha_final(sha, intermediate_key); av_sha_init(sha, 160); av_sha_update(sha, fixed_key, 16); av_sha_update(sha, intermediate_key, 20); av_sha_update(sha, activation_bytes, 4); av_sha_final(sha, intermediate_iv); av_sha_init(sha, 160); av_sha_update(sha, intermediate_key, 16); av_sha_update(sha, intermediate_iv, 16); av_sha_final(sha, calculated_checksum); if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n"); ret = AVERROR_INVALIDDATA; goto fail; } av_aes_init(c->aes_decrypt, intermediate_key, 128, 1); av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1); for (i = 0; i < 4; i++) { // file data (in output) is stored in big-endian mode if (activation_bytes[i] != output[3 - i]) { // critical error av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n"); ret = AVERROR_INVALIDDATA; goto fail; } } memcpy(c->file_key, output + 8, 16); memcpy(input, output + 26, 16); av_sha_init(sha, 160); av_sha_update(sha, input, 16); av_sha_update(sha, c->file_key, 16); av_sha_update(sha, fixed_key, 16); av_sha_final(sha, c->file_iv); fail: av_free(sha); return ret; } // Audible AAX (and AAX+) bytestream decryption static int aax_filter(uint8_t *input, int size, MOVContext *c) { int blocks = 0; unsigned char iv[16]; memcpy(iv, c->file_iv, 16); // iv is overwritten blocks = size >> 4; // trailing bytes are not encrypted! av_aes_init(c->aes_decrypt, c->file_key, 128, 1); av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1); return 0; } /* read major brand, minor version and compatible brands and store them as metadata */ static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint32_t minor_ver; int comp_brand_size; char* comp_brands_str; uint8_t type[5] = {0}; int ret = ffio_read_size(pb, type, 4); if (ret < 0) return ret; if (strcmp(type, "qt ")) c->isom = 1; av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type); av_dict_set(&c->fc->metadata, "major_brand", type, 0); minor_ver = avio_rb32(pb); /* minor version */ av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0); comp_brand_size = atom.size - 8; if (comp_brand_size < 0) return AVERROR_INVALIDDATA; comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */ if (!comp_brands_str) return AVERROR(ENOMEM); ret = ffio_read_size(pb, comp_brands_str, comp_brand_size); if (ret < 0) { av_freep(&comp_brands_str); return ret; } comp_brands_str[comp_brand_size] = 0; av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0); av_freep(&comp_brands_str); return 0; } /* this atom should contain all header atoms */ static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; if (c->found_moov) { av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n"); avio_skip(pb, atom.size); return 0; } if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */ /* so we don't parse the whole file if over a network */ c->found_moov=1; return 0; /* now go for mdat */ } static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (!c->has_looked_for_mfra && c->use_mfra_for > 0) { c->has_looked_for_mfra = 1; if (pb->seekable & AVIO_SEEKABLE_NORMAL) { int ret; av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look " "for a mfra\n"); if ((ret = mov_read_mfra(c, pb)) < 0) { av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to " "read the mfra (may be a live ismv)\n"); } } else { av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not " "seekable, can not look for mfra\n"); } } c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8; av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset); return mov_read_default(c, pb, atom); } static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time) { if (time) { if(time >= 2082844800) time -= 2082844800; /* seconds between 1904-01-01 and Epoch */ if ((int64_t)(time * 1000000ULL) / 1000000 != time) { av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n"); return; } avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000); } } static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int version; char language[4] = {0}; unsigned lang; int64_t creation_time; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; if (sc->time_scale) { av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version > 1) { avpriv_request_sample(c->fc, "Version %d", version); return AVERROR_PATCHWELCOME; } avio_rb24(pb); /* flags */ if (version == 1) { creation_time = avio_rb64(pb); avio_rb64(pb); } else { creation_time = avio_rb32(pb); avio_rb32(pb); /* modification time */ } mov_metadata_creation_time(&st->metadata, creation_time); sc->time_scale = avio_rb32(pb); if (sc->time_scale <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale); sc->time_scale = 1; } st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */ lang = avio_rb16(pb); /* language */ if (ff_mov_lang_to_iso639(lang, language)) av_dict_set(&st->metadata, "language", language, 0); avio_rb16(pb); /* quality */ return 0; } static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int i; int64_t creation_time; int version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ if (version == 1) { creation_time = avio_rb64(pb); avio_rb64(pb); } else { creation_time = avio_rb32(pb); avio_rb32(pb); /* modification time */ } mov_metadata_creation_time(&c->fc->metadata, creation_time); c->time_scale = avio_rb32(pb); /* time scale */ if (c->time_scale <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale); c->time_scale = 1; } av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale); c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */ // set the AVCodecContext duration because the duration of individual tracks // may be inaccurate if (c->time_scale > 0 && !c->trex_data) c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale); avio_rb32(pb); /* preferred scale */ avio_rb16(pb); /* preferred volume */ avio_skip(pb, 10); /* reserved */ /* movie display matrix, store it in main context and use it later on */ for (i = 0; i < 3; i++) { c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point } avio_rb32(pb); /* preview time */ avio_rb32(pb); /* preview duration */ avio_rb32(pb); /* poster time */ avio_rb32(pb); /* selection time */ avio_rb32(pb); /* selection duration */ avio_rb32(pb); /* current time */ avio_rb32(pb); /* next track ID */ return 0; } static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int little_endian; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; little_endian = avio_rb16(pb) & 0xFF; av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian); if (little_endian == 1) { switch (st->codecpar->codec_id) { case AV_CODEC_ID_PCM_S24BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; break; case AV_CODEC_ID_PCM_S32BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; break; case AV_CODEC_ID_PCM_F32BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE; break; case AV_CODEC_ID_PCM_F64BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE; break; default: break; } } return 0; } static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; char color_parameter_type[5] = { 0 }; uint16_t color_primaries, color_trc, color_matrix; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; ret = ffio_read_size(pb, color_parameter_type, 4); if (ret < 0) return ret; if (strncmp(color_parameter_type, "nclx", 4) && strncmp(color_parameter_type, "nclc", 4)) { av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n", color_parameter_type); return 0; } color_primaries = avio_rb16(pb); color_trc = avio_rb16(pb); color_matrix = avio_rb16(pb); av_log(c->fc, AV_LOG_TRACE, "%s: pri %d trc %d matrix %d", color_parameter_type, color_primaries, color_trc, color_matrix); if (!strncmp(color_parameter_type, "nclx", 4)) { uint8_t color_range = avio_r8(pb) >> 7; av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range); if (color_range) st->codecpar->color_range = AVCOL_RANGE_JPEG; else st->codecpar->color_range = AVCOL_RANGE_MPEG; } if (!av_color_primaries_name(color_primaries)) color_primaries = AVCOL_PRI_UNSPECIFIED; if (!av_color_transfer_name(color_trc)) color_trc = AVCOL_TRC_UNSPECIFIED; if (!av_color_space_name(color_matrix)) color_matrix = AVCOL_SPC_UNSPECIFIED; st->codecpar->color_primaries = color_primaries; st->codecpar->color_trc = color_trc; st->codecpar->color_space = color_matrix; av_log(c->fc, AV_LOG_TRACE, "\n"); return 0; } static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; unsigned mov_field_order; enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN; if (c->fc->nb_streams < 1) // will happen with jp2 files return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size < 2) return AVERROR_INVALIDDATA; mov_field_order = avio_rb16(pb); if ((mov_field_order & 0xFF00) == 0x0100) decoded_field_order = AV_FIELD_PROGRESSIVE; else if ((mov_field_order & 0xFF00) == 0x0200) { switch (mov_field_order & 0xFF) { case 0x01: decoded_field_order = AV_FIELD_TT; break; case 0x06: decoded_field_order = AV_FIELD_BB; break; case 0x09: decoded_field_order = AV_FIELD_TB; break; case 0x0E: decoded_field_order = AV_FIELD_BT; break; } } if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) { av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order); } st->codecpar->field_order = decoded_field_order; return 0; } static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom) { int err = 0; uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE; if (size > INT_MAX || (uint64_t)atom.size > INT_MAX) return AVERROR_INVALIDDATA; if ((err = av_reallocp(&par->extradata, size)) < 0) { par->extradata_size = 0; return err; } par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE; return 0; } /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */ static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, AVCodecParameters *par, uint8_t *buf) { int64_t result = atom.size; int err; AV_WB32(buf , atom.size + 8); AV_WL32(buf + 4, atom.type); err = ffio_read_size(pb, buf + 8, atom.size); if (err < 0) { par->extradata_size -= atom.size; return err; } else if (err < atom.size) { av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n"); par->extradata_size -= atom.size - err; result = err; } memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE); return result; } /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */ static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, enum AVCodecID codec_id) { AVStream *st; uint64_t original_size; int err; if (c->fc->nb_streams < 1) // will happen with jp2 files return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (st->codecpar->codec_id != codec_id) return 0; /* unexpected codec_id - don't mess with extradata */ original_size = st->codecpar->extradata_size; err = mov_realloc_extradata(st->codecpar, atom); if (err) return err; err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size); if (err < 0) return err; return 0; // Note: this is the original behavior to ignore truncation. } /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */ static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC); } static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS); } static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000); } static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K); } static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI); if(ret == 0) ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD); return ret; } static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216); if (!ret && c->fc->nb_streams >= 1) { AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar; if (par->extradata_size >= 40) { par->height = AV_RB16(&par->extradata[36]); par->width = AV_RB16(&par->extradata[38]); } } return ret; } static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (c->fc->nb_streams >= 1) { AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar; if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') && par->codec_id == AV_CODEC_ID_H264 && atom.size > 11) { int cid; avio_skip(pb, 10); cid = avio_rb16(pb); /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */ if (cid == 0xd4d || cid == 0xd4e) par->width = 1440; return 0; } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') || par->codec_tag == MKTAG('A', 'V', 'd', 'n')) && atom.size >= 24) { int num, den; avio_skip(pb, 12); num = avio_rb32(pb); den = avio_rb32(pb); if (num <= 0 || den <= 0) return 0; switch (avio_rb32(pb)) { case 2: if (den >= INT_MAX / 2) return 0; den *= 2; case 1: c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num; c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den; default: return 0; } } } return mov_read_avid(c, pb, atom); } static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret = 0; int length = 0; uint64_t original_size; if (c->fc->nb_streams >= 1) { AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar; if (par->codec_id == AV_CODEC_ID_H264) return 0; if (atom.size == 16) { original_size = par->extradata_size; ret = mov_realloc_extradata(par, atom); if (!ret) { length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size); if (length == atom.size) { const uint8_t range_value = par->extradata[original_size + 19]; switch (range_value) { case 1: par->color_range = AVCOL_RANGE_MPEG; break; case 2: par->color_range = AVCOL_RANGE_JPEG; break; default: av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value); break; } ff_dlog(c, "color_range: %d\n", par->color_range); } else { /* For some reason the whole atom was not added to the extradata */ av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n"); } } else { av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n"); } } else { av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size); } } return ret; } static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3); } static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 || st->codecpar->codec_id == AV_CODEC_ID_QDMC || st->codecpar->codec_id == AV_CODEC_ID_SPEEX) { // pass all frma atom to codec, needed at least for QDMC and QDM2 av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size); if (ret < 0) return ret; } else if (atom.size > 8) { /* to read frma, esds atoms */ if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) { uint64_t buffer; ret = ffio_ensure_seekback(pb, 8); if (ret < 0) return ret; buffer = avio_rb64(pb); atom.size -= 8; if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a') && buffer >> 32 <= atom.size && buffer >> 32 >= 8) { avio_skip(pb, -8); atom.size += 8; } else if (!st->codecpar->extradata_size) { #define ALAC_EXTRADATA_SIZE 36 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE; AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE); AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c')); AV_WB64(st->codecpar->extradata + 12, buffer); avio_read(pb, st->codecpar->extradata + 20, 16); avio_skip(pb, atom.size - 24); return 0; } } if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; } else avio_skip(pb, atom.size); return 0; } /** * This function reads atom content and puts data in extradata without tag * nor size unlike mov_read_extradata. */ static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; if (atom.size >= 10) { // Broken files created by legacy versions of libavformat will // wrap a whole fiel atom inside of a glbl atom. unsigned size = avio_rb32(pb); unsigned type = avio_rl32(pb); avio_seek(pb, -8, SEEK_CUR); if (type == MKTAG('f','i','e','l') && size == atom.size) return mov_read_default(c, pb, atom); } if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) { av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n"); return 0; } av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size); if (ret < 0) return ret; return 0; } static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint8_t profile_level; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size >= (1<<28) || atom.size < 7) return AVERROR_INVALIDDATA; profile_level = avio_r8(pb); if ((profile_level & 0xf0) != 0xc0) return 0; avio_seek(pb, 6, SEEK_CUR); av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7); if (ret < 0) return ret; return 0; } /** * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself, * but can have extradata appended at the end after the 40 bytes belonging * to the struct. */ static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; if (atom.size <= 40) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; avio_skip(pb, 40); av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40); if (ret < 0) return ret; return 0; } static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); if (!entries) return 0; if (sc->chunk_offsets) av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n"); av_free(sc->chunk_offsets); sc->chunk_count = 0; sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets)); if (!sc->chunk_offsets) return AVERROR(ENOMEM); sc->chunk_count = entries; if (atom.type == MKTAG('s','t','c','o')) for (i = 0; i < entries && !pb->eof_reached; i++) sc->chunk_offsets[i] = avio_rb32(pb); else if (atom.type == MKTAG('c','o','6','4')) for (i = 0; i < entries && !pb->eof_reached; i++) sc->chunk_offsets[i] = avio_rb64(pb); else return AVERROR_INVALIDDATA; sc->chunk_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } /** * Compute codec id for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags) { /* lpcm flags: * 0x1 = float * 0x2 = big-endian * 0x4 = signed */ return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0); } static int mov_codec_id(AVStream *st, uint32_t format) { int id = ff_codec_get_id(ff_codec_movaudio_tags, format); if (id <= 0 && ((format & 0xFFFF) == 'm' + ('s' << 8) || (format & 0xFFFF) == 'T' + ('S' << 8))) id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF); if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) { st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && /* skip old ASF MPEG-4 tag */ format && format != MKTAG('m','p','4','s')) { id = ff_codec_get_id(ff_codec_movvideo_tags, format); if (id <= 0) id = ff_codec_get_id(ff_codec_bmp_tags, format); if (id > 0) st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE && st->codecpar->codec_id == AV_CODEC_ID_NONE)) { id = ff_codec_get_id(ff_codec_movsubtitle_tags, format); if (id > 0) st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; } } st->codecpar->codec_tag = format; return id; } static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc) { uint8_t codec_name[32] = { 0 }; int64_t stsd_start; unsigned int len; /* The first 16 bytes of the video sample description are already * read in ff_mov_read_stsd_entries() */ stsd_start = avio_tell(pb) - 16; avio_rb16(pb); /* version */ avio_rb16(pb); /* revision level */ avio_rb32(pb); /* vendor */ avio_rb32(pb); /* temporal quality */ avio_rb32(pb); /* spatial quality */ st->codecpar->width = avio_rb16(pb); /* width */ st->codecpar->height = avio_rb16(pb); /* height */ avio_rb32(pb); /* horiz resolution */ avio_rb32(pb); /* vert resolution */ avio_rb32(pb); /* data size, always 0 */ avio_rb16(pb); /* frames per samples */ len = avio_r8(pb); /* codec name, pascal string */ if (len > 31) len = 31; mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name)); if (len < 31) avio_skip(pb, 31 - len); if (codec_name[0]) av_dict_set(&st->metadata, "encoder", codec_name, 0); /* codec_tag YV12 triggers an UV swap in rawdec.c */ if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) { st->codecpar->codec_tag = MKTAG('I', '4', '2', '0'); st->codecpar->width &= ~1; st->codecpar->height &= ~1; } /* Flash Media Server uses tag H.263 with Sorenson Spark */ if (st->codecpar->codec_tag == MKTAG('H','2','6','3') && !memcmp(codec_name, "Sorenson H263", 13)) st->codecpar->codec_id = AV_CODEC_ID_FLV1; st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */ avio_seek(pb, stsd_start, SEEK_SET); if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) { st->codecpar->bits_per_coded_sample &= 0x1F; sc->has_palette = 1; } } static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc) { int bits_per_sample, flags; uint16_t version = avio_rb16(pb); AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE); avio_rb16(pb); /* revision level */ avio_rb32(pb); /* vendor */ st->codecpar->channels = avio_rb16(pb); /* channel count */ st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */ av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels); sc->audio_cid = avio_rb16(pb); avio_rb16(pb); /* packet size = 0 */ st->codecpar->sample_rate = ((avio_rb32(pb) >> 16)); // Read QT version 1 fields. In version 0 these do not exist. av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom); if (!c->isom || (compatible_brands && strstr(compatible_brands->value, "qt "))) { if (version == 1) { sc->samples_per_frame = avio_rb32(pb); avio_rb32(pb); /* bytes per packet */ sc->bytes_per_frame = avio_rb32(pb); avio_rb32(pb); /* bytes per sample */ } else if (version == 2) { avio_rb32(pb); /* sizeof struct only */ st->codecpar->sample_rate = av_int2double(avio_rb64(pb)); st->codecpar->channels = avio_rb32(pb); avio_rb32(pb); /* always 0x7F000000 */ st->codecpar->bits_per_coded_sample = avio_rb32(pb); flags = avio_rb32(pb); /* lpcm format specific flag */ sc->bytes_per_frame = avio_rb32(pb); sc->samples_per_frame = avio_rb32(pb); if (st->codecpar->codec_tag == MKTAG('l','p','c','m')) st->codecpar->codec_id = ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample, flags); } if (version == 0 || (version == 1 && sc->audio_cid != -2)) { /* can't correctly handle variable sized packet as audio unit */ switch (st->codecpar->codec_id) { case AV_CODEC_ID_MP2: case AV_CODEC_ID_MP3: st->need_parsing = AVSTREAM_PARSE_FULL; break; } } } if (sc->format == 0) { if (st->codecpar->bits_per_coded_sample == 8) st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' ')); else if (st->codecpar->bits_per_coded_sample == 16) st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s')); } switch (st->codecpar->codec_id) { case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_U8: if (st->codecpar->bits_per_coded_sample == 16) st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; break; case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S16BE: if (st->codecpar->bits_per_coded_sample == 8) st->codecpar->codec_id = AV_CODEC_ID_PCM_S8; else if (st->codecpar->bits_per_coded_sample == 24) st->codecpar->codec_id = st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE; else if (st->codecpar->bits_per_coded_sample == 32) st->codecpar->codec_id = st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE; break; /* set values for old format before stsd version 1 appeared */ case AV_CODEC_ID_MACE3: sc->samples_per_frame = 6; sc->bytes_per_frame = 2 * st->codecpar->channels; break; case AV_CODEC_ID_MACE6: sc->samples_per_frame = 6; sc->bytes_per_frame = 1 * st->codecpar->channels; break; case AV_CODEC_ID_ADPCM_IMA_QT: sc->samples_per_frame = 64; sc->bytes_per_frame = 34 * st->codecpar->channels; break; case AV_CODEC_ID_GSM: sc->samples_per_frame = 160; sc->bytes_per_frame = 33; break; default: break; } bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id); if (bits_per_sample) { st->codecpar->bits_per_coded_sample = bits_per_sample; sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels; } } static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size) { // ttxt stsd contains display flags, justification, background // color, fonts, and default styles, so fake an atom to read it MOVAtom fake_atom = { .size = size }; // mp4s contains a regular esds atom if (st->codecpar->codec_tag != AV_RL32("mp4s")) mov_read_glbl(c, pb, fake_atom); st->codecpar->width = sc->width; st->codecpar->height = sc->height; } static uint32_t yuv_to_rgba(uint32_t ycbcr) { uint8_t r, g, b; int y, cb, cr; y = (ycbcr >> 16) & 0xFF; cr = (ycbcr >> 8) & 0xFF; cb = ycbcr & 0xFF; b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000); g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000); r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000); return (r << 16) | (g << 8) | b; } static int mov_rewrite_dvd_sub_extradata(AVStream *st) { char buf[256] = {0}; uint8_t *src = st->codecpar->extradata; int i; if (st->codecpar->extradata_size != 64) return 0; if (st->codecpar->width > 0 && st->codecpar->height > 0) snprintf(buf, sizeof(buf), "size: %dx%d\n", st->codecpar->width, st->codecpar->height); av_strlcat(buf, "palette: ", sizeof(buf)); for (i = 0; i < 16; i++) { uint32_t yuv = AV_RB32(src + i * 4); uint32_t rgba = yuv_to_rgba(yuv); av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : ""); } if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf)) return 0; av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = 0; st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); st->codecpar->extradata_size = strlen(buf); memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size); return 0; } static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size) { int ret; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { if ((int)size != size) return AVERROR(ENOMEM); ret = ff_get_extradata(c->fc, st->codecpar, pb, size); if (ret < 0) return ret; if (size > 16) { MOVStreamContext *tmcd_ctx = st->priv_data; int val; val = AV_RB32(st->codecpar->extradata + 4); tmcd_ctx->tmcd_flags = val; st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */ st->avg_frame_rate.den = 1; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->time_base = av_inv_q(st->avg_frame_rate); FF_ENABLE_DEPRECATION_WARNINGS #endif /* adjust for per frame dur in counter mode */ if (tmcd_ctx->tmcd_flags & 0x0008) { int timescale = AV_RB32(st->codecpar->extradata + 8); int framedur = AV_RB32(st->codecpar->extradata + 12); st->avg_frame_rate.num *= timescale; st->avg_frame_rate.den *= framedur; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->time_base.den *= timescale; st->codec->time_base.num *= framedur; FF_ENABLE_DEPRECATION_WARNINGS #endif } if (size > 30) { uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */ uint32_t format = AV_RB32(st->codecpar->extradata + 22); if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) { uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */ if (str_size > 0 && size >= (int)str_size + 26) { char *reel_name = av_malloc(str_size + 1); if (!reel_name) return AVERROR(ENOMEM); memcpy(reel_name, st->codecpar->extradata + 30, str_size); reel_name[str_size] = 0; /* Add null terminator */ /* don't add reel_name if emtpy string */ if (*reel_name == 0) { av_free(reel_name); } else { av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL); } } } } } } else { /* other codec type, just skip (rtp, mp4s ...) */ avio_skip(pb, size); } return 0; } static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc) { if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && !st->codecpar->sample_rate && sc->time_scale > 1) st->codecpar->sample_rate = sc->time_scale; /* special codec parameters handling */ switch (st->codecpar->codec_id) { #if CONFIG_DV_DEMUXER case AV_CODEC_ID_DVAUDIO: c->dv_fctx = avformat_alloc_context(); if (!c->dv_fctx) { av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n"); return AVERROR(ENOMEM); } c->dv_demux = avpriv_dv_init_demux(c->dv_fctx); if (!c->dv_demux) { av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n"); return AVERROR(ENOMEM); } sc->dv_audio_container = 1; st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE; break; #endif /* no ifdef since parameters are always those */ case AV_CODEC_ID_QCELP: st->codecpar->channels = 1; // force sample rate for qcelp when not stored in mov if (st->codecpar->codec_tag != MKTAG('Q','c','l','p')) st->codecpar->sample_rate = 8000; // FIXME: Why is the following needed for some files? sc->samples_per_frame = 160; if (!sc->bytes_per_frame) sc->bytes_per_frame = 35; break; case AV_CODEC_ID_AMR_NB: st->codecpar->channels = 1; /* force sample rate for amr, stsd in 3gp does not store sample rate */ st->codecpar->sample_rate = 8000; break; case AV_CODEC_ID_AMR_WB: st->codecpar->channels = 1; st->codecpar->sample_rate = 16000; break; case AV_CODEC_ID_MP2: case AV_CODEC_ID_MP3: /* force type after stsd for m1a hdlr */ st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; break; case AV_CODEC_ID_GSM: case AV_CODEC_ID_ADPCM_MS: case AV_CODEC_ID_ADPCM_IMA_WAV: case AV_CODEC_ID_ILBC: case AV_CODEC_ID_MACE3: case AV_CODEC_ID_MACE6: case AV_CODEC_ID_QDM2: st->codecpar->block_align = sc->bytes_per_frame; break; case AV_CODEC_ID_ALAC: if (st->codecpar->extradata_size == 36) { st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21); st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32); } break; case AV_CODEC_ID_AC3: case AV_CODEC_ID_EAC3: case AV_CODEC_ID_MPEG1VIDEO: case AV_CODEC_ID_VC1: case AV_CODEC_ID_VP9: st->need_parsing = AVSTREAM_PARSE_FULL; break; default: break; } return 0; } static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb, int codec_tag, int format, int64_t size) { int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format); if (codec_tag && (codec_tag != format && // AVID 1:1 samples with differing data format and codec tag exist (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) && // prores is allowed to have differing data format and codec tag codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") && // so is dv (sigh) codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") && (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id : codec_tag != MKTAG('j','p','e','g')))) { /* Multiple fourcc, we skip JPEG. This is not correct, we should * export it as a separate AVStream but this needs a few changes * in the MOV demuxer, patch welcome. */ av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n"); avio_skip(pb, size); return 1; } return 0; } int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries) { AVStream *st; MOVStreamContext *sc; int pseudo_stream_id; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; for (pseudo_stream_id = 0; pseudo_stream_id < entries && !pb->eof_reached; pseudo_stream_id++) { //Parsing Sample description table enum AVCodecID id; int ret, dref_id = 1; MOVAtom a = { AV_RL32("stsd") }; int64_t start_pos = avio_tell(pb); int64_t size = avio_rb32(pb); /* size */ uint32_t format = avio_rl32(pb); /* data format */ if (size >= 16) { avio_rb32(pb); /* reserved */ avio_rb16(pb); /* reserved */ dref_id = avio_rb16(pb); } else if (size <= 7) { av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size); return AVERROR_INVALIDDATA; } if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format, size - (avio_tell(pb) - start_pos))) continue; sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id; sc->dref_id= dref_id; sc->format = format; id = mov_codec_id(st, format); av_log(c->fc, AV_LOG_TRACE, "size=%"PRId64" 4CC=%s codec_type=%d\n", size, av_fourcc2str(format), st->codecpar->codec_type); if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) { st->codecpar->codec_id = id; mov_parse_stsd_video(c, pb, st, sc); } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) { st->codecpar->codec_id = id; mov_parse_stsd_audio(c, pb, st, sc); if (st->codecpar->sample_rate < 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate); return AVERROR_INVALIDDATA; } } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){ st->codecpar->codec_id = id; mov_parse_stsd_subtitle(c, pb, st, sc, size - (avio_tell(pb) - start_pos)); } else { ret = mov_parse_stsd_data(c, pb, st, sc, size - (avio_tell(pb) - start_pos)); if (ret < 0) return ret; } /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */ a.size = size - (avio_tell(pb) - start_pos); if (a.size > 8) { if ((ret = mov_read_default(c, pb, a)) < 0) return ret; } else if (a.size > 0) avio_skip(pb, a.size); if (sc->extradata && st->codecpar->extradata) { int extra_size = st->codecpar->extradata_size; /* Move the current stream extradata to the stream context one. */ sc->extradata_size[pseudo_stream_id] = extra_size; sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!sc->extradata[pseudo_stream_id]) return AVERROR(ENOMEM); memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size); av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = 0; } } if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int ret, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); if (entries <= 0) { av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries); return AVERROR_INVALIDDATA; } if (sc->extradata) { av_log(c->fc, AV_LOG_ERROR, "Duplicate STSD\n"); return AVERROR_INVALIDDATA; } /* Prepare space for hosting multiple extradata. */ sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata)); sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size)); if (!sc->extradata_size || !sc->extradata) { ret = AVERROR(ENOMEM); goto fail; } ret = ff_mov_read_stsd_entries(c, pb, entries); if (ret < 0) return ret; sc->stsd_count = entries; /* Restore back the primary extradata. */ av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = sc->extradata_size[0]; if (sc->extradata_size[0]) { st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]); } return mov_finalize_stsd_codec(c, pb, st, sc); fail: av_freep(&sc->extradata); av_freep(&sc->extradata_size); return ret; } static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries); if (!entries) return 0; if (sc->stsc_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n"); av_free(sc->stsc_data); sc->stsc_count = 0; sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data)); if (!sc->stsc_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->stsc_data[i].first = avio_rb32(pb); sc->stsc_data[i].count = avio_rb32(pb); sc->stsc_data[i].id = avio_rb32(pb); } sc->stsc_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } #define mov_stsc_index_valid(index, count) ((index) < (count) - 1) /* Compute the samples value for the stsc entry at the given index. */ static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index) { int chunk_count; if (mov_stsc_index_valid(index, sc->stsc_count)) chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first; else chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1); return sc->stsc_data[index].count * chunk_count; } static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (sc->stps_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n"); av_free(sc->stps_data); sc->stps_count = 0; sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data)); if (!sc->stps_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->stps_data[i] = avio_rb32(pb); } sc->stps_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries); if (!entries) { sc->keyframe_absent = 1; if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) st->need_parsing = AVSTREAM_PARSE_HEADERS; return 0; } if (sc->keyframes) av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n"); if (entries >= UINT_MAX / sizeof(int)) return AVERROR_INVALIDDATA; av_freep(&sc->keyframes); sc->keyframe_count = 0; sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes)); if (!sc->keyframes) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->keyframes[i] = avio_rb32(pb); } sc->keyframe_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries, sample_size, field_size, num_bytes; GetBitContext gb; unsigned char* buf; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ if (atom.type == MKTAG('s','t','s','z')) { sample_size = avio_rb32(pb); if (!sc->sample_size) /* do not overwrite value computed in stsd */ sc->sample_size = sample_size; sc->stsz_sample_size = sample_size; field_size = 32; } else { sample_size = 0; avio_rb24(pb); /* reserved */ field_size = avio_r8(pb); } entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries); sc->sample_count = entries; if (sample_size) return 0; if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size); return AVERROR_INVALIDDATA; } if (!entries) return 0; if (entries >= (UINT_MAX - 4) / field_size) return AVERROR_INVALIDDATA; if (sc->sample_sizes) av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n"); av_free(sc->sample_sizes); sc->sample_count = 0; sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes)); if (!sc->sample_sizes) return AVERROR(ENOMEM); num_bytes = (entries*field_size+4)>>3; buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE); if (!buf) { av_freep(&sc->sample_sizes); return AVERROR(ENOMEM); } ret = ffio_read_size(pb, buf, num_bytes); if (ret < 0) { av_freep(&sc->sample_sizes); av_free(buf); return ret; } init_get_bits(&gb, buf, 8*num_bytes); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->sample_sizes[i] = get_bits_long(&gb, field_size); sc->data_size += sc->sample_sizes[i]; } sc->sample_count = i; av_free(buf); if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; int64_t duration=0; int64_t total_sample_count=0; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n", c->fc->nb_streams-1, entries); if (sc->stts_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n"); av_free(sc->stts_data); sc->stts_count = 0; sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data)); if (!sc->stts_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { int sample_duration; int sample_count; sample_count=avio_rb32(pb); sample_duration = avio_rb32(pb); if (sample_count < 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count); return AVERROR_INVALIDDATA; } sc->stts_data[i].count= sample_count; sc->stts_data[i].duration= sample_duration; av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n", sample_count, sample_duration); if ( i+1 == entries && i && sample_count == 1 && total_sample_count > 100 && sample_duration/10 > duration / total_sample_count) sample_duration = duration / total_sample_count; duration+=(int64_t)sample_duration*sample_count; total_sample_count+=sample_count; } sc->stts_count = i; sc->duration_for_fps += duration; sc->nb_frames_for_fps += total_sample_count; if (pb->eof_reached) return AVERROR_EOF; st->nb_frames= total_sample_count; if (duration) st->duration= duration; sc->track_end = duration; return 0; } static void mov_update_dts_shift(MOVStreamContext *sc, int duration) { if (duration < 0) { if (duration == INT_MIN) { av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX); duration++; } sc->dts_shift = FFMAX(sc->dts_shift, -duration); } } static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, j, entries, ctts_count = 0; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries); if (!entries) return 0; if (entries >= UINT_MAX / sizeof(*sc->ctts_data)) return AVERROR_INVALIDDATA; av_freep(&sc->ctts_data); sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data)); if (!sc->ctts_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { int count =avio_rb32(pb); int duration =avio_rb32(pb); if (count <= 0) { av_log(c->fc, AV_LOG_TRACE, "ignoring CTTS entry with count=%d duration=%d\n", count, duration); continue; } /* Expand entries such that we have a 1-1 mapping with samples. */ for (j = 0; j < count; j++) add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size, 1, duration); av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n", count, duration); if (FFNABS(duration) < -(1<<28) && i+2<entries) { av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n"); av_freep(&sc->ctts_data); sc->ctts_count = 0; return 0; } if (i+2<entries) mov_update_dts_shift(sc, duration); } sc->ctts_count = ctts_count; if (pb->eof_reached) return AVERROR_EOF; av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift); return 0; } static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; uint8_t version; uint32_t grouping_type; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ grouping_type = avio_rl32(pb); if (grouping_type != MKTAG( 'r','a','p',' ')) return 0; /* only support 'rap ' grouping */ if (version == 1) avio_rb32(pb); /* grouping_type_parameter */ entries = avio_rb32(pb); if (!entries) return 0; if (sc->rap_group) av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n"); av_free(sc->rap_group); sc->rap_group_count = 0; sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group)); if (!sc->rap_group) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->rap_group[i].count = avio_rb32(pb); /* sample_count */ sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */ } sc->rap_group_count = i; return pb->eof_reached ? AVERROR_EOF : 0; } /** * Get ith edit list entry (media time, duration). */ static int get_edit_list_entry(MOVContext *mov, const MOVStreamContext *msc, unsigned int edit_list_index, int64_t *edit_list_media_time, int64_t *edit_list_duration, int64_t global_timescale) { if (edit_list_index == msc->elst_count) { return 0; } *edit_list_media_time = msc->elst_data[edit_list_index].time; *edit_list_duration = msc->elst_data[edit_list_index].duration; /* duration is in global timescale units;convert to msc timescale */ if (global_timescale == 0) { avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists"); return 0; } *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale, global_timescale); return 1; } /** * Find the closest previous frame to the timestamp, in e_old index * entries. Searching for just any frame / just key frames can be controlled by * last argument 'flag'. * Returns the index of the entry in st->index_entries if successful, * else returns -1. */ static int64_t find_prev_closest_index(AVStream *st, AVIndexEntry *e_old, int nb_old, int64_t timestamp, int flag) { AVIndexEntry *e_keep = st->index_entries; int nb_keep = st->nb_index_entries; int64_t found = -1; int64_t i = 0; st->index_entries = e_old; st->nb_index_entries = nb_old; found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD); // Keep going backwards in the index entries until the timestamp is the same. if (found >= 0) { for (i = found; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp; i--) { if ((flag & AVSEEK_FLAG_ANY) || (e_old[i - 1].flags & AVINDEX_KEYFRAME)) { found = i - 1; } } } /* restore AVStream state*/ st->index_entries = e_keep; st->nb_index_entries = nb_keep; return found; } /** * Add index entry with the given values, to the end of st->index_entries. * Returns the new size st->index_entries if successful, else returns -1. * * This function is similar to ff_add_index_entry in libavformat/utils.c * except that here we are always unconditionally adding an index entry to * the end, instead of searching the entries list and skipping the add if * there is an existing entry with the same timestamp. * This is needed because the mov_fix_index calls this func with the same * unincremented timestamp for successive discarded frames. */ static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags) { AVIndexEntry *entries, *ie; int64_t index = -1; const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry); // Double the allocation each time, to lower memory fragmentation. // Another difference from ff_add_index_entry function. const size_t requested_size = min_size_needed > st->index_entries_allocated_size ? FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) : min_size_needed; if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry)) return -1; entries = av_fast_realloc(st->index_entries, &st->index_entries_allocated_size, requested_size); if(!entries) return -1; st->index_entries= entries; index= st->nb_index_entries++; ie= &entries[index]; ie->pos = pos; ie->timestamp = timestamp; ie->min_distance= distance; ie->size= size; ie->flags = flags; return index; } /** * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index) * by subtracting end_ts successively by the amounts given in frame_duration_buffer. */ static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts, int64_t* frame_duration_buffer, int frame_duration_buffer_size) { int i = 0; av_assert0(end_index >= 0 && end_index <= st->nb_index_entries); for (i = 0; i < frame_duration_buffer_size; i++) { end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i]; st->index_entries[end_index - 1 - i].timestamp = end_ts; } } /** * Append a new ctts entry to ctts_data. * Returns the new ctts_count if successful, else returns -1. */ static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size, int count, int duration) { MOVStts *ctts_buf_new; const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts); const size_t requested_size = min_size_needed > *allocated_size ? FFMAX(min_size_needed, 2 * (*allocated_size)) : min_size_needed; if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts)) return -1; ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size); if(!ctts_buf_new) return -1; *ctts_data = ctts_buf_new; ctts_buf_new[*ctts_count].count = count; ctts_buf_new[*ctts_count].duration = duration; *ctts_count = (*ctts_count) + 1; return *ctts_count; } static void mov_current_sample_inc(MOVStreamContext *sc) { sc->current_sample++; sc->current_index++; if (sc->index_ranges && sc->current_index >= sc->current_index_range->end && sc->current_index_range->end) { sc->current_index_range++; sc->current_index = sc->current_index_range->start; } } static void mov_current_sample_dec(MOVStreamContext *sc) { sc->current_sample--; sc->current_index--; if (sc->index_ranges && sc->current_index < sc->current_index_range->start && sc->current_index_range > sc->index_ranges) { sc->current_index_range--; sc->current_index = sc->current_index_range->end - 1; } } static void mov_current_sample_set(MOVStreamContext *sc, int current_sample) { int64_t range_size; sc->current_sample = current_sample; sc->current_index = current_sample; if (!sc->index_ranges) { return; } for (sc->current_index_range = sc->index_ranges; sc->current_index_range->end; sc->current_index_range++) { range_size = sc->current_index_range->end - sc->current_index_range->start; if (range_size > current_sample) { sc->current_index = sc->current_index_range->start + current_sample; break; } current_sample -= range_size; } } /** * Fix st->index_entries, so that it contains only the entries (and the entries * which are needed to decode them) that fall in the edit list time ranges. * Also fixes the timestamps of the index entries to match the timeline * specified the edit lists. */ static void mov_fix_index(MOVContext *mov, AVStream *st) { MOVStreamContext *msc = st->priv_data; AVIndexEntry *e_old = st->index_entries; int nb_old = st->nb_index_entries; const AVIndexEntry *e_old_end = e_old + nb_old; const AVIndexEntry *current = NULL; MOVStts *ctts_data_old = msc->ctts_data; int64_t ctts_index_old = 0; int64_t ctts_sample_old = 0; int64_t ctts_count_old = msc->ctts_count; int64_t edit_list_media_time = 0; int64_t edit_list_duration = 0; int64_t frame_duration = 0; int64_t edit_list_dts_counter = 0; int64_t edit_list_dts_entry_end = 0; int64_t edit_list_start_ctts_sample = 0; int64_t curr_cts; int64_t curr_ctts = 0; int64_t min_corrected_pts = -1; int64_t empty_edits_sum_duration = 0; int64_t edit_list_index = 0; int64_t index; int64_t index_ctts_count; int flags; int64_t start_dts = 0; int64_t edit_list_media_time_dts = 0; int64_t edit_list_start_encountered = 0; int64_t search_timestamp = 0; int64_t* frame_duration_buffer = NULL; int num_discarded_begin = 0; int first_non_zero_audio_edit = -1; int packet_skip_samples = 0; MOVIndexRange *current_index_range; int i; if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) { return; } // allocate the index ranges array msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0])); if (!msc->index_ranges) { av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n"); return; } msc->current_index_range = msc->index_ranges; current_index_range = msc->index_ranges - 1; // Clean AVStream from traces of old index st->index_entries = NULL; st->index_entries_allocated_size = 0; st->nb_index_entries = 0; // Clean ctts fields of MOVStreamContext msc->ctts_data = NULL; msc->ctts_count = 0; msc->ctts_index = 0; msc->ctts_sample = 0; msc->ctts_allocated_size = 0; // If the dts_shift is positive (in case of negative ctts values in mov), // then negate the DTS by dts_shift if (msc->dts_shift > 0) { edit_list_dts_entry_end -= msc->dts_shift; av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift); } start_dts = edit_list_dts_entry_end; while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time, &edit_list_duration, mov->time_scale)) { av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n", st->index, edit_list_index, edit_list_media_time, edit_list_duration); edit_list_index++; edit_list_dts_counter = edit_list_dts_entry_end; edit_list_dts_entry_end += edit_list_duration; num_discarded_begin = 0; if (edit_list_media_time == -1) { empty_edits_sum_duration += edit_list_duration; continue; } // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them // according to the edit list below. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if (first_non_zero_audio_edit < 0) { first_non_zero_audio_edit = 1; } else { first_non_zero_audio_edit = 0; } if (first_non_zero_audio_edit > 0) st->skip_samples = msc->start_pad = 0; } //find closest previous key frame edit_list_media_time_dts = edit_list_media_time; if (msc->dts_shift > 0) { edit_list_media_time_dts -= msc->dts_shift; } // While reordering frame index according to edit list we must handle properly // the scenario when edit list entry starts from none key frame. // We find closest previous key frame and preserve it and consequent frames in index. // All frames which are outside edit list entry time boundaries will be dropped after decoding. search_timestamp = edit_list_media_time_dts; if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { // Audio decoders like AAC need need a decoder delay samples previous to the current sample, // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the // edit_list_media_time to cover the decoder delay. search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp); } index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0); if (index == -1) { av_log(mov->fc, AV_LOG_WARNING, "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n", st->index, edit_list_index, search_timestamp); index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY); if (index == -1) { av_log(mov->fc, AV_LOG_WARNING, "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n" "Rounding edit list media time to zero.\n", st->index, edit_list_index, search_timestamp); index = 0; edit_list_media_time = 0; } } current = e_old + index; ctts_index_old = 0; ctts_sample_old = 0; // set ctts_index properly for the found key frame for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) { if (ctts_data_old && ctts_index_old < ctts_count_old) { ctts_sample_old++; if (ctts_data_old[ctts_index_old].count == ctts_sample_old) { ctts_index_old++; ctts_sample_old = 0; } } } edit_list_start_ctts_sample = ctts_sample_old; // Iterate over index and arrange it according to edit list edit_list_start_encountered = 0; for (; current < e_old_end; current++, index++) { // check if frame outside edit list mark it for discard frame_duration = (current + 1 < e_old_end) ? ((current + 1)->timestamp - current->timestamp) : edit_list_duration; flags = current->flags; // frames (pts) before or after edit list curr_cts = current->timestamp + msc->dts_shift; curr_ctts = 0; if (ctts_data_old && ctts_index_old < ctts_count_old) { curr_ctts = ctts_data_old[ctts_index_old].duration; av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n", curr_cts, curr_ctts, ctts_index_old, ctts_count_old); curr_cts += curr_ctts; ctts_sample_old++; if (ctts_sample_old == ctts_data_old[ctts_index_old].count) { if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count, &msc->ctts_allocated_size, ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration) == -1) { av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n", ctts_index_old, ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration); break; } ctts_index_old++; ctts_sample_old = 0; edit_list_start_ctts_sample = 0; } } if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) { if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS && curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time && first_non_zero_audio_edit > 0) { packet_skip_samples = edit_list_media_time - curr_cts; st->skip_samples += packet_skip_samples; // Shift the index entry timestamp by packet_skip_samples to be correct. edit_list_dts_counter -= packet_skip_samples; if (edit_list_start_encountered == 0) { edit_list_start_encountered = 1; // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for // discarded packets. if (frame_duration_buffer) { fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter, frame_duration_buffer, num_discarded_begin); av_freep(&frame_duration_buffer); } } av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts); } else { flags |= AVINDEX_DISCARD_FRAME; av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index); if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) { num_discarded_begin++; frame_duration_buffer = av_realloc(frame_duration_buffer, num_discarded_begin * sizeof(int64_t)); if (!frame_duration_buffer) { av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n"); break; } frame_duration_buffer[num_discarded_begin - 1] = frame_duration; // Increment skip_samples for the first non-zero audio edit list if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) { st->skip_samples += frame_duration; msc->start_pad = st->skip_samples; } } } } else { if (min_corrected_pts < 0) { min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift; } else { min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift); } if (edit_list_start_encountered == 0) { edit_list_start_encountered = 1; // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for // discarded packets. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) { fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter, frame_duration_buffer, num_discarded_begin); av_freep(&frame_duration_buffer); } } } if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size, current->min_distance, flags) == -1) { av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n"); break; } // Update the index ranges array if (current_index_range < msc->index_ranges || index != current_index_range->end) { current_index_range++; current_index_range->start = index; } current_index_range->end = index + 1; // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list. if (edit_list_start_encountered > 0) { edit_list_dts_counter = edit_list_dts_counter + frame_duration; } // Break when found first key frame after edit entry completion if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) && ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) { if (ctts_data_old && ctts_sample_old != 0) { if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count, &msc->ctts_allocated_size, ctts_sample_old - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration) == -1) { av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n", ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration); break; } } break; } } } // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the // sum duration of emtpy edits here. min_corrected_pts -= empty_edits_sum_duration; // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the // dts by that amount to make the first pts zero. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) { av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts); for (i = 0; i < st->nb_index_entries; ++i) { st->index_entries[i].timestamp -= min_corrected_pts; } } // Update av stream length st->duration = edit_list_dts_entry_end - start_dts; // Free the old index and the old CTTS structures av_free(e_old); av_free(ctts_data_old); // Null terminate the index ranges array current_index_range++; current_index_range->start = 0; current_index_range->end = 0; msc->current_index = msc->index_ranges[0].start; } static void mov_build_index(MOVContext *mov, AVStream *st) { MOVStreamContext *sc = st->priv_data; int64_t current_offset; int64_t current_dts = 0; unsigned int stts_index = 0; unsigned int stsc_index = 0; unsigned int stss_index = 0; unsigned int stps_index = 0; unsigned int i, j; uint64_t stream_size = 0; if (sc->elst_count) { int i, edit_start_index = 0, multiple_edits = 0; int64_t empty_duration = 0; // empty duration of the first edit list entry int64_t start_time = 0; // start time of the media for (i = 0; i < sc->elst_count; i++) { const MOVElst *e = &sc->elst_data[i]; if (i == 0 && e->time == -1) { /* if empty, the first entry is the start time of the stream * relative to the presentation itself */ empty_duration = e->duration; edit_start_index = 1; } else if (i == edit_start_index && e->time >= 0) { start_time = e->time; } else { multiple_edits = 1; } } if (multiple_edits && !mov->advanced_editlist) av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, " "Use -advanced_editlist to correctly decode otherwise " "a/v desync might occur\n"); /* adjust first dts according to edit list */ if ((empty_duration || start_time) && mov->time_scale > 0) { if (empty_duration) empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale); sc->time_offset = start_time - empty_duration; if (!mov->advanced_editlist) current_dts = -sc->time_offset; } if (!multiple_edits && !mov->advanced_editlist && st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0) sc->start_pad = start_time; } /* only use old uncompressed audio chunk demuxing when stts specifies it */ if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && sc->stts_count == 1 && sc->stts_data[0].duration == 1)) { unsigned int current_sample = 0; unsigned int stts_sample = 0; unsigned int sample_size; unsigned int distance = 0; unsigned int rap_group_index = 0; unsigned int rap_group_sample = 0; int64_t last_dts = 0; int64_t dts_correction = 0; int rap_group_present = sc->rap_group_count && sc->rap_group; int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0); current_dts -= sc->dts_shift; last_dts = current_dts; if (!sc->sample_count || st->nb_index_entries) return; if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries) return; if (av_reallocp_array(&st->index_entries, st->nb_index_entries + sc->sample_count, sizeof(*st->index_entries)) < 0) { st->nb_index_entries = 0; return; } st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries); for (i = 0; i < sc->chunk_count; i++) { int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX; current_offset = sc->chunk_offsets[i]; while (mov_stsc_index_valid(stsc_index, sc->stsc_count) && i + 1 == sc->stsc_data[stsc_index + 1].first) stsc_index++; if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size && sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) { av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size); sc->stsz_sample_size = sc->sample_size; } if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) { av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size); sc->stsz_sample_size = sc->sample_size; } for (j = 0; j < sc->stsc_data[stsc_index].count; j++) { int keyframe = 0; if (current_sample >= sc->sample_count) { av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n"); return; } if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) { keyframe = 1; if (stss_index + 1 < sc->keyframe_count) stss_index++; } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) { keyframe = 1; if (stps_index + 1 < sc->stps_count) stps_index++; } if (rap_group_present && rap_group_index < sc->rap_group_count) { if (sc->rap_group[rap_group_index].index > 0) keyframe = 1; if (++rap_group_sample == sc->rap_group[rap_group_index].count) { rap_group_sample = 0; rap_group_index++; } } if (sc->keyframe_absent && !sc->stps_count && !rap_group_present && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0))) keyframe = 1; if (keyframe) distance = 0; sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample]; if (sc->pseudo_stream_id == -1 || sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) { AVIndexEntry *e; if (sample_size > 0x3FFFFFFF) { av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size); return; } e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; e->size = sample_size; e->min_distance = distance; e->flags = keyframe ? AVINDEX_KEYFRAME : 0; av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", " "size %u, distance %u, keyframe %d\n", st->index, current_sample, current_offset, current_dts, sample_size, distance, keyframe); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100) ff_rfps_add_frame(mov->fc, st, current_dts); } current_offset += sample_size; stream_size += sample_size; /* A negative sample duration is invalid based on the spec, * but some samples need it to correct the DTS. */ if (sc->stts_data[stts_index].duration < 0) { av_log(mov->fc, AV_LOG_WARNING, "Invalid SampleDelta %d in STTS, at %d st:%d\n", sc->stts_data[stts_index].duration, stts_index, st->index); dts_correction += sc->stts_data[stts_index].duration - 1; sc->stts_data[stts_index].duration = 1; } current_dts += sc->stts_data[stts_index].duration; if (!dts_correction || current_dts + dts_correction > last_dts) { current_dts += dts_correction; dts_correction = 0; } else { /* Avoid creating non-monotonous DTS */ dts_correction += current_dts - last_dts - 1; current_dts = last_dts + 1; } last_dts = current_dts; distance++; stts_sample++; current_sample++; if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) { stts_sample = 0; stts_index++; } } } if (st->duration > 0) st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration; } else { unsigned chunk_samples, total = 0; // compute total chunk count for (i = 0; i < sc->stsc_count; i++) { unsigned count, chunk_count; chunk_samples = sc->stsc_data[i].count; if (i != sc->stsc_count - 1 && sc->samples_per_frame && chunk_samples % sc->samples_per_frame) { av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n"); return; } if (sc->samples_per_frame >= 160) { // gsm count = chunk_samples / sc->samples_per_frame; } else if (sc->samples_per_frame > 1) { unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame; count = (chunk_samples+samples-1) / samples; } else { count = (chunk_samples+1023) / 1024; } if (mov_stsc_index_valid(i, sc->stsc_count)) chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first; else chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1); total += chunk_count * count; } av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total); if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries) return; if (av_reallocp_array(&st->index_entries, st->nb_index_entries + total, sizeof(*st->index_entries)) < 0) { st->nb_index_entries = 0; return; } st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries); // populate index for (i = 0; i < sc->chunk_count; i++) { current_offset = sc->chunk_offsets[i]; if (mov_stsc_index_valid(stsc_index, sc->stsc_count) && i + 1 == sc->stsc_data[stsc_index + 1].first) stsc_index++; chunk_samples = sc->stsc_data[stsc_index].count; while (chunk_samples > 0) { AVIndexEntry *e; unsigned size, samples; if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) { avpriv_request_sample(mov->fc, "Zero bytes per frame, but %d samples per frame", sc->samples_per_frame); return; } if (sc->samples_per_frame >= 160) { // gsm samples = sc->samples_per_frame; size = sc->bytes_per_frame; } else { if (sc->samples_per_frame > 1) { samples = FFMIN((1024 / sc->samples_per_frame)* sc->samples_per_frame, chunk_samples); size = (samples / sc->samples_per_frame) * sc->bytes_per_frame; } else { samples = FFMIN(1024, chunk_samples); size = samples * sc->sample_size; } } if (st->nb_index_entries >= total) { av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total); return; } if (size > 0x3FFFFFFF) { av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size); return; } e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; e->size = size; e->min_distance = 0; e->flags = AVINDEX_KEYFRAME; av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", " "size %u, duration %u\n", st->index, i, current_offset, current_dts, size, samples); current_offset += size; current_dts += samples; chunk_samples -= samples; } } } if (!mov->ignore_editlist && mov->advanced_editlist) { // Fix index according to edit lists. mov_fix_index(mov, st); } } static int test_same_origin(const char *src, const char *ref) { char src_proto[64]; char ref_proto[64]; char src_auth[256]; char ref_auth[256]; char src_host[256]; char ref_host[256]; int src_port=-1; int ref_port=-1; av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src); av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref); if (strlen(src) == 0) { return -1; } else if (strlen(src_auth) + 1 >= sizeof(src_auth) || strlen(ref_auth) + 1 >= sizeof(ref_auth) || strlen(src_host) + 1 >= sizeof(src_host) || strlen(ref_host) + 1 >= sizeof(ref_host)) { return 0; } else if (strcmp(src_proto, ref_proto) || strcmp(src_auth, ref_auth) || strcmp(src_host, ref_host) || src_port != ref_port) { return 0; } else return 1; } static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref) { /* try relative path, we do not try the absolute because it can leak information about our system to an attacker */ if (ref->nlvl_to > 0 && ref->nlvl_from > 0) { char filename[1025]; const char *src_path; int i, l; /* find a source dir */ src_path = strrchr(src, '/'); if (src_path) src_path++; else src_path = src; /* find a next level down to target */ for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--) if (ref->path[l] == '/') { if (i == ref->nlvl_to - 1) break; else i++; } /* compose filename if next level down to target was found */ if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) { memcpy(filename, src, src_path - src); filename[src_path - src] = 0; for (i = 1; i < ref->nlvl_from; i++) av_strlcat(filename, "../", sizeof(filename)); av_strlcat(filename, ref->path + l + 1, sizeof(filename)); if (!c->use_absolute_path) { int same_origin = test_same_origin(src, filename); if (!same_origin) { av_log(c->fc, AV_LOG_ERROR, "Reference with mismatching origin, %s not tried for security reasons, " "set demuxer option use_absolute_path to allow it anyway\n", ref->path); return AVERROR(ENOENT); } if(strstr(ref->path + l + 1, "..") || strstr(ref->path + l + 1, ":") || (ref->nlvl_from > 1 && same_origin < 0) || (filename[0] == '/' && src_path == src)) return AVERROR(ENOENT); } if (strlen(filename) + 1 == sizeof(filename)) return AVERROR(ENOENT); if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL)) return 0; } } else if (c->use_absolute_path) { av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, " "this is a possible security issue\n"); if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL)) return 0; } else { av_log(c->fc, AV_LOG_ERROR, "Absolute path %s not tried for security reasons, " "set demuxer option use_absolute_path to allow absolute paths\n", ref->path); } return AVERROR(ENOENT); } static void fix_timescale(MOVContext *c, MOVStreamContext *sc) { if (sc->time_scale <= 0) { av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex); sc->time_scale = c->time_scale; if (sc->time_scale <= 0) sc->time_scale = 1; } } static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int ret; st = avformat_new_stream(c->fc, NULL); if (!st) return AVERROR(ENOMEM); st->id = c->fc->nb_streams; sc = av_mallocz(sizeof(MOVStreamContext)); if (!sc) return AVERROR(ENOMEM); st->priv_data = sc; st->codecpar->codec_type = AVMEDIA_TYPE_DATA; sc->ffindex = st->index; c->trak_index = st->index; if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; c->trak_index = -1; /* sanity checks */ if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count || (!sc->sample_size && !sc->sample_count))) || (!sc->chunk_count && sc->sample_count)) { av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n", st->index); return 0; } fix_timescale(c, sc); avpriv_set_pts_info(st, 64, 1, sc->time_scale); mov_build_index(c, st); if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) { MOVDref *dref = &sc->drefs[sc->dref_id - 1]; if (c->enable_drefs) { if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0) av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening alias: path='%s', dir='%s', " "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n", st->index, dref->path, dref->dir, dref->filename, dref->volume, dref->nlvl_from, dref->nlvl_to); } else { av_log(c->fc, AV_LOG_WARNING, "Skipped opening external track: " "stream %d, alias: path='%s', dir='%s', " "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d." "Set enable_drefs to allow this.\n", st->index, dref->path, dref->dir, dref->filename, dref->volume, dref->nlvl_from, dref->nlvl_to); } } else { sc->pb = c->fc->pb; sc->pb_is_copied = 1; } if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height && sc->height && sc->width && (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) { st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) / ((double)st->codecpar->width * sc->height), INT_MAX); } #if FF_API_R_FRAME_RATE if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1)) av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, sc->time_scale, sc->stts_data[0].duration, INT_MAX); #endif } // done for ai5q, ai52, ai55, ai1q, ai12 and ai15. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 && TAG_IS_AVCI(st->codecpar->codec_tag)) { ret = ff_generate_avci_extradata(st); if (ret < 0) return ret; } switch (st->codecpar->codec_id) { #if CONFIG_H261_DECODER case AV_CODEC_ID_H261: #endif #if CONFIG_H263_DECODER case AV_CODEC_ID_H263: #endif #if CONFIG_MPEG4_DECODER case AV_CODEC_ID_MPEG4: #endif st->codecpar->width = 0; /* let decoder init width/height */ st->codecpar->height= 0; break; } // If the duration of the mp3 packets is not constant, then they could need a parser if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && sc->stts_count > 3 && sc->stts_count*10 > st->nb_frames && sc->time_scale == st->codecpar->sample_rate) { st->need_parsing = AVSTREAM_PARSE_FULL; } /* Do not need those anymore. */ av_freep(&sc->chunk_offsets); av_freep(&sc->sample_sizes); av_freep(&sc->keyframes); av_freep(&sc->stts_data); av_freep(&sc->stps_data); av_freep(&sc->elst_data); av_freep(&sc->rap_group); return 0; } static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; c->itunes_metadata = 1; ret = mov_read_default(c, pb, atom); c->itunes_metadata = 0; return ret; } static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint32_t count; uint32_t i; if (atom.size < 8) return 0; avio_skip(pb, 4); count = avio_rb32(pb); if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) { av_log(c->fc, AV_LOG_ERROR, "The 'keys' atom with the invalid key count: %"PRIu32"\n", count); return AVERROR_INVALIDDATA; } c->meta_keys_count = count + 1; c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys)); if (!c->meta_keys) return AVERROR(ENOMEM); for (i = 1; i <= count; ++i) { uint32_t key_size = avio_rb32(pb); uint32_t type = avio_rl32(pb); if (key_size < 8) { av_log(c->fc, AV_LOG_ERROR, "The key# %"PRIu32" in meta has invalid size:" "%"PRIu32"\n", i, key_size); return AVERROR_INVALIDDATA; } key_size -= 8; if (type != MKTAG('m','d','t','a')) { avio_skip(pb, key_size); } c->meta_keys[i] = av_mallocz(key_size + 1); if (!c->meta_keys[i]) return AVERROR(ENOMEM); avio_read(pb, c->meta_keys[i], key_size); } return 0; } static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t end = avio_tell(pb) + atom.size; uint8_t *key = NULL, *val = NULL, *mean = NULL; int i; int ret = 0; AVStream *st; MOVStreamContext *sc; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; for (i = 0; i < 3; i++) { uint8_t **p; uint32_t len, tag; if (end - avio_tell(pb) <= 12) break; len = avio_rb32(pb); tag = avio_rl32(pb); avio_skip(pb, 4); // flags if (len < 12 || len - 12 > end - avio_tell(pb)) break; len -= 12; if (tag == MKTAG('m', 'e', 'a', 'n')) p = &mean; else if (tag == MKTAG('n', 'a', 'm', 'e')) p = &key; else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) { avio_skip(pb, 4); len -= 4; p = &val; } else break; *p = av_malloc(len + 1); if (!*p) break; ret = ffio_read_size(pb, *p, len); if (ret < 0) { av_freep(p); break; } (*p)[len] = 0; } if (mean && key && val) { if (strcmp(key, "iTunSMPB") == 0) { int priming, remainder, samples; if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){ if(priming>0 && priming<16384) sc->start_pad = priming; } } if (strcmp(key, "cdec") != 0) { av_dict_set(&c->fc->metadata, key, val, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL); key = val = NULL; } } else { av_log(c->fc, AV_LOG_VERBOSE, "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size); } avio_seek(pb, end, SEEK_SET); av_freep(&key); av_freep(&val); av_freep(&mean); return ret; } static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom) { while (atom.size > 8) { uint32_t tag = avio_rl32(pb); atom.size -= 4; if (tag == MKTAG('h','d','l','r')) { avio_seek(pb, -8, SEEK_CUR); atom.size += 8; return mov_read_default(c, pb, atom); } } return 0; } // return 1 when matrix is identity, 0 otherwise #define IS_MATRIX_IDENT(matrix) \ ( (matrix)[0][0] == (1 << 16) && \ (matrix)[1][1] == (1 << 16) && \ (matrix)[2][2] == (1 << 30) && \ !(matrix)[0][1] && !(matrix)[0][2] && \ !(matrix)[1][0] && !(matrix)[1][2] && \ !(matrix)[2][0] && !(matrix)[2][1]) static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int i, j, e; int width; int height; int display_matrix[3][3]; int res_display_matrix[3][3] = { { 0 } }; AVStream *st; MOVStreamContext *sc; int version; int flags; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; version = avio_r8(pb); flags = avio_rb24(pb); st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0; if (version == 1) { avio_rb64(pb); avio_rb64(pb); } else { avio_rb32(pb); /* creation time */ avio_rb32(pb); /* modification time */ } st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/ avio_rb32(pb); /* reserved */ /* highlevel (considering edits) duration in movie timebase */ (version == 1) ? avio_rb64(pb) : avio_rb32(pb); avio_rb32(pb); /* reserved */ avio_rb32(pb); /* reserved */ avio_rb16(pb); /* layer */ avio_rb16(pb); /* alternate group */ avio_rb16(pb); /* volume */ avio_rb16(pb); /* reserved */ //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2) // they're kept in fixed point format through all calculations // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX // side data, but the scale factor is not needed to calculate aspect ratio for (i = 0; i < 3; i++) { display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point } width = avio_rb32(pb); // 16.16 fixed point track width height = avio_rb32(pb); // 16.16 fixed point track height sc->width = width >> 16; sc->height = height >> 16; // apply the moov display matrix (after the tkhd one) for (i = 0; i < 3; i++) { const int sh[3] = { 16, 16, 30 }; for (j = 0; j < 3; j++) { for (e = 0; e < 3; e++) { res_display_matrix[i][j] += ((int64_t) display_matrix[i][e] * c->movie_display_matrix[e][j]) >> sh[e]; } } } // save the matrix when it is not the default identity if (!IS_MATRIX_IDENT(res_display_matrix)) { double rotate; av_freep(&sc->display_matrix); sc->display_matrix = av_malloc(sizeof(int32_t) * 9); if (!sc->display_matrix) return AVERROR(ENOMEM); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) sc->display_matrix[i * 3 + j] = res_display_matrix[i][j]; #if FF_API_OLD_ROTATE_API rotate = av_display_rotation_get(sc->display_matrix); if (!isnan(rotate)) { char rotate_buf[64]; rotate = -rotate; if (rotate < 0) // for backward compatibility rotate += 360; snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate); av_dict_set(&st->metadata, "rotate", rotate_buf, 0); } #endif } // transform the display width/height according to the matrix // to keep the same scale, use [width height 1<<16] if (width && height && sc->display_matrix) { double disp_transform[2]; for (i = 0; i < 2; i++) disp_transform[i] = hypot(sc->display_matrix[0 + i], sc->display_matrix[3 + i]); if (disp_transform[0] > 0 && disp_transform[1] > 0 && disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) && fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01) st->sample_aspect_ratio = av_d2q( disp_transform[0] / disp_transform[1], INT_MAX); } return 0; } static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; MOVTrackExt *trex = NULL; MOVFragmentIndex* index = NULL; int flags, track_id, i, found = 0; avio_r8(pb); /* version */ flags = avio_rb24(pb); track_id = avio_rb32(pb); if (!track_id) return AVERROR_INVALIDDATA; frag->track_id = track_id; for (i = 0; i < c->trex_count; i++) if (c->trex_data[i].track_id == frag->track_id) { trex = &c->trex_data[i]; break; } if (!trex) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n"); return AVERROR_INVALIDDATA; } frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ? avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ? frag->moof_offset : frag->implicit_offset; frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id; frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ? avio_rb32(pb) : trex->duration; frag->size = flags & MOV_TFHD_DEFAULT_SIZE ? avio_rb32(pb) : trex->size; frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ? avio_rb32(pb) : trex->flags; frag->time = AV_NOPTS_VALUE; for (i = 0; i < c->fragment_index_count; i++) { int j; MOVFragmentIndex* candidate = c->fragment_index_data[i]; if (candidate->track_id == frag->track_id) { av_log(c->fc, AV_LOG_DEBUG, "found fragment index for track %u\n", frag->track_id); index = candidate; for (j = index->current_item; j < index->item_count; j++) { if (frag->implicit_offset == index->items[j].moof_offset) { av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry " "for track %u and moof_offset %"PRId64"\n", frag->track_id, index->items[j].moof_offset); frag->time = index->items[j].time; index->current_item = j + 1; found = 1; break; } } if (found) break; } } if (index && !found) { av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but " "it doesn't have an (in-order) entry for moof_offset " "%"PRId64"\n", frag->track_id, frag->implicit_offset); } av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags); return 0; } static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom) { unsigned i, num; void *new_tracks; num = atom.size / 4; if (!(new_tracks = av_malloc_array(num, sizeof(int)))) return AVERROR(ENOMEM); av_free(c->chapter_tracks); c->chapter_tracks = new_tracks; c->nb_chapter_tracks = num; for (i = 0; i < num && !pb->eof_reached; i++) c->chapter_tracks[i] = avio_rb32(pb); return 0; } static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVTrackExt *trex; int err; if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data)) return AVERROR_INVALIDDATA; if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1, sizeof(*c->trex_data))) < 0) { c->trex_count = 0; return err; } c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used. trex = &c->trex_data[c->trex_count++]; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ trex->track_id = avio_rb32(pb); trex->stsd_id = avio_rb32(pb); trex->duration = avio_rb32(pb); trex->size = avio_rb32(pb); trex->flags = avio_rb32(pb); return 0; } static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; AVStream *st = NULL; MOVStreamContext *sc; int version, i; for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == frag->track_id) { st = c->fc->streams[i]; break; } } if (!st) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id); return AVERROR_INVALIDDATA; } sc = st->priv_data; if (sc->pseudo_stream_id + 1 != frag->stsd_id) return 0; version = avio_r8(pb); avio_rb24(pb); /* flags */ if (version) { sc->track_end = avio_rb64(pb); } else { sc->track_end = avio_rb32(pb); } return 0; } static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; AVStream *st = NULL; MOVStreamContext *sc; MOVStts *ctts_data; uint64_t offset; int64_t dts; int data_offset = 0; unsigned entries, first_sample_flags = frag->flags; int flags, distance, i; for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == frag->track_id) { st = c->fc->streams[i]; break; } } if (!st) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id); return AVERROR_INVALIDDATA; } sc = st->priv_data; if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1) return 0; avio_r8(pb); /* version */ flags = avio_rb24(pb); entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries); if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data)) return AVERROR_INVALIDDATA; if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb); if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb); dts = sc->track_end - sc->time_offset; offset = frag->base_data_offset + data_offset; distance = 0; av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags); for (i = 0; i < entries && !pb->eof_reached; i++) { unsigned sample_size = frag->size; int sample_flags = i ? frag->flags : first_sample_flags; unsigned sample_duration = frag->duration; unsigned ctts_duration = 0; int keyframe = 0; int ctts_index = 0; int old_nb_index_entries = st->nb_index_entries; if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb); mov_update_dts_shift(sc, ctts_duration); if (frag->time != AV_NOPTS_VALUE) { if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) { int64_t pts = frag->time; av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64 " sc->dts_shift %d ctts.duration %d" " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts, sc->dts_shift, ctts_duration, sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS); dts = pts - sc->dts_shift; if (flags & MOV_TRUN_SAMPLE_CTS) { dts -= ctts_duration; } else { dts -= sc->time_offset; } av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts); } else { dts = frag->time - sc->time_offset; av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64 ", using it for dts\n", dts); } frag->time = AV_NOPTS_VALUE; } if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) keyframe = 1; else keyframe = !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC | MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES)); if (keyframe) distance = 0; ctts_index = av_add_index_entry(st, offset, dts, sample_size, distance, keyframe ? AVINDEX_KEYFRAME : 0); if (ctts_index >= 0 && old_nb_index_entries < st->nb_index_entries) { unsigned int size_needed = st->nb_index_entries * sizeof(*sc->ctts_data); unsigned int request_size = size_needed > sc->ctts_allocated_size ? FFMAX(size_needed, 2 * sc->ctts_allocated_size) : size_needed; unsigned int old_ctts_size = sc->ctts_allocated_size; ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size, request_size); if (!ctts_data) { av_freep(&sc->ctts_data); return AVERROR(ENOMEM); } sc->ctts_data = ctts_data; // In case there were samples without ctts entries, ensure they get // zero valued entries. This ensures clips which mix boxes with and // without ctts entries don't pickup uninitialized data. memset((uint8_t*)(sc->ctts_data) + old_ctts_size, 0, sc->ctts_allocated_size - old_ctts_size); if (ctts_index != old_nb_index_entries) { memmove(sc->ctts_data + ctts_index + 1, sc->ctts_data + ctts_index, sizeof(*sc->ctts_data) * (sc->ctts_count - ctts_index)); if (ctts_index <= sc->current_sample) { // if we inserted a new item before the current sample, move the // counter ahead so it is still pointing to the same sample. sc->current_sample++; } } sc->ctts_data[ctts_index].count = 1; sc->ctts_data[ctts_index].duration = ctts_duration; sc->ctts_count++; } else { av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n"); } av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", " "size %u, distance %d, keyframe %d\n", st->index, ctts_index, offset, dts, sample_size, distance, keyframe); distance++; dts += sample_duration; offset += sample_size; sc->data_size += sample_size; sc->duration_for_fps += sample_duration; sc->nb_frames_for_fps ++; } if (pb->eof_reached) return AVERROR_EOF; frag->implicit_offset = offset; sc->track_end = dts + sc->time_offset; if (st->duration < sc->track_end) st->duration = sc->track_end; return 0; } static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t offset = avio_tell(pb) + atom.size, pts; uint8_t version; unsigned i, track_id; AVStream *st = NULL; AVStream *ref_st = NULL; MOVStreamContext *sc, *ref_sc = NULL; MOVFragmentIndex *index = NULL; MOVFragmentIndex **tmp; AVRational timescale; version = avio_r8(pb); if (version > 1) { avpriv_request_sample(c->fc, "sidx version %u", version); return 0; } avio_rb24(pb); // flags track_id = avio_rb32(pb); // Reference ID for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == track_id) { st = c->fc->streams[i]; break; } } if (!st) { av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id); return 0; } sc = st->priv_data; timescale = av_make_q(1, avio_rb32(pb)); if (timescale.den <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den); return AVERROR_INVALIDDATA; } if (version == 0) { pts = avio_rb32(pb); offset += avio_rb32(pb); } else { pts = avio_rb64(pb); offset += avio_rb64(pb); } avio_rb16(pb); // reserved index = av_mallocz(sizeof(MOVFragmentIndex)); if (!index) return AVERROR(ENOMEM); index->track_id = track_id; index->item_count = avio_rb16(pb); index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem)); if (!index->items) { av_freep(&index); return AVERROR(ENOMEM); } for (i = 0; i < index->item_count; i++) { uint32_t size = avio_rb32(pb); uint32_t duration = avio_rb32(pb); if (size & 0x80000000) { avpriv_request_sample(c->fc, "sidx reference_type 1"); av_freep(&index->items); av_freep(&index); return AVERROR_PATCHWELCOME; } avio_rb32(pb); // sap_flags index->items[i].moof_offset = offset; index->items[i].time = av_rescale_q(pts, st->time_base, timescale); offset += size; pts += duration; } st->duration = sc->track_end = pts; tmp = av_realloc_array(c->fragment_index_data, c->fragment_index_count + 1, sizeof(MOVFragmentIndex*)); if (!tmp) { av_freep(&index->items); av_freep(&index); return AVERROR(ENOMEM); } c->fragment_index_data = tmp; c->fragment_index_data[c->fragment_index_count++] = index; sc->has_sidx = 1; if (offset == avio_size(pb)) { for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == c->fragment_index_data[0]->track_id) { ref_st = c->fc->streams[i]; ref_sc = ref_st->priv_data; break; } } for (i = 0; i < c->fc->nb_streams; i++) { st = c->fc->streams[i]; sc = st->priv_data; if (!sc->has_sidx) { st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale); } } c->fragment_index_complete = 1; } return 0; } /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */ /* like the files created with Adobe Premiere 5.0, for samples see */ /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */ static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int err; if (atom.size < 8) return 0; /* continue */ if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */ avio_skip(pb, atom.size - 4); return 0; } atom.type = avio_rl32(pb); atom.size -= 8; if (atom.type != MKTAG('m','d','a','t')) { avio_skip(pb, atom.size); return 0; } err = mov_read_mdat(c, pb, atom); return err; } static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom) { #if CONFIG_ZLIB AVIOContext ctx; uint8_t *cmov_data; uint8_t *moov_data; /* uncompressed data */ long cmov_len, moov_len; int ret = -1; avio_rb32(pb); /* dcom atom */ if (avio_rl32(pb) != MKTAG('d','c','o','m')) return AVERROR_INVALIDDATA; if (avio_rl32(pb) != MKTAG('z','l','i','b')) { av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n"); return AVERROR_INVALIDDATA; } avio_rb32(pb); /* cmvd atom */ if (avio_rl32(pb) != MKTAG('c','m','v','d')) return AVERROR_INVALIDDATA; moov_len = avio_rb32(pb); /* uncompressed size */ cmov_len = atom.size - 6 * 4; cmov_data = av_malloc(cmov_len); if (!cmov_data) return AVERROR(ENOMEM); moov_data = av_malloc(moov_len); if (!moov_data) { av_free(cmov_data); return AVERROR(ENOMEM); } ret = ffio_read_size(pb, cmov_data, cmov_len); if (ret < 0) goto free_and_return; if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK) goto free_and_return; if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0) goto free_and_return; ctx.seekable = AVIO_SEEKABLE_NORMAL; atom.type = MKTAG('m','o','o','v'); atom.size = moov_len; ret = mov_read_default(c, &ctx, atom); free_and_return: av_free(moov_data); av_free(cmov_data); return ret; #else av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n"); return AVERROR(ENOSYS); #endif } /* edit list atom */ static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; int i, edit_count, version; if (c->fc->nb_streams < 1 || c->ignore_editlist) return 0; sc = c->fc->streams[c->fc->nb_streams-1]->priv_data; version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ edit_count = avio_rb32(pb); /* entries */ if (!edit_count) return 0; if (sc->elst_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n"); av_free(sc->elst_data); sc->elst_count = 0; sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data)); if (!sc->elst_data) return AVERROR(ENOMEM); av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count); for (i = 0; i < edit_count && !pb->eof_reached; i++) { MOVElst *e = &sc->elst_data[i]; if (version == 1) { e->duration = avio_rb64(pb); e->time = avio_rb64(pb); } else { e->duration = avio_rb32(pb); /* segment duration */ e->time = (int32_t)avio_rb32(pb); /* media time */ } e->rate = avio_rb32(pb) / 65536.0; av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n", e->duration, e->time, e->rate); if (e->time < 0 && e->time != -1 && c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) { av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n", c->fc->nb_streams-1, i, e->time); return AVERROR_INVALIDDATA; } } sc->elst_count = i; return 0; } static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; if (c->fc->nb_streams < 1) return AVERROR_INVALIDDATA; sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data; sc->timecode_track = avio_rb32(pb); return 0; } static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int version, color_range, color_primaries, color_trc, color_space; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version != 1) { av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version); return 0; } avio_skip(pb, 3); /* flags */ avio_skip(pb, 2); /* profile + level */ color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */ color_primaries = avio_r8(pb); color_trc = avio_r8(pb); color_space = avio_r8(pb); if (avio_rb16(pb)) /* codecIntializationDataSize */ return AVERROR_INVALIDDATA; if (!av_color_primaries_name(color_primaries)) color_primaries = AVCOL_PRI_UNSPECIFIED; if (!av_color_transfer_name(color_trc)) color_trc = AVCOL_TRC_UNSPECIFIED; if (!av_color_space_name(color_space)) color_space = AVCOL_SPC_UNSPECIFIED; st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; st->codecpar->color_primaries = color_primaries; st->codecpar->color_trc = color_trc; st->codecpar->color_space = color_space; return 0; } static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; const int chroma_den = 50000; const int luma_den = 10000; int i, j, version; if (c->fc->nb_streams < 1) return AVERROR_INVALIDDATA; sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version) { av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version); return 0; } avio_skip(pb, 3); /* flags */ sc->mastering = av_mastering_display_metadata_alloc(); if (!sc->mastering) return AVERROR(ENOMEM); for (i = 0; i < 3; i++) for (j = 0; j < 2; j++) sc->mastering->display_primaries[i][j] = av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den); for (i = 0; i < 2; i++) sc->mastering->white_point[i] = av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den); sc->mastering->max_luminance = av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den); sc->mastering->min_luminance = av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den); sc->mastering->has_primaries = 1; sc->mastering->has_luminance = 1; return 0; } static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; int version; if (c->fc->nb_streams < 1) return AVERROR_INVALIDDATA; sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version) { av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version); return 0; } avio_skip(pb, 3); /* flags */ sc->coll = av_content_light_metadata_alloc(&sc->coll_size); if (!sc->coll) return AVERROR(ENOMEM); sc->coll->MaxCLL = avio_rb16(pb); sc->coll->MaxFALL = avio_rb16(pb); return 0; } static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; enum AVStereo3DType type; int mode; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); /* version + flags */ mode = avio_r8(pb); switch (mode) { case 0: type = AV_STEREO3D_2D; break; case 1: type = AV_STEREO3D_TOPBOTTOM; break; case 2: type = AV_STEREO3D_SIDEBYSIDE; break; default: av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode); return 0; } sc->stereo3d = av_stereo3d_alloc(); if (!sc->stereo3d) return AVERROR(ENOMEM); sc->stereo3d->type = type; return 0; } static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int size, layout; int32_t yaw, pitch, roll; uint32_t l = 0, t = 0, r = 0, b = 0; uint32_t tag, padding = 0; enum AVSphericalProjection projection; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (atom.size < 8) { av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n"); return AVERROR_INVALIDDATA; } size = avio_rb32(pb); if (size <= 12 || size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('s','v','h','d')) { av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n"); return 0; } avio_skip(pb, 4); /* version + flags */ avio_skip(pb, size - 12); /* metadata_source */ size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('p','r','o','j')) { av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n"); return 0; } size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('p','r','h','d')) { av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n"); return 0; } avio_skip(pb, 4); /* version + flags */ /* 16.16 fixed point */ yaw = avio_rb32(pb); pitch = avio_rb32(pb); roll = avio_rb32(pb); size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); avio_skip(pb, 4); /* version + flags */ switch (tag) { case MKTAG('c','b','m','p'): layout = avio_rb32(pb); if (layout) { av_log(c->fc, AV_LOG_WARNING, "Unsupported cubemap layout %d\n", layout); return 0; } projection = AV_SPHERICAL_CUBEMAP; padding = avio_rb32(pb); break; case MKTAG('e','q','u','i'): t = avio_rb32(pb); b = avio_rb32(pb); l = avio_rb32(pb); r = avio_rb32(pb); if (b >= UINT_MAX - t || r >= UINT_MAX - l) { av_log(c->fc, AV_LOG_ERROR, "Invalid bounding rectangle coordinates " "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b); return AVERROR_INVALIDDATA; } if (l || t || r || b) projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE; else projection = AV_SPHERICAL_EQUIRECTANGULAR; break; default: av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n"); return 0; } sc->spherical = av_spherical_alloc(&sc->spherical_size); if (!sc->spherical) return AVERROR(ENOMEM); sc->spherical->projection = projection; sc->spherical->yaw = yaw; sc->spherical->pitch = pitch; sc->spherical->roll = roll; sc->spherical->padding = padding; sc->spherical->bound_left = l; sc->spherical->bound_top = t; sc->spherical->bound_right = r; sc->spherical->bound_bottom = b; return 0; } static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len) { int ret = 0; uint8_t *buffer = av_malloc(len + 1); const char *val; if (!buffer) return AVERROR(ENOMEM); buffer[len] = '\0'; ret = ffio_read_size(pb, buffer, len); if (ret < 0) goto out; /* Check for mandatory keys and values, try to support XML as best-effort */ if (av_stristr(buffer, "<GSpherical:StitchingSoftware>") && (val = av_stristr(buffer, "<GSpherical:Spherical>")) && av_stristr(val, "true") && (val = av_stristr(buffer, "<GSpherical:Stitched>")) && av_stristr(val, "true") && (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) && av_stristr(val, "equirectangular")) { sc->spherical = av_spherical_alloc(&sc->spherical_size); if (!sc->spherical) goto out; sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR; if (av_stristr(buffer, "<GSpherical:StereoMode>")) { enum AVStereo3DType mode; if (av_stristr(buffer, "left-right")) mode = AV_STEREO3D_SIDEBYSIDE; else if (av_stristr(buffer, "top-bottom")) mode = AV_STEREO3D_TOPBOTTOM; else mode = AV_STEREO3D_2D; sc->stereo3d = av_stereo3d_alloc(); if (!sc->stereo3d) goto out; sc->stereo3d->type = mode; } /* orientation */ val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>"); if (val) sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16); val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>"); if (val) sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16); val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>"); if (val) sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16); } out: av_free(buffer); return ret; } static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int64_t ret; uint8_t uuid[16]; static const uint8_t uuid_isml_manifest[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; static const uint8_t uuid_xmp[] = { 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac }; static const uint8_t uuid_spherical[] = { 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93, 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd, }; if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX)) return AVERROR_INVALIDDATA; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; ret = avio_read(pb, uuid, sizeof(uuid)); if (ret < 0) { return ret; } else if (ret != sizeof(uuid)) { return AVERROR_INVALIDDATA; } if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) { uint8_t *buffer, *ptr; char *endptr; size_t len = atom.size - sizeof(uuid); if (len < 4) { return AVERROR_INVALIDDATA; } ret = avio_skip(pb, 4); // zeroes len -= 4; buffer = av_mallocz(len + 1); if (!buffer) { return AVERROR(ENOMEM); } ret = avio_read(pb, buffer, len); if (ret < 0) { av_free(buffer); return ret; } else if (ret != len) { av_free(buffer); return AVERROR_INVALIDDATA; } ptr = buffer; while ((ptr = av_stristr(ptr, "systemBitrate=\""))) { ptr += sizeof("systemBitrate=\"") - 1; c->bitrates_count++; c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates)); if (!c->bitrates) { c->bitrates_count = 0; av_free(buffer); return AVERROR(ENOMEM); } errno = 0; ret = strtol(ptr, &endptr, 10); if (ret < 0 || errno || *endptr != '"') { c->bitrates[c->bitrates_count - 1] = 0; } else { c->bitrates[c->bitrates_count - 1] = ret; } } av_free(buffer); } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) { uint8_t *buffer; size_t len = atom.size - sizeof(uuid); if (c->export_xmp) { buffer = av_mallocz(len + 1); if (!buffer) { return AVERROR(ENOMEM); } ret = avio_read(pb, buffer, len); if (ret < 0) { av_free(buffer); return ret; } else if (ret != len) { av_free(buffer); return AVERROR_INVALIDDATA; } buffer[len] = '\0'; av_dict_set(&c->fc->metadata, "xmp", buffer, 0); av_free(buffer); } else { // skip all uuid atom, which makes it fast for long uuid-xmp file ret = avio_skip(pb, len); if (ret < 0) return ret; } } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) { size_t len = atom.size - sizeof(uuid); ret = mov_parse_uuid_spherical(sc, pb, len); if (ret < 0) return ret; if (!sc->spherical) av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n"); } return 0; } static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; uint8_t content[16]; if (atom.size < 8) return 0; ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size)); if (ret < 0) return ret; if ( !c->found_moov && !c->found_mdat && !memcmp(content, "Anevia\x1A\x1A", 8) && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) { c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS; } return 0; } static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint32_t format = avio_rl32(pb); MOVStreamContext *sc; enum AVCodecID id; AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; switch (sc->format) { case MKTAG('e','n','c','v'): // encrypted video case MKTAG('e','n','c','a'): // encrypted audio id = mov_codec_id(st, format); if (st->codecpar->codec_id != AV_CODEC_ID_NONE && st->codecpar->codec_id != id) { av_log(c->fc, AV_LOG_WARNING, "ignoring 'frma' atom of '%.4s', stream has codec id %d\n", (char*)&format, st->codecpar->codec_id); break; } st->codecpar->codec_id = id; sc->format = format; break; default: if (format != sc->format) { av_log(c->fc, AV_LOG_WARNING, "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n", (char*)&format, (char*)&sc->format); } break; } return 0; } static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; size_t auxiliary_info_size; if (c->decryption_key_len == 0 || c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (sc->cenc.aes_ctr) { av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n"); return AVERROR_INVALIDDATA; } avio_r8(pb); /* version */ sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */ avio_rb32(pb); /* entries */ if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) { av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size); return AVERROR_INVALIDDATA; } /* save the auxiliary info as is */ auxiliary_info_size = atom.size - 8; sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size); if (!sc->cenc.auxiliary_info) { return AVERROR(ENOMEM); } sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size; sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info; sc->cenc.auxiliary_info_index = 0; if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) { av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info"); return AVERROR_INVALIDDATA; } /* initialize the cipher */ sc->cenc.aes_ctr = av_aes_ctr_alloc(); if (!sc->cenc.aes_ctr) { return AVERROR(ENOMEM); } return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key); } static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; size_t data_size; int atom_header_size; int flags; if (c->decryption_key_len == 0 || c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) { av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n"); return AVERROR_INVALIDDATA; } atom_header_size = 9; avio_r8(pb); /* version */ flags = avio_rb24(pb); if ((flags & 0x01) != 0) { atom_header_size += 8; avio_rb32(pb); /* info type */ avio_rb32(pb); /* info type param */ } sc->cenc.auxiliary_info_default_size = avio_r8(pb); avio_rb32(pb); /* entries */ if (atom.size <= atom_header_size) { return 0; } if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) { av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size); return AVERROR_INVALIDDATA; } /* save the auxiliary info sizes as is */ data_size = atom.size - atom_header_size; sc->cenc.auxiliary_info_sizes = av_malloc(data_size); if (!sc->cenc.auxiliary_info_sizes) { return AVERROR(ENOMEM); } sc->cenc.auxiliary_info_sizes_count = data_size; if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) { av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes"); return AVERROR_INVALIDDATA; } return 0; } static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int last, type, size, ret; uint8_t buf[4]; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30) || atom.size < 42) return AVERROR_INVALIDDATA; /* Check FlacSpecificBox version. */ if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; avio_rb24(pb); /* Flags */ avio_read(pb, buf, sizeof(buf)); flac_parse_block_header(buf, &last, &type, &size); if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) { av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n"); return AVERROR_INVALIDDATA; } ret = ff_get_extradata(c->fc, st->codecpar, pb, size); if (ret < 0) return ret; if (!last) av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n"); return 0; } static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index) { size_t auxiliary_info_seek_offset = 0; int i; if (sc->cenc.auxiliary_info_default_size) { auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index; } else if (sc->cenc.auxiliary_info_sizes) { if (index > sc->cenc.auxiliary_info_sizes_count) { av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n", index, sc->cenc.auxiliary_info_sizes_count); return AVERROR_INVALIDDATA; } for (i = 0; i < index; i++) { auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i]; } } if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) { av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n", auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info)); return AVERROR_INVALIDDATA; } sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset; sc->cenc.auxiliary_info_index = index; return 0; } static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size) { uint32_t encrypted_bytes; uint16_t subsample_count; uint16_t clear_bytes; uint8_t* input_end = input + size; int ret; if (index != sc->cenc.auxiliary_info_index) { ret = mov_seek_auxiliary_info(c, sc, index); if (ret < 0) { return ret; } } /* read the iv */ if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) { av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n"); return AVERROR_INVALIDDATA; } av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE; if (!sc->cenc.use_subsamples) { /* decrypt the whole packet */ av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size); return 0; } /* read the subsample count */ if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) { av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n"); return AVERROR_INVALIDDATA; } subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += sizeof(uint16_t); for (; subsample_count > 0; subsample_count--) { if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) { av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n"); return AVERROR_INVALIDDATA; } /* read the number of clear / encrypted bytes */ clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += sizeof(uint16_t); encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += sizeof(uint32_t); if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) { av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n"); return AVERROR_INVALIDDATA; } /* skip the clear bytes */ input += clear_bytes; /* decrypt the encrypted bytes */ av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes); input += encrypted_bytes; } if (input < input_end) { av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n"); return AVERROR_INVALIDDATA; } sc->cenc.auxiliary_info_index++; return 0; } static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom) { const int OPUS_SEEK_PREROLL_MS = 80; AVStream *st; size_t size; int16_t pre_skip; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30) || atom.size < 11) return AVERROR_INVALIDDATA; /* Check OpusSpecificBox version. */ if (avio_r8(pb) != 0) { av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n"); return AVERROR_INVALIDDATA; } /* OpusSpecificBox size plus magic for Ogg OpusHead header. */ size = atom.size + 8; if (ff_alloc_extradata(st->codecpar, size)) return AVERROR(ENOMEM); AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s')); AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d')); AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */ avio_read(pb, st->codecpar->extradata + 9, size - 9); /* OpusSpecificBox is stored in big-endian, but OpusHead is little-endian; aside from the preceeding magic and version they're otherwise currently identical. Data after output gain at offset 16 doesn't need to be bytewapped. */ pre_skip = AV_RB16(st->codecpar->extradata + 10); AV_WL16(st->codecpar->extradata + 10, pre_skip); AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12)); AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16)); st->codecpar->initial_padding = pre_skip; st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); return 0; } static const MOVParseTableEntry mov_default_parse_table[] = { { MKTAG('A','C','L','R'), mov_read_aclr }, { MKTAG('A','P','R','G'), mov_read_avid }, { MKTAG('A','A','L','P'), mov_read_avid }, { MKTAG('A','R','E','S'), mov_read_ares }, { MKTAG('a','v','s','s'), mov_read_avss }, { MKTAG('c','h','p','l'), mov_read_chpl }, { MKTAG('c','o','6','4'), mov_read_stco }, { MKTAG('c','o','l','r'), mov_read_colr }, { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */ { MKTAG('d','i','n','f'), mov_read_default }, { MKTAG('D','p','x','E'), mov_read_dpxe }, { MKTAG('d','r','e','f'), mov_read_dref }, { MKTAG('e','d','t','s'), mov_read_default }, { MKTAG('e','l','s','t'), mov_read_elst }, { MKTAG('e','n','d','a'), mov_read_enda }, { MKTAG('f','i','e','l'), mov_read_fiel }, { MKTAG('a','d','r','m'), mov_read_adrm }, { MKTAG('f','t','y','p'), mov_read_ftyp }, { MKTAG('g','l','b','l'), mov_read_glbl }, { MKTAG('h','d','l','r'), mov_read_hdlr }, { MKTAG('i','l','s','t'), mov_read_ilst }, { MKTAG('j','p','2','h'), mov_read_jp2h }, { MKTAG('m','d','a','t'), mov_read_mdat }, { MKTAG('m','d','h','d'), mov_read_mdhd }, { MKTAG('m','d','i','a'), mov_read_default }, { MKTAG('m','e','t','a'), mov_read_meta }, { MKTAG('m','i','n','f'), mov_read_default }, { MKTAG('m','o','o','f'), mov_read_moof }, { MKTAG('m','o','o','v'), mov_read_moov }, { MKTAG('m','v','e','x'), mov_read_default }, { MKTAG('m','v','h','d'), mov_read_mvhd }, { MKTAG('S','M','I',' '), mov_read_svq3 }, { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */ { MKTAG('a','v','c','C'), mov_read_glbl }, { MKTAG('p','a','s','p'), mov_read_pasp }, { MKTAG('s','i','d','x'), mov_read_sidx }, { MKTAG('s','t','b','l'), mov_read_default }, { MKTAG('s','t','c','o'), mov_read_stco }, { MKTAG('s','t','p','s'), mov_read_stps }, { MKTAG('s','t','r','f'), mov_read_strf }, { MKTAG('s','t','s','c'), mov_read_stsc }, { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */ { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */ { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */ { MKTAG('s','t','t','s'), mov_read_stts }, { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */ { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */ { MKTAG('t','f','d','t'), mov_read_tfdt }, { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */ { MKTAG('t','r','a','k'), mov_read_trak }, { MKTAG('t','r','a','f'), mov_read_default }, { MKTAG('t','r','e','f'), mov_read_default }, { MKTAG('t','m','c','d'), mov_read_tmcd }, { MKTAG('c','h','a','p'), mov_read_chap }, { MKTAG('t','r','e','x'), mov_read_trex }, { MKTAG('t','r','u','n'), mov_read_trun }, { MKTAG('u','d','t','a'), mov_read_default }, { MKTAG('w','a','v','e'), mov_read_wave }, { MKTAG('e','s','d','s'), mov_read_esds }, { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */ { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */ { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */ { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */ { MKTAG('w','f','e','x'), mov_read_wfex }, { MKTAG('c','m','o','v'), mov_read_cmov }, { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */ { MKTAG('d','v','c','1'), mov_read_dvc1 }, { MKTAG('s','b','g','p'), mov_read_sbgp }, { MKTAG('h','v','c','C'), mov_read_glbl }, { MKTAG('u','u','i','d'), mov_read_uuid }, { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 }, { MKTAG('f','r','e','e'), mov_read_free }, { MKTAG('-','-','-','-'), mov_read_custom }, { MKTAG('s','i','n','f'), mov_read_default }, { MKTAG('f','r','m','a'), mov_read_frma }, { MKTAG('s','e','n','c'), mov_read_senc }, { MKTAG('s','a','i','z'), mov_read_saiz }, { MKTAG('d','f','L','a'), mov_read_dfla }, { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */ { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */ { MKTAG('d','O','p','s'), mov_read_dops }, { MKTAG('S','m','D','m'), mov_read_smdm }, { MKTAG('C','o','L','L'), mov_read_coll }, { MKTAG('v','p','c','C'), mov_read_vpcc }, { 0, NULL } }; static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t total_size = 0; MOVAtom a; int i; if (c->atom_depth > 10) { av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n"); return AVERROR_INVALIDDATA; } c->atom_depth ++; if (atom.size < 0) atom.size = INT64_MAX; while (total_size <= atom.size - 8 && !avio_feof(pb)) { int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL; a.size = atom.size; a.type=0; if (atom.size >= 8) { a.size = avio_rb32(pb); a.type = avio_rl32(pb); if (a.type == MKTAG('f','r','e','e') && a.size >= 8 && c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT && c->moov_retry) { uint8_t buf[8]; uint32_t *type = (uint32_t *)buf + 1; if (avio_read(pb, buf, 8) != 8) return AVERROR_INVALIDDATA; avio_seek(pb, -8, SEEK_CUR); if (*type == MKTAG('m','v','h','d') || *type == MKTAG('c','m','o','v')) { av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n"); a.type = MKTAG('m','o','o','v'); } } if (atom.type != MKTAG('r','o','o','t') && atom.type != MKTAG('m','o','o','v')) { if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t')) { av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n"); avio_skip(pb, -8); c->atom_depth --; return 0; } } total_size += 8; if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */ a.size = avio_rb64(pb) - 8; total_size += 8; } } av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n", av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size); if (a.size == 0) { a.size = atom.size - total_size + 8; } a.size -= 8; if (a.size < 0) break; a.size = FFMIN(a.size, atom.size - total_size); for (i = 0; mov_default_parse_table[i].type; i++) if (mov_default_parse_table[i].type == a.type) { parse = mov_default_parse_table[i].parse; break; } // container is user data if (!parse && (atom.type == MKTAG('u','d','t','a') || atom.type == MKTAG('i','l','s','t'))) parse = mov_read_udta_string; // Supports parsing the QuickTime Metadata Keys. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html if (!parse && c->found_hdlr_mdta && atom.type == MKTAG('m','e','t','a') && a.type == MKTAG('k','e','y','s')) { parse = mov_read_keys; } if (!parse) { /* skip leaf atoms data */ avio_skip(pb, a.size); } else { int64_t start_pos = avio_tell(pb); int64_t left; int err = parse(c, pb, a); if (err < 0) { c->atom_depth --; return err; } if (c->found_moov && c->found_mdat && ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) || start_pos + a.size == avio_size(pb))) { if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) c->next_root_atom = start_pos + a.size; c->atom_depth --; return 0; } left = a.size - avio_tell(pb) + start_pos; if (left > 0) /* skip garbage at atom end */ avio_skip(pb, left); else if (left < 0) { av_log(c->fc, AV_LOG_WARNING, "overread end of atom '%.4s' by %"PRId64" bytes\n", (char*)&a.type, -left); avio_seek(pb, left, SEEK_CUR); } } total_size += a.size; } if (total_size < atom.size && atom.size < 0x7ffff) avio_skip(pb, atom.size - total_size); c->atom_depth --; return 0; } static int mov_probe(AVProbeData *p) { int64_t offset; uint32_t tag; int score = 0; int moov_offset = -1; /* check file header */ offset = 0; for (;;) { /* ignore invalid offset */ if ((offset + 8) > (unsigned int)p->buf_size) break; tag = AV_RL32(p->buf + offset + 4); switch(tag) { /* check for obvious tags */ case MKTAG('m','o','o','v'): moov_offset = offset + 4; case MKTAG('m','d','a','t'): case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */ case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */ case MKTAG('f','t','y','p'): if (AV_RB32(p->buf+offset) < 8 && (AV_RB32(p->buf+offset) != 1 || offset + 12 > (unsigned int)p->buf_size || AV_RB64(p->buf+offset + 8) == 0)) { score = FFMAX(score, AVPROBE_SCORE_EXTENSION); } else if (tag == MKTAG('f','t','y','p') && ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ') || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ') )) { score = FFMAX(score, 5); } else { score = AVPROBE_SCORE_MAX; } offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; break; /* those are more common words, so rate then a bit less */ case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */ case MKTAG('w','i','d','e'): case MKTAG('f','r','e','e'): case MKTAG('j','u','n','k'): case MKTAG('p','i','c','t'): score = FFMAX(score, AVPROBE_SCORE_MAX - 5); offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; break; case MKTAG(0x82,0x82,0x7f,0x7d): case MKTAG('s','k','i','p'): case MKTAG('u','u','i','d'): case MKTAG('p','r','f','l'): /* if we only find those cause probedata is too small at least rate them */ score = FFMAX(score, AVPROBE_SCORE_EXTENSION); offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; break; default: offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; } } if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) { /* moov atom in the header - we should make sure that this is not a * MOV-packed MPEG-PS */ offset = moov_offset; while(offset < (p->buf_size - 16)){ /* Sufficient space */ /* We found an actual hdlr atom */ if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') && AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') && AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){ av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n"); /* We found a media handler reference atom describing an * MPEG-PS-in-MOV, return a * low score to force expanding the probe window until * mpegps_probe finds what it needs */ return 5; }else /* Keep looking */ offset+=2; } } return score; } // must be done after parsing all trak because there's no order requirement static void mov_read_chapters(AVFormatContext *s) { MOVContext *mov = s->priv_data; AVStream *st; MOVStreamContext *sc; int64_t cur_pos; int i, j; int chapter_track; for (j = 0; j < mov->nb_chapter_tracks; j++) { chapter_track = mov->chapter_tracks[j]; st = NULL; for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->id == chapter_track) { st = s->streams[i]; break; } if (!st) { av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n"); continue; } sc = st->priv_data; cur_pos = avio_tell(sc->pb); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS; if (st->nb_index_entries) { // Retrieve the first frame, if possible AVPacket pkt; AVIndexEntry *sample = &st->index_entries[0]; if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) { av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n"); goto finish; } if (av_get_packet(sc->pb, &pkt, sample->size) < 0) goto finish; st->attached_pic = pkt; st->attached_pic.stream_index = st->index; st->attached_pic.flags |= AV_PKT_FLAG_KEY; } } else { st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA; st->discard = AVDISCARD_ALL; for (i = 0; i < st->nb_index_entries; i++) { AVIndexEntry *sample = &st->index_entries[i]; int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration; uint8_t *title; uint16_t ch; int len, title_len; if (end < sample->timestamp) { av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n"); end = AV_NOPTS_VALUE; } if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) { av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i); goto finish; } // the first two bytes are the length of the title len = avio_rb16(sc->pb); if (len > sample->size-2) continue; title_len = 2*len + 1; if (!(title = av_mallocz(title_len))) goto finish; // The samples could theoretically be in any encoding if there's an encd // atom following, but in practice are only utf-8 or utf-16, distinguished // instead by the presence of a BOM if (!len) { title[0] = 0; } else { ch = avio_rb16(sc->pb); if (ch == 0xfeff) avio_get_str16be(sc->pb, len, title, title_len); else if (ch == 0xfffe) avio_get_str16le(sc->pb, len, title, title_len); else { AV_WB16(title, ch); if (len == 1 || len == 2) title[len] = 0; else avio_get_str(sc->pb, INT_MAX, title + 2, len - 1); } } avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title); av_freep(&title); } } finish: avio_seek(sc->pb, cur_pos, SEEK_SET); } } static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st, uint32_t value, int flags) { AVTimecode tc; char buf[AV_TIMECODE_STR_SIZE]; AVRational rate = st->avg_frame_rate; int ret = av_timecode_init(&tc, rate, flags, 0, s); if (ret < 0) return ret; av_dict_set(&st->metadata, "timecode", av_timecode_make_string(&tc, buf, value), 0); return 0; } static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st) { MOVStreamContext *sc = st->priv_data; char buf[AV_TIMECODE_STR_SIZE]; int64_t cur_pos = avio_tell(sc->pb); int hh, mm, ss, ff, drop; if (!st->nb_index_entries) return -1; avio_seek(sc->pb, st->index_entries->pos, SEEK_SET); avio_skip(s->pb, 13); hh = avio_r8(s->pb); mm = avio_r8(s->pb); ss = avio_r8(s->pb); drop = avio_r8(s->pb); ff = avio_r8(s->pb); snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d", hh, mm, ss, drop ? ';' : ':', ff); av_dict_set(&st->metadata, "timecode", buf, 0); avio_seek(sc->pb, cur_pos, SEEK_SET); return 0; } static int mov_read_timecode_track(AVFormatContext *s, AVStream *st) { MOVStreamContext *sc = st->priv_data; int flags = 0; int64_t cur_pos = avio_tell(sc->pb); uint32_t value; if (!st->nb_index_entries) return -1; avio_seek(sc->pb, st->index_entries->pos, SEEK_SET); value = avio_rb32(s->pb); if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME; if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX; if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE; /* Assume Counter flag is set to 1 in tmcd track (even though it is likely * not the case) and thus assume "frame number format" instead of QT one. * No sample with tmcd track can be found with a QT timecode at the moment, * despite what the tmcd track "suggests" (Counter flag set to 0 means QT * format). */ parse_timecode_in_framenum_format(s, st, value, flags); avio_seek(sc->pb, cur_pos, SEEK_SET); return 0; } static int mov_read_close(AVFormatContext *s) { MOVContext *mov = s->priv_data; int i, j; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (!sc) continue; av_freep(&sc->ctts_data); for (j = 0; j < sc->drefs_count; j++) { av_freep(&sc->drefs[j].path); av_freep(&sc->drefs[j].dir); } av_freep(&sc->drefs); sc->drefs_count = 0; if (!sc->pb_is_copied) ff_format_io_close(s, &sc->pb); sc->pb = NULL; av_freep(&sc->chunk_offsets); av_freep(&sc->stsc_data); av_freep(&sc->sample_sizes); av_freep(&sc->keyframes); av_freep(&sc->stts_data); av_freep(&sc->stps_data); av_freep(&sc->elst_data); av_freep(&sc->rap_group); av_freep(&sc->display_matrix); av_freep(&sc->index_ranges); if (sc->extradata) for (j = 0; j < sc->stsd_count; j++) av_free(sc->extradata[j]); av_freep(&sc->extradata); av_freep(&sc->extradata_size); av_freep(&sc->cenc.auxiliary_info); av_freep(&sc->cenc.auxiliary_info_sizes); av_aes_ctr_free(sc->cenc.aes_ctr); av_freep(&sc->stereo3d); av_freep(&sc->spherical); av_freep(&sc->mastering); av_freep(&sc->coll); } if (mov->dv_demux) { avformat_free_context(mov->dv_fctx); mov->dv_fctx = NULL; } if (mov->meta_keys) { for (i = 1; i < mov->meta_keys_count; i++) { av_freep(&mov->meta_keys[i]); } av_freep(&mov->meta_keys); } av_freep(&mov->trex_data); av_freep(&mov->bitrates); for (i = 0; i < mov->fragment_index_count; i++) { MOVFragmentIndex* index = mov->fragment_index_data[i]; av_freep(&index->items); av_freep(&mov->fragment_index_data[i]); } av_freep(&mov->fragment_index_data); av_freep(&mov->aes_decrypt); av_freep(&mov->chapter_tracks); return 0; } static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id) { int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->timecode_track == tmcd_id) return 1; } return 0; } /* look for a tmcd track not referenced by any video track, and export it globally */ static void export_orphan_timecode(AVFormatContext *s) { int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d') && !tmcd_is_referenced(s, i + 1)) { AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0); if (tcr) { av_dict_set(&s->metadata, "timecode", tcr->value, 0); break; } } } } static int read_tfra(MOVContext *mov, AVIOContext *f) { MOVFragmentIndex* index = NULL; int version, fieldlength, i, j; int64_t pos = avio_tell(f); uint32_t size = avio_rb32(f); void *tmp; if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) { return 1; } av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n"); index = av_mallocz(sizeof(MOVFragmentIndex)); if (!index) { return AVERROR(ENOMEM); } tmp = av_realloc_array(mov->fragment_index_data, mov->fragment_index_count + 1, sizeof(MOVFragmentIndex*)); if (!tmp) { av_freep(&index); return AVERROR(ENOMEM); } mov->fragment_index_data = tmp; mov->fragment_index_data[mov->fragment_index_count++] = index; version = avio_r8(f); avio_rb24(f); index->track_id = avio_rb32(f); fieldlength = avio_rb32(f); index->item_count = avio_rb32(f); index->items = av_mallocz_array( index->item_count, sizeof(MOVFragmentIndexItem)); if (!index->items) { index->item_count = 0; return AVERROR(ENOMEM); } for (i = 0; i < index->item_count; i++) { int64_t time, offset; if (version == 1) { time = avio_rb64(f); offset = avio_rb64(f); } else { time = avio_rb32(f); offset = avio_rb32(f); } index->items[i].time = time; index->items[i].moof_offset = offset; for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++) avio_r8(f); } avio_seek(f, pos + size, SEEK_SET); return 0; } static int mov_read_mfra(MOVContext *c, AVIOContext *f) { int64_t stream_size = avio_size(f); int64_t original_pos = avio_tell(f); int64_t seek_ret; int32_t mfra_size; int ret = -1; if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) { ret = seek_ret; goto fail; } mfra_size = avio_rb32(f); if (mfra_size < 0 || mfra_size > stream_size) { av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n"); goto fail; } if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) { ret = seek_ret; goto fail; } if (avio_rb32(f) != mfra_size) { av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n"); goto fail; } if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) { av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n"); goto fail; } av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n"); do { ret = read_tfra(c, f); if (ret < 0) goto fail; } while (!ret); ret = 0; fail: seek_ret = avio_seek(f, original_pos, SEEK_SET); if (seek_ret < 0) { av_log(c->fc, AV_LOG_ERROR, "failed to seek back after looking for mfra\n"); ret = seek_ret; } return ret; } static int mov_read_header(AVFormatContext *s) { MOVContext *mov = s->priv_data; AVIOContext *pb = s->pb; int j, err; MOVAtom atom = { AV_RL32("root") }; int i; if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n", mov->decryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } mov->fc = s; mov->trak_index = -1; /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */ if (pb->seekable & AVIO_SEEKABLE_NORMAL) atom.size = avio_size(pb); else atom.size = INT64_MAX; /* check MOV header */ do { if (mov->moov_retry) avio_seek(pb, 0, SEEK_SET); if ((err = mov_read_default(mov, pb, atom)) < 0) { av_log(s, AV_LOG_ERROR, "error reading header\n"); mov_read_close(s); return err; } } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++); if (!mov->found_moov) { av_log(s, AV_LOG_ERROR, "moov atom not found\n"); mov_read_close(s); return AVERROR_INVALIDDATA; } av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb)); if (pb->seekable & AVIO_SEEKABLE_NORMAL) { if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters) mov_read_chapters(s); for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) { mov_read_timecode_track(s, s->streams[i]); } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) { mov_read_rtmd_track(s, s->streams[i]); } } /* copy timecode metadata from tmcd tracks to the related video streams */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (sc->timecode_track > 0) { AVDictionaryEntry *tcr; int tmcd_st_id = -1; for (j = 0; j < s->nb_streams; j++) if (s->streams[j]->id == sc->timecode_track) tmcd_st_id = j; if (tmcd_st_id < 0 || tmcd_st_id == i) continue; tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0); if (tcr) av_dict_set(&st->metadata, "timecode", tcr->value, 0); } } export_orphan_timecode(s); for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; fix_timescale(mov, sc); if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) { st->skip_samples = sc->start_pad; } if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0) av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den, sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX); if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (st->codecpar->width <= 0 || st->codecpar->height <= 0) { st->codecpar->width = sc->width; st->codecpar->height = sc->height; } if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) { if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0) return err; } } if (mov->handbrake_version && mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2 st->codecpar->codec_id == AV_CODEC_ID_MP3 ) { av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n"); st->need_parsing = AVSTREAM_PARSE_FULL; } } if (mov->trex_data) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (st->duration > 0) { if (sc->data_size > INT64_MAX / sc->time_scale / 8) { av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n", sc->data_size, sc->time_scale); mov_read_close(s); return AVERROR_INVALIDDATA; } st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration; } } } if (mov->use_mfra_for > 0) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (sc->duration_for_fps > 0) { if (sc->data_size > INT64_MAX / sc->time_scale / 8) { av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n", sc->data_size, sc->time_scale); mov_read_close(s); return AVERROR_INVALIDDATA; } st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / sc->duration_for_fps; } } } for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) { if (mov->bitrates[i]) { s->streams[i]->codecpar->bit_rate = mov->bitrates[i]; } } ff_rfps_calculate(s); for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; switch (st->codecpar->codec_type) { case AVMEDIA_TYPE_AUDIO: err = ff_replaygain_export(st, s->metadata); if (err < 0) { mov_read_close(s); return err; } break; case AVMEDIA_TYPE_VIDEO: if (sc->display_matrix) { err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix, sizeof(int32_t) * 9); if (err < 0) return err; sc->display_matrix = NULL; } if (sc->stereo3d) { err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D, (uint8_t *)sc->stereo3d, sizeof(*sc->stereo3d)); if (err < 0) return err; sc->stereo3d = NULL; } if (sc->spherical) { err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL, (uint8_t *)sc->spherical, sc->spherical_size); if (err < 0) return err; sc->spherical = NULL; } if (sc->mastering) { err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)sc->mastering, sizeof(*sc->mastering)); if (err < 0) return err; sc->mastering = NULL; } if (sc->coll) { err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)sc->coll, sc->coll_size); if (err < 0) return err; sc->coll = NULL; } break; } } ff_configure_buffers_for_index(s, AV_TIME_BASE); for (i = 0; i < mov->fragment_index_count; i++) { MOVFragmentIndex *idx = mov->fragment_index_data[i]; for (j = 0; j < idx->item_count; j++) if (idx->items[j].moof_offset <= mov->fragment.moof_offset) idx->items[j].headers_read = 1; } return 0; } static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st) { AVIndexEntry *sample = NULL; int64_t best_dts = INT64_MAX; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *avst = s->streams[i]; MOVStreamContext *msc = avst->priv_data; if (msc->pb && msc->current_sample < avst->nb_index_entries) { AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample]; int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale); av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts); if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) || ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) || (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) { sample = current_sample; best_dts = dts; *st = avst; } } } return sample; } static int should_retry(AVIOContext *pb, int error_code) { if (error_code == AVERROR_EOF || avio_feof(pb)) return 0; return 1; } static int mov_switch_root(AVFormatContext *s, int64_t target) { MOVContext *mov = s->priv_data; int i, j; int already_read = 0; if (avio_seek(s->pb, target, SEEK_SET) != target) { av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target); return AVERROR_INVALIDDATA; } mov->next_root_atom = 0; for (i = 0; i < mov->fragment_index_count; i++) { MOVFragmentIndex *index = mov->fragment_index_data[i]; int found = 0; for (j = 0; j < index->item_count; j++) { MOVFragmentIndexItem *item = &index->items[j]; if (found) { mov->next_root_atom = item->moof_offset; break; // Advance to next index in outer loop } else if (item->moof_offset == target) { index->current_item = FFMIN(j, index->current_item); if (item->headers_read) already_read = 1; item->headers_read = 1; found = 1; } } if (!found) index->current_item = 0; } if (already_read) return 0; mov->found_mdat = 0; if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 || avio_feof(s->pb)) return AVERROR_EOF; av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb)); return 1; } static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt) { uint8_t *side, *extradata; int extradata_size; /* Save the current index. */ sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1; /* Notify the decoder that extradata changed. */ extradata_size = sc->extradata_size[sc->last_stsd_index]; extradata = sc->extradata[sc->last_stsd_index]; if (extradata_size > 0 && extradata) { side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, extradata_size); if (!side) return AVERROR(ENOMEM); memcpy(side, extradata, extradata_size); } return 0; } static int mov_read_packet(AVFormatContext *s, AVPacket *pkt) { MOVContext *mov = s->priv_data; MOVStreamContext *sc; AVIndexEntry *sample; AVStream *st = NULL; int64_t current_index; int ret; mov->fc = s; retry: sample = mov_find_next_sample(s, &st); if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) { if (!mov->next_root_atom) return AVERROR_EOF; if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0) return ret; goto retry; } sc = st->priv_data; /* must be done just before reading, to avoid infinite loop on sample */ current_index = sc->current_index; mov_current_sample_inc(sc); if (mov->next_root_atom) { sample->pos = FFMIN(sample->pos, mov->next_root_atom); sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos)); } if (st->discard != AVDISCARD_ALL) { int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET); if (ret64 != sample->pos) { av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n", sc->ffindex, sample->pos); if (should_retry(sc->pb, ret64)) { mov_current_sample_dec(sc); } return AVERROR_INVALIDDATA; } if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) { av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex); goto retry; } ret = av_get_packet(sc->pb, pkt, sample->size); if (ret < 0) { if (should_retry(sc->pb, ret)) { mov_current_sample_dec(sc); } return ret; } if (sc->has_palette) { uint8_t *pal; pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); if (!pal) { av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n"); } else { memcpy(pal, sc->palette, AVPALETTE_SIZE); sc->has_palette = 0; } } #if CONFIG_DV_DEMUXER if (mov->dv_demux && sc->dv_audio_container) { avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos); av_freep(&pkt->data); pkt->size = 0; ret = avpriv_dv_get_packet(mov->dv_demux, pkt); if (ret < 0) return ret; } #endif if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) { if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0) st->need_parsing = AVSTREAM_PARSE_FULL; } } pkt->stream_index = sc->ffindex; pkt->dts = sample->timestamp; if (sample->flags & AVINDEX_DISCARD_FRAME) { pkt->flags |= AV_PKT_FLAG_DISCARD; } if (sc->ctts_data && sc->ctts_index < sc->ctts_count) { pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration; /* update ctts context */ sc->ctts_sample++; if (sc->ctts_index < sc->ctts_count && sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) { sc->ctts_index++; sc->ctts_sample = 0; } } else { int64_t next_dts = (sc->current_sample < st->nb_index_entries) ? st->index_entries[sc->current_sample].timestamp : st->duration; pkt->duration = next_dts - pkt->dts; pkt->pts = pkt->dts; } if (st->discard == AVDISCARD_ALL) goto retry; pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0; pkt->pos = sample->pos; /* Multiple stsd handling. */ if (sc->stsc_data) { /* Keep track of the stsc index for the given sample, then check * if the stsd index is different from the last used one. */ sc->stsc_sample++; if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) && mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) { sc->stsc_index++; sc->stsc_sample = 0; /* Do not check indexes after a switch. */ } else if (sc->stsc_data[sc->stsc_index].id > 0 && sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count && sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) { ret = mov_change_extradata(sc, pkt); if (ret < 0) return ret; } } if (mov->aax_mode) aax_filter(pkt->data, pkt->size, mov); if (sc->cenc.aes_ctr) { ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size); if (ret) { return ret; } } return 0; } static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp) { MOVContext *mov = s->priv_data; MOVStreamContext *sc = st->priv_data; int i, j; if (!mov->fragment_index_complete) return 0; for (i = 0; i < mov->fragment_index_count; i++) { if (mov->fragment_index_data[i]->track_id == st->id || !sc->has_sidx) { MOVFragmentIndex *index = mov->fragment_index_data[i]; for (j = index->item_count - 1; j >= 0; j--) { if (index->items[j].time <= timestamp) { if (index->items[j].headers_read) return 0; return mov_switch_root(s, index->items[j].moof_offset); } } } } return 0; } static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags) { MOVStreamContext *sc = st->priv_data; int sample, time_sample; int i; int ret = mov_seek_fragment(s, st, timestamp); if (ret < 0) return ret; sample = av_index_search_timestamp(st, timestamp, flags); av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample); if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp) sample = 0; if (sample < 0) /* not sure what to do */ return AVERROR_INVALIDDATA; mov_current_sample_set(sc, sample); av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample); /* adjust ctts index */ if (sc->ctts_data) { time_sample = 0; for (i = 0; i < sc->ctts_count; i++) { int next = time_sample + sc->ctts_data[i].count; if (next > sc->current_sample) { sc->ctts_index = i; sc->ctts_sample = sc->current_sample - time_sample; break; } time_sample = next; } } /* adjust stsd index */ time_sample = 0; for (i = 0; i < sc->stsc_count; i++) { int next = time_sample + mov_get_stsc_samples(sc, i); if (next > sc->current_sample) { sc->stsc_index = i; sc->stsc_sample = sc->current_sample - time_sample; break; } time_sample = next; } return sample; } static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { MOVContext *mc = s->priv_data; AVStream *st; int sample; int i; if (stream_index >= s->nb_streams) return AVERROR_INVALIDDATA; st = s->streams[stream_index]; sample = mov_seek_stream(s, st, sample_time, flags); if (sample < 0) return sample; if (mc->seek_individually) { /* adjust seek timestamp to found sample timestamp */ int64_t seek_timestamp = st->index_entries[sample].timestamp; for (i = 0; i < s->nb_streams; i++) { int64_t timestamp; MOVStreamContext *sc = s->streams[i]->priv_data; st = s->streams[i]; st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0; if (stream_index == i) continue; timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base); mov_seek_stream(s, st, timestamp, flags); } } else { for (i = 0; i < s->nb_streams; i++) { MOVStreamContext *sc; st = s->streams[i]; sc = st->priv_data; mov_current_sample_set(sc, 0); } while (1) { MOVStreamContext *sc; AVIndexEntry *entry = mov_find_next_sample(s, &st); if (!entry) return AVERROR_INVALIDDATA; sc = st->priv_data; if (sc->ffindex == stream_index && sc->current_sample == sample) break; mov_current_sample_inc(sc); } } return 0; } #define OFFSET(x) offsetof(MOVContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption mov_options[] = { {"use_absolute_path", "allow using absolute path when opening alias, this is a possible security issue", OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS}, {"seek_streams_individually", "Seek each stream individually to the to the closest point", OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS}, {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS}, {"advanced_editlist", "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.", OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS}, {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS}, {"use_mfra_for", "use mfra for fragment timestamps", OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, -1, FF_MOV_FLAG_MFRA_PTS, FLAGS, "use_mfra_for"}, {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0, FLAGS, "use_mfra_for" }, {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0, FLAGS, "use_mfra_for" }, {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0, FLAGS, "use_mfra_for" }, { "export_all", "Export unrecognized metadata entries", OFFSET(export_all), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS }, { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS }, { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM }, { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files! "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key), AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"}, .flags = AV_OPT_FLAG_DECODING_PARAM }, { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM }, { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS }, { NULL }, }; static const AVClass mov_class = { .class_name = "mov,mp4,m4a,3gp,3g2,mj2", .item_name = av_default_item_name, .option = mov_options, .version = LIBAVUTIL_VERSION_INT, }; AVInputFormat ff_mov_demuxer = { .name = "mov,mp4,m4a,3gp,3g2,mj2", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .priv_class = &mov_class, .priv_data_size = sizeof(MOVContext), .extensions = "mov,mp4,m4a,3gp,3g2,mj2", .read_probe = mov_probe, .read_header = mov_read_header, .read_packet = mov_read_packet, .read_close = mov_read_close, .read_seek = mov_read_seek, .flags = AVFMT_NO_BYTE_SEEK, };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2786_0
crossvul-cpp_data_bad_2779_0
/* * MXF demuxer. * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * References * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value * SMPTE 377M MXF File Format Specifications * SMPTE 378M Operational Pattern 1a * SMPTE 379M MXF Generic Container * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container * * Principle * Search for Track numbers which will identify essence element KLV packets. * Search for SourcePackage which define tracks which contains Track numbers. * Material Package contains tracks with reference to SourcePackage tracks. * Search for Descriptors (Picture, Sound) which contains codec info and parameters. * Assign Descriptors to correct Tracks. * * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext. * Metadata parsing resolves Strong References to objects. * * Simple demuxer, only OP1A supported and some files might not work at all. * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1 */ #include <inttypes.h> #include "libavutil/aes.h" #include "libavutil/avassert.h" #include "libavutil/mathematics.h" #include "libavcodec/bytestream.h" #include "libavutil/intreadwrite.h" #include "libavutil/parseutils.h" #include "libavutil/timecode.h" #include "avformat.h" #include "internal.h" #include "mxf.h" typedef enum { Header, BodyPartition, Footer } MXFPartitionType; typedef enum { OP1a = 1, OP1b, OP1c, OP2a, OP2b, OP2c, OP3a, OP3b, OP3c, OPAtom, OPSONYOpt, /* FATE sample, violates the spec in places */ } MXFOP; typedef struct MXFPartition { int closed; int complete; MXFPartitionType type; uint64_t previous_partition; int index_sid; int body_sid; int64_t this_partition; int64_t essence_offset; ///< absolute offset of essence int64_t essence_length; int32_t kag_size; int64_t header_byte_count; int64_t index_byte_count; int pack_length; int64_t pack_ofs; ///< absolute offset of pack in file, including run-in } MXFPartition; typedef struct MXFCryptoContext { UID uid; enum MXFMetadataSetType type; UID source_container_ul; } MXFCryptoContext; typedef struct MXFStructuralComponent { UID uid; enum MXFMetadataSetType type; UID source_package_ul; UID source_package_uid; UID data_definition_ul; int64_t duration; int64_t start_position; int source_track_id; } MXFStructuralComponent; typedef struct MXFSequence { UID uid; enum MXFMetadataSetType type; UID data_definition_ul; UID *structural_components_refs; int structural_components_count; int64_t duration; uint8_t origin; } MXFSequence; typedef struct MXFTrack { UID uid; enum MXFMetadataSetType type; int drop_frame; int start_frame; struct AVRational rate; AVTimecode tc; } MXFTimecodeComponent; typedef struct { UID uid; enum MXFMetadataSetType type; UID input_segment_ref; } MXFPulldownComponent; typedef struct { UID uid; enum MXFMetadataSetType type; UID *structural_components_refs; int structural_components_count; int64_t duration; } MXFEssenceGroup; typedef struct { UID uid; enum MXFMetadataSetType type; char *name; char *value; } MXFTaggedValue; typedef struct { UID uid; enum MXFMetadataSetType type; MXFSequence *sequence; /* mandatory, and only one */ UID sequence_ref; int track_id; char *name; uint8_t track_number[4]; AVRational edit_rate; int intra_only; uint64_t sample_count; int64_t original_duration; /* st->duration in SampleRate/EditRate units */ } MXFTrack; typedef struct MXFDescriptor { UID uid; enum MXFMetadataSetType type; UID essence_container_ul; UID essence_codec_ul; UID codec_ul; AVRational sample_rate; AVRational aspect_ratio; int width; int height; /* Field height, not frame height */ int frame_layout; /* See MXFFrameLayout enum */ int video_line_map[2]; #define MXF_FIELD_DOMINANCE_DEFAULT 0 #define MXF_FIELD_DOMINANCE_FF 1 /* coded first, displayed first */ #define MXF_FIELD_DOMINANCE_FL 2 /* coded first, displayed last */ int field_dominance; int channels; int bits_per_sample; int64_t duration; /* ContainerDuration optional property */ unsigned int component_depth; unsigned int horiz_subsampling; unsigned int vert_subsampling; UID *sub_descriptors_refs; int sub_descriptors_count; int linked_track_id; uint8_t *extradata; int extradata_size; enum AVPixelFormat pix_fmt; } MXFDescriptor; typedef struct MXFIndexTableSegment { UID uid; enum MXFMetadataSetType type; int edit_unit_byte_count; int index_sid; int body_sid; AVRational index_edit_rate; uint64_t index_start_position; uint64_t index_duration; int8_t *temporal_offset_entries; int *flag_entries; uint64_t *stream_offset_entries; int nb_index_entries; } MXFIndexTableSegment; typedef struct MXFPackage { UID uid; enum MXFMetadataSetType type; UID package_uid; UID package_ul; UID *tracks_refs; int tracks_count; MXFDescriptor *descriptor; /* only one */ UID descriptor_ref; char *name; UID *comment_refs; int comment_count; } MXFPackage; typedef struct MXFMetadataSet { UID uid; enum MXFMetadataSetType type; } MXFMetadataSet; /* decoded index table */ typedef struct MXFIndexTable { int index_sid; int body_sid; int nb_ptses; /* number of PTSes or total duration of index */ int64_t first_dts; /* DTS = EditUnit + first_dts */ int64_t *ptses; /* maps EditUnit -> PTS */ int nb_segments; MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */ AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */ int8_t *offsets; /* temporal offsets for display order to stored order conversion */ } MXFIndexTable; typedef struct MXFContext { MXFPartition *partitions; unsigned partitions_count; MXFOP op; UID *packages_refs; int packages_count; MXFMetadataSet **metadata_sets; int metadata_sets_count; AVFormatContext *fc; struct AVAES *aesc; uint8_t *local_tags; int local_tags_count; uint64_t footer_partition; KLVPacket current_klv_data; int current_klv_index; int run_in; MXFPartition *current_partition; int parsing_backward; int64_t last_forward_tell; int last_forward_partition; int current_edit_unit; int nb_index_tables; MXFIndexTable *index_tables; int edit_units_per_packet; ///< how many edit units to read at a time (PCM, OPAtom) } MXFContext; enum MXFWrappingScheme { Frame, Clip, }; /* NOTE: klv_offset is not set (-1) for local keys */ typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset); typedef struct MXFMetadataReadTableEntry { const UID key; MXFMetadataReadFunc *read; int ctx_size; enum MXFMetadataSetType type; } MXFMetadataReadTableEntry; static int mxf_read_close(AVFormatContext *s); /* partial keys to match */ static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 }; static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 }; static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 }; static const uint8_t mxf_canopus_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x0a,0x0e,0x0f,0x03,0x01 }; static const uint8_t mxf_system_item_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 }; static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 }; /* complete keys to match */ static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 }; static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 }; static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 }; static const uint8_t mxf_random_index_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x11,0x01,0x00 }; static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 }; static const uint8_t mxf_avid_project_name[] = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf }; static const uint8_t mxf_jp2k_rsiz[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }; static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 }; static const uint8_t mxf_indirect_value_utf16be[] = { 0x42,0x01,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 }; #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y))) static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx) { MXFIndexTableSegment *seg; switch ((*ctx)->type) { case Descriptor: av_freep(&((MXFDescriptor *)*ctx)->extradata); break; case MultipleDescriptor: av_freep(&((MXFDescriptor *)*ctx)->sub_descriptors_refs); break; case Sequence: av_freep(&((MXFSequence *)*ctx)->structural_components_refs); break; case EssenceGroup: av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs); break; case SourcePackage: case MaterialPackage: av_freep(&((MXFPackage *)*ctx)->tracks_refs); av_freep(&((MXFPackage *)*ctx)->name); av_freep(&((MXFPackage *)*ctx)->comment_refs); break; case TaggedValue: av_freep(&((MXFTaggedValue *)*ctx)->name); av_freep(&((MXFTaggedValue *)*ctx)->value); break; case Track: av_freep(&((MXFTrack *)*ctx)->name); break; case IndexTableSegment: seg = (MXFIndexTableSegment *)*ctx; av_freep(&seg->temporal_offset_entries); av_freep(&seg->flag_entries); av_freep(&seg->stream_offset_entries); default: break; } if (freectx) av_freep(ctx); } static int64_t klv_decode_ber_length(AVIOContext *pb) { uint64_t size = avio_r8(pb); if (size & 0x80) { /* long form */ int bytes_num = size & 0x7f; /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */ if (bytes_num > 8) return AVERROR_INVALIDDATA; size = 0; while (bytes_num--) size = size << 8 | avio_r8(pb); } return size; } static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size) { int i, b; for (i = 0; i < size && !avio_feof(pb); i++) { b = avio_r8(pb); if (b == key[0]) i = 0; else if (b != key[i]) i = -1; } return i == size; } static int klv_read_packet(KLVPacket *klv, AVIOContext *pb) { if (!mxf_read_sync(pb, mxf_klv_key, 4)) return AVERROR_INVALIDDATA; klv->offset = avio_tell(pb) - 4; memcpy(klv->key, mxf_klv_key, 4); avio_read(pb, klv->key + 4, 12); klv->length = klv_decode_ber_length(pb); return klv->length == -1 ? -1 : 0; } static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv) { int i; for (i = 0; i < s->nb_streams; i++) { MXFTrack *track = s->streams[i]->priv_data; /* SMPTE 379M 7.3 */ if (track && !memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number))) return i; } /* return 0 if only one stream, for OP Atom files with 0 as track number */ return s->nb_streams == 1 ? 0 : -1; } /* XXX: use AVBitStreamFilter */ static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length) { const uint8_t *buf_ptr, *end_ptr; uint8_t *data_ptr; int i; if (length > 61444) /* worst case PAL 1920 samples 8 channels */ return AVERROR_INVALIDDATA; length = av_get_packet(pb, pkt, length); if (length < 0) return length; data_ptr = pkt->data; end_ptr = pkt->data + length; buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */ for (; end_ptr - buf_ptr >= st->codecpar->channels * 4; ) { for (i = 0; i < st->codecpar->channels; i++) { uint32_t sample = bytestream_get_le32(&buf_ptr); if (st->codecpar->bits_per_coded_sample == 24) bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff); else bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff); } buf_ptr += 32 - st->codecpar->channels*4; // always 8 channels stored SMPTE 331M } av_shrink_packet(pkt, data_ptr - pkt->data); return 0; } static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv) { static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b}; MXFContext *mxf = s->priv_data; AVIOContext *pb = s->pb; int64_t end = avio_tell(pb) + klv->length; int64_t size; uint64_t orig_size; uint64_t plaintext_size; uint8_t ivec[16]; uint8_t tmpbuf[16]; int index; if (!mxf->aesc && s->key && s->keylen == 16) { mxf->aesc = av_aes_alloc(); if (!mxf->aesc) return AVERROR(ENOMEM); av_aes_init(mxf->aesc, s->key, 128, 1); } // crypto context avio_skip(pb, klv_decode_ber_length(pb)); // plaintext offset klv_decode_ber_length(pb); plaintext_size = avio_rb64(pb); // source klv key klv_decode_ber_length(pb); avio_read(pb, klv->key, 16); if (!IS_KLV_KEY(klv, mxf_essence_element_key)) return AVERROR_INVALIDDATA; index = mxf_get_stream_index(s, klv); if (index < 0) return AVERROR_INVALIDDATA; // source size klv_decode_ber_length(pb); orig_size = avio_rb64(pb); if (orig_size < plaintext_size) return AVERROR_INVALIDDATA; // enc. code size = klv_decode_ber_length(pb); if (size < 32 || size - 32 < orig_size) return AVERROR_INVALIDDATA; avio_read(pb, ivec, 16); avio_read(pb, tmpbuf, 16); if (mxf->aesc) av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1); if (memcmp(tmpbuf, checkv, 16)) av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n"); size -= 32; size = av_get_packet(pb, pkt, size); if (size < 0) return size; else if (size < plaintext_size) return AVERROR_INVALIDDATA; size -= plaintext_size; if (mxf->aesc) av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size], &pkt->data[plaintext_size], size >> 4, ivec, 1); av_shrink_packet(pkt, orig_size); pkt->stream_index = index; avio_skip(pb, end - avio_tell(pb)); return 0; } static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; int item_num = avio_rb32(pb); int item_len = avio_rb32(pb); if (item_len != 18) { avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } if (item_num > 65536) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } if (mxf->local_tags) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n"); av_free(mxf->local_tags); mxf->local_tags_count = 0; mxf->local_tags = av_calloc(item_num, item_len); if (!mxf->local_tags) return AVERROR(ENOMEM); mxf->local_tags_count = item_num; avio_read(pb, mxf->local_tags, item_num*item_len); return 0; } static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; MXFPartition *partition, *tmp_part; UID op; uint64_t footer_partition; uint32_t nb_essence_containers; tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions)); if (!tmp_part) return AVERROR(ENOMEM); mxf->partitions = tmp_part; if (mxf->parsing_backward) { /* insert the new partition pack in the middle * this makes the entries in mxf->partitions sorted by offset */ memmove(&mxf->partitions[mxf->last_forward_partition+1], &mxf->partitions[mxf->last_forward_partition], (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions)); partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition]; } else { mxf->last_forward_partition++; partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count]; } memset(partition, 0, sizeof(*partition)); mxf->partitions_count++; partition->pack_length = avio_tell(pb) - klv_offset + size; partition->pack_ofs = klv_offset; switch(uid[13]) { case 2: partition->type = Header; break; case 3: partition->type = BodyPartition; break; case 4: partition->type = Footer; break; default: av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]); return AVERROR_INVALIDDATA; } /* consider both footers to be closed (there is only Footer and CompleteFooter) */ partition->closed = partition->type == Footer || !(uid[14] & 1); partition->complete = uid[14] > 2; avio_skip(pb, 4); partition->kag_size = avio_rb32(pb); partition->this_partition = avio_rb64(pb); partition->previous_partition = avio_rb64(pb); footer_partition = avio_rb64(pb); partition->header_byte_count = avio_rb64(pb); partition->index_byte_count = avio_rb64(pb); partition->index_sid = avio_rb32(pb); avio_skip(pb, 8); partition->body_sid = avio_rb32(pb); if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) { av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n"); return AVERROR_INVALIDDATA; } nb_essence_containers = avio_rb32(pb); if (partition->this_partition && partition->previous_partition == partition->this_partition) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition equal to ThisPartition %"PRIx64"\n", partition->previous_partition); /* override with the actual previous partition offset */ if (!mxf->parsing_backward && mxf->last_forward_partition > 1) { MXFPartition *prev = mxf->partitions + mxf->last_forward_partition - 2; partition->previous_partition = prev->this_partition; } /* if no previous body partition are found point to the header * partition */ if (partition->previous_partition == partition->this_partition) partition->previous_partition = 0; av_log(mxf->fc, AV_LOG_ERROR, "Overriding PreviousPartition with %"PRIx64"\n", partition->previous_partition); } /* some files don't have FooterPartition set in every partition */ if (footer_partition) { if (mxf->footer_partition && mxf->footer_partition != footer_partition) { av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n", mxf->footer_partition, footer_partition); } else { mxf->footer_partition = footer_partition; } } av_log(mxf->fc, AV_LOG_TRACE, "PartitionPack: ThisPartition = 0x%"PRIX64 ", PreviousPartition = 0x%"PRIX64", " "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n", partition->this_partition, partition->previous_partition, footer_partition, partition->index_sid, partition->body_sid); /* sanity check PreviousPartition if set */ //NOTE: this isn't actually enough, see mxf_seek_to_previous_partition() if (partition->previous_partition && mxf->run_in + partition->previous_partition >= klv_offset) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition points to this partition or forward\n"); return AVERROR_INVALIDDATA; } if (op[12] == 1 && op[13] == 1) mxf->op = OP1a; else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b; else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c; else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a; else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b; else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c; else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a; else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b; else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c; else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt; else if (op[12] == 0x10) { /* SMPTE 390m: "There shall be exactly one essence container" * The following block deals with files that violate this, namely: * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */ if (nb_essence_containers != 1) { MXFOP op = nb_essence_containers ? OP1a : OPAtom; /* only nag once */ if (!mxf->op) av_log(mxf->fc, AV_LOG_WARNING, "\"OPAtom\" with %"PRIu32" ECs - assuming %s\n", nb_essence_containers, op == OP1a ? "OP1a" : "OPAtom"); mxf->op = op; } else mxf->op = OPAtom; } else { av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]); mxf->op = OP1a; } if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) { av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ", partition->kag_size); if (mxf->op == OPSONYOpt) partition->kag_size = 512; else partition->kag_size = 1; av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size); } return 0; } static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set) { MXFMetadataSet **tmp; tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets)); if (!tmp) return AVERROR(ENOMEM); mxf->metadata_sets = tmp; mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set; mxf->metadata_sets_count++; return 0; } static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFCryptoContext *cryptocontext = arg; if (size != 16) return AVERROR_INVALIDDATA; if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul)) avio_read(pb, cryptocontext->source_container_ul, 16); return 0; } static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count) { *count = avio_rb32(pb); *refs = av_calloc(*count, sizeof(UID)); if (!*refs) { *count = 0; return AVERROR(ENOMEM); } avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */ avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID)); return 0; } static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be) { int ret; size_t buf_size; if (size < 0 || size > INT_MAX/2) return AVERROR(EINVAL); buf_size = size + size / 2 + 1; *str = av_malloc(buf_size); if (!*str) return AVERROR(ENOMEM); if (be) ret = avio_get_str16be(pb, size, *str, buf_size); else ret = avio_get_str16le(pb, size, *str, buf_size); if (ret < 0) { av_freep(str); return ret; } return ret; } #define READ_STR16(type, big_endian) \ static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \ { \ return mxf_read_utf16_string(pb, size, str, big_endian); \ } READ_STR16(be, 1) READ_STR16(le, 0) #undef READ_STR16 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; switch (tag) { case 0x1901: if (mxf->packages_refs) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n"); av_free(mxf->packages_refs); return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count); } return 0; } static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFStructuralComponent *source_clip = arg; switch(tag) { case 0x0202: source_clip->duration = avio_rb64(pb); break; case 0x1201: source_clip->start_position = avio_rb64(pb); break; case 0x1101: /* UMID, only get last 16 bytes */ avio_read(pb, source_clip->source_package_ul, 16); avio_read(pb, source_clip->source_package_uid, 16); break; case 0x1102: source_clip->source_track_id = avio_rb32(pb); break; } return 0; } static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFTimecodeComponent *mxf_timecode = arg; switch(tag) { case 0x1501: mxf_timecode->start_frame = avio_rb64(pb); break; case 0x1502: mxf_timecode->rate = (AVRational){avio_rb16(pb), 1}; break; case 0x1503: mxf_timecode->drop_frame = avio_r8(pb); break; } return 0; } static int mxf_read_pulldown_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFPulldownComponent *mxf_pulldown = arg; switch(tag) { case 0x0d01: avio_read(pb, mxf_pulldown->input_segment_ref, 16); break; } return 0; } static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFTrack *track = arg; switch(tag) { case 0x4801: track->track_id = avio_rb32(pb); break; case 0x4804: avio_read(pb, track->track_number, 4); break; case 0x4802: mxf_read_utf16be_string(pb, size, &track->name); break; case 0x4b01: track->edit_rate.num = avio_rb32(pb); track->edit_rate.den = avio_rb32(pb); break; case 0x4803: avio_read(pb, track->sequence_ref, 16); break; } return 0; } static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFSequence *sequence = arg; switch(tag) { case 0x0202: sequence->duration = avio_rb64(pb); break; case 0x0201: avio_read(pb, sequence->data_definition_ul, 16); break; case 0x4b02: sequence->origin = avio_r8(pb); break; case 0x1001: return mxf_read_strong_ref_array(pb, &sequence->structural_components_refs, &sequence->structural_components_count); } return 0; } static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFEssenceGroup *essence_group = arg; switch (tag) { case 0x0202: essence_group->duration = avio_rb64(pb); break; case 0x0501: return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs, &essence_group->structural_components_count); } return 0; } static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFPackage *package = arg; switch(tag) { case 0x4403: return mxf_read_strong_ref_array(pb, &package->tracks_refs, &package->tracks_count); case 0x4401: /* UMID */ avio_read(pb, package->package_ul, 16); avio_read(pb, package->package_uid, 16); break; case 0x4701: avio_read(pb, package->descriptor_ref, 16); break; case 0x4402: return mxf_read_utf16be_string(pb, size, &package->name); case 0x4406: return mxf_read_strong_ref_array(pb, &package->comment_refs, &package->comment_count); } return 0; } static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment) { int i, length; segment->nb_index_entries = avio_rb32(pb); length = avio_rb32(pb); if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) { av_freep(&segment->temporal_offset_entries); av_freep(&segment->flag_entries); return AVERROR(ENOMEM); } for (i = 0; i < segment->nb_index_entries; i++) { segment->temporal_offset_entries[i] = avio_r8(pb); avio_r8(pb); /* KeyFrameOffset */ segment->flag_entries[i] = avio_r8(pb); segment->stream_offset_entries[i] = avio_rb64(pb); avio_skip(pb, length - 11); } return 0; } static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFIndexTableSegment *segment = arg; switch(tag) { case 0x3F05: segment->edit_unit_byte_count = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "EditUnitByteCount %d\n", segment->edit_unit_byte_count); break; case 0x3F06: segment->index_sid = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "IndexSID %d\n", segment->index_sid); break; case 0x3F07: segment->body_sid = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "BodySID %d\n", segment->body_sid); break; case 0x3F0A: av_log(NULL, AV_LOG_TRACE, "IndexEntryArray found\n"); return mxf_read_index_entry_array(pb, segment); case 0x3F0B: segment->index_edit_rate.num = avio_rb32(pb); segment->index_edit_rate.den = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "IndexEditRate %d/%d\n", segment->index_edit_rate.num, segment->index_edit_rate.den); break; case 0x3F0C: segment->index_start_position = avio_rb64(pb); av_log(NULL, AV_LOG_TRACE, "IndexStartPosition %"PRId64"\n", segment->index_start_position); break; case 0x3F0D: segment->index_duration = avio_rb64(pb); av_log(NULL, AV_LOG_TRACE, "IndexDuration %"PRId64"\n", segment->index_duration); break; } return 0; } static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor) { int code, value, ofs = 0; char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */ do { code = avio_r8(pb); value = avio_r8(pb); av_log(NULL, AV_LOG_TRACE, "pixel layout: code %#x\n", code); if (ofs <= 14) { layout[ofs++] = code; layout[ofs++] = value; } else break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */ } while (code != 0); /* SMPTE 377M E.2.46 */ ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt); } static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFDescriptor *descriptor = arg; int entry_count, entry_size; switch(tag) { case 0x3F01: return mxf_read_strong_ref_array(pb, &descriptor->sub_descriptors_refs, &descriptor->sub_descriptors_count); case 0x3002: /* ContainerDuration */ descriptor->duration = avio_rb64(pb); break; case 0x3004: avio_read(pb, descriptor->essence_container_ul, 16); break; case 0x3005: avio_read(pb, descriptor->codec_ul, 16); break; case 0x3006: descriptor->linked_track_id = avio_rb32(pb); break; case 0x3201: /* PictureEssenceCoding */ avio_read(pb, descriptor->essence_codec_ul, 16); break; case 0x3203: descriptor->width = avio_rb32(pb); break; case 0x3202: descriptor->height = avio_rb32(pb); break; case 0x320C: descriptor->frame_layout = avio_r8(pb); break; case 0x320D: entry_count = avio_rb32(pb); entry_size = avio_rb32(pb); if (entry_size == 4) { if (entry_count > 0) descriptor->video_line_map[0] = avio_rb32(pb); else descriptor->video_line_map[0] = 0; if (entry_count > 1) descriptor->video_line_map[1] = avio_rb32(pb); else descriptor->video_line_map[1] = 0; } else av_log(NULL, AV_LOG_WARNING, "VideoLineMap element size %d currently not supported\n", entry_size); break; case 0x320E: descriptor->aspect_ratio.num = avio_rb32(pb); descriptor->aspect_ratio.den = avio_rb32(pb); break; case 0x3212: descriptor->field_dominance = avio_r8(pb); break; case 0x3301: descriptor->component_depth = avio_rb32(pb); break; case 0x3302: descriptor->horiz_subsampling = avio_rb32(pb); break; case 0x3308: descriptor->vert_subsampling = avio_rb32(pb); break; case 0x3D03: descriptor->sample_rate.num = avio_rb32(pb); descriptor->sample_rate.den = avio_rb32(pb); break; case 0x3D06: /* SoundEssenceCompression */ avio_read(pb, descriptor->essence_codec_ul, 16); break; case 0x3D07: descriptor->channels = avio_rb32(pb); break; case 0x3D01: descriptor->bits_per_sample = avio_rb32(pb); break; case 0x3401: mxf_read_pixel_layout(pb, descriptor); break; default: /* Private uid used by SONY C0023S01.mxf */ if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) { if (descriptor->extradata) av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n"); av_free(descriptor->extradata); descriptor->extradata_size = 0; descriptor->extradata = av_malloc(size); if (!descriptor->extradata) return AVERROR(ENOMEM); descriptor->extradata_size = size; avio_read(pb, descriptor->extradata, size); } if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) { uint32_t rsiz = avio_rb16(pb); if (rsiz == FF_PROFILE_JPEG2000_DCINEMA_2K || rsiz == FF_PROFILE_JPEG2000_DCINEMA_4K) descriptor->pix_fmt = AV_PIX_FMT_XYZ12; } break; } return 0; } static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size) { MXFTaggedValue *tagged_value = arg; uint8_t key[17]; if (size <= 17) return 0; avio_read(pb, key, 17); /* TODO: handle other types of of indirect values */ if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) { return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value); } else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) { return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value); } return 0; } static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFTaggedValue *tagged_value = arg; switch (tag){ case 0x5001: return mxf_read_utf16be_string(pb, size, &tagged_value->name); case 0x5003: return mxf_read_indirect_value(tagged_value, pb, size); } return 0; } /* * Match an uid independently of the version byte and up to len common bytes * Returns: boolean */ static int mxf_match_uid(const UID key, const UID uid, int len) { int i; for (i = 0; i < len; i++) { if (i != 7 && key[i] != uid[i]) return 0; } return 1; } static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid) { while (uls->uid[0]) { if(mxf_match_uid(uls->uid, *uid, uls->matching_len)) break; uls++; } return uls; } static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type) { int i; if (!strong_ref) return NULL; for (i = 0; i < mxf->metadata_sets_count; i++) { if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) && (type == AnyType || mxf->metadata_sets[i]->type == type)) { return mxf->metadata_sets[i]; } } return NULL; } static const MXFCodecUL mxf_picture_essence_container_uls[] = { // video essence container uls { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x10,0x60,0x01 }, 14, AV_CODEC_ID_H264 }, /* H.264 frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x12,0x01,0x00 }, 14, AV_CODEC_ID_VC1 }, /* VC-1 frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MPEG-ES frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* Type D-10 mapping of 40Mbps 525/60-I */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO }, /* DV 625 25mbps */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO }, /* uncompressed picture */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x01,0x01 }, 15, AV_CODEC_ID_HQ_HQA }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x02,0x01 }, 15, AV_CODEC_ID_HQX }, { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4f }, 14, AV_CODEC_ID_RAWVIDEO }, /* Legacy ?? Uncompressed Picture */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; /* EC ULs for intra-only formats */ static const MXFCodecUL mxf_intra_only_essence_container_uls[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MXF-GC SMPTE D-10 mappings */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */ static const MXFCodecUL mxf_intra_only_picture_essence_coding_uls[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14, AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra Profiles */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG 2000 code stream */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; /* actual coded width for AVC-Intra to allow selecting correct SPS/PPS */ static const MXFCodecUL mxf_intra_only_picture_coded_width[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 16, 1440 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 16, 1440 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 16, 1440 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 16, 1440 }, { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, 0 }, }; static const MXFCodecUL mxf_sound_essence_container_uls[] = { // sound essence container uls { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */ { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4F }, 14, AV_CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14, AV_CODEC_ID_AAC }, /* MPEG-2 AAC ADTS (legacy) */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; static const MXFCodecUL mxf_data_essence_container_uls[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 }, 16, 0 }, { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; static const char* const mxf_data_essence_descriptor[] = { "vbi_vanc_smpte_436M", }; static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments) { int i, j, nb_segments = 0; MXFIndexTableSegment **unsorted_segments; int last_body_sid = -1, last_index_sid = -1, last_index_start = -1; /* count number of segments, allocate arrays and copy unsorted segments */ for (i = 0; i < mxf->metadata_sets_count; i++) if (mxf->metadata_sets[i]->type == IndexTableSegment) nb_segments++; if (!nb_segments) return AVERROR_INVALIDDATA; if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) || !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) { av_freep(sorted_segments); av_free(unsorted_segments); return AVERROR(ENOMEM); } for (i = j = 0; i < mxf->metadata_sets_count; i++) if (mxf->metadata_sets[i]->type == IndexTableSegment) unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i]; *nb_sorted_segments = 0; /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */ for (i = 0; i < nb_segments; i++) { int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1; uint64_t best_index_duration = 0; for (j = 0; j < nb_segments; j++) { MXFIndexTableSegment *s = unsorted_segments[j]; /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates. * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around. * If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have. */ if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) && (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start || (s->index_start_position == best_index_start && s->index_duration > best_index_duration))) { best = j; best_body_sid = s->body_sid; best_index_sid = s->index_sid; best_index_start = s->index_start_position; best_index_duration = s->index_duration; } } /* no suitable entry found -> we're done */ if (best == -1) break; (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best]; last_body_sid = best_body_sid; last_index_sid = best_index_sid; last_index_start = best_index_start; } av_free(unsorted_segments); return 0; } /** * Computes the absolute file offset of the given essence container offset */ static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out) { int x; int64_t offset_in = offset; /* for logging */ for (x = 0; x < mxf->partitions_count; x++) { MXFPartition *p = &mxf->partitions[x]; if (p->body_sid != body_sid) continue; if (offset < p->essence_length || !p->essence_length) { *offset_out = p->essence_offset + offset; return 0; } offset -= p->essence_length; } av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n", offset_in, body_sid); return AVERROR_INVALIDDATA; } /** * Returns the end position of the essence container with given BodySID, or zero if unknown */ static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid) { int x; int64_t ret = 0; for (x = 0; x < mxf->partitions_count; x++) { MXFPartition *p = &mxf->partitions[x]; if (p->body_sid != body_sid) continue; if (!p->essence_length) return 0; ret = p->essence_offset + p->essence_length; } return ret; } /* EditUnit -> absolute offset */ static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, int64_t *edit_unit_out, int64_t *offset_out, int nag) { int i; int64_t offset_temp = 0; for (i = 0; i < index_table->nb_segments; i++) { MXFIndexTableSegment *s = index_table->segments[i]; edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */ if (edit_unit < s->index_start_position + s->index_duration) { int64_t index = edit_unit - s->index_start_position; if (s->edit_unit_byte_count) offset_temp += s->edit_unit_byte_count * index; else if (s->nb_index_entries) { if (s->nb_index_entries == 2 * s->index_duration + 1) index *= 2; /* Avid index */ if (index < 0 || index >= s->nb_index_entries) { av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n", index_table->index_sid, s->index_start_position); return AVERROR_INVALIDDATA; } offset_temp = s->stream_offset_entries[index]; } else { av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n", index_table->index_sid, s->index_start_position); return AVERROR_INVALIDDATA; } if (edit_unit_out) *edit_unit_out = edit_unit; return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out); } else { /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */ offset_temp += s->edit_unit_byte_count * s->index_duration; } } if (nag) av_log(mxf->fc, AV_LOG_ERROR, "failed to map EditUnit %"PRId64" in IndexSID %i to an offset\n", edit_unit, index_table->index_sid); return AVERROR_INVALIDDATA; } static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table) { int i, j, x; int8_t max_temporal_offset = -128; uint8_t *flags; /* first compute how many entries we have */ for (i = 0; i < index_table->nb_segments; i++) { MXFIndexTableSegment *s = index_table->segments[i]; if (!s->nb_index_entries) { index_table->nb_ptses = 0; return 0; /* no TemporalOffsets */ } index_table->nb_ptses += s->index_duration; } /* paranoid check */ if (index_table->nb_ptses <= 0) return 0; if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) || !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry))) || !(index_table->offsets = av_calloc(index_table->nb_ptses, sizeof(int8_t))) || !(flags = av_calloc(index_table->nb_ptses, sizeof(uint8_t)))) { av_freep(&index_table->ptses); av_freep(&index_table->fake_index); av_freep(&index_table->offsets); return AVERROR(ENOMEM); } /* we may have a few bad TemporalOffsets * make sure the corresponding PTSes don't have the bogus value 0 */ for (x = 0; x < index_table->nb_ptses; x++) index_table->ptses[x] = AV_NOPTS_VALUE; /** * We have this: * * x TemporalOffset * 0: 0 * 1: 1 * 2: 1 * 3: -2 * 4: 1 * 5: 1 * 6: -2 * * We want to transform it into this: * * x DTS PTS * 0: -1 0 * 1: 0 3 * 2: 1 1 * 3: 2 2 * 4: 3 6 * 5: 4 4 * 6: 5 5 * * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses, * then settings mxf->first_dts = -max(TemporalOffset[x]). * The latter makes DTS <= PTS. */ for (i = x = 0; i < index_table->nb_segments; i++) { MXFIndexTableSegment *s = index_table->segments[i]; int index_delta = 1; int n = s->nb_index_entries; if (s->nb_index_entries == 2 * s->index_duration + 1) { index_delta = 2; /* Avid index */ /* ignore the last entry - it's the size of the essence container */ n--; } for (j = 0; j < n; j += index_delta, x++) { int offset = s->temporal_offset_entries[j] / index_delta; int index = x + offset; if (x >= index_table->nb_ptses) { av_log(mxf->fc, AV_LOG_ERROR, "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n", s->nb_index_entries, s->index_duration); break; } flags[x] = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0; if (index < 0 || index >= index_table->nb_ptses) { av_log(mxf->fc, AV_LOG_ERROR, "index entry %i + TemporalOffset %i = %i, which is out of bounds\n", x, offset, index); continue; } index_table->offsets[x] = offset; index_table->ptses[index] = x; max_temporal_offset = FFMAX(max_temporal_offset, offset); } } /* calculate the fake index table in display order */ for (x = 0; x < index_table->nb_ptses; x++) { index_table->fake_index[x].timestamp = x; if (index_table->ptses[x] != AV_NOPTS_VALUE) index_table->fake_index[index_table->ptses[x]].flags = flags[x]; } av_freep(&flags); index_table->first_dts = -max_temporal_offset; return 0; } /** * Sorts and collects index table segments into index tables. * Also computes PTSes if possible. */ static int mxf_compute_index_tables(MXFContext *mxf) { int i, j, k, ret, nb_sorted_segments; MXFIndexTableSegment **sorted_segments = NULL; AVStream *st = NULL; for (i = 0; i < mxf->fc->nb_streams; i++) { if (mxf->fc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA) continue; st = mxf->fc->streams[i]; break; } if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) || nb_sorted_segments <= 0) { av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n"); return 0; } /* sanity check and count unique BodySIDs/IndexSIDs */ for (i = 0; i < nb_sorted_segments; i++) { if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) mxf->nb_index_tables++; else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) { av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n"); ret = AVERROR_INVALIDDATA; goto finish_decoding_index; } } mxf->index_tables = av_mallocz_array(mxf->nb_index_tables, sizeof(*mxf->index_tables)); if (!mxf->index_tables) { av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n"); ret = AVERROR(ENOMEM); goto finish_decoding_index; } /* distribute sorted segments to index tables */ for (i = j = 0; i < nb_sorted_segments; i++) { if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) { /* next IndexSID */ j++; } mxf->index_tables[j].nb_segments++; } for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) { MXFIndexTable *t = &mxf->index_tables[j]; t->segments = av_mallocz_array(t->nb_segments, sizeof(*t->segments)); if (!t->segments) { av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment" " pointer array\n"); ret = AVERROR(ENOMEM); goto finish_decoding_index; } if (sorted_segments[i]->index_start_position) av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n", sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position); memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*)); t->index_sid = sorted_segments[i]->index_sid; t->body_sid = sorted_segments[i]->body_sid; if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0) goto finish_decoding_index; /* fix zero IndexDurations */ for (k = 0; k < t->nb_segments; k++) { if (t->segments[k]->index_duration) continue; if (t->nb_segments > 1) av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n", t->index_sid, k); if (!st) { av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n"); break; } /* assume the first stream's duration is reasonable * leave index_duration = 0 on further segments in case we have any (unlikely) */ t->segments[k]->index_duration = st->duration; break; } } ret = 0; finish_decoding_index: av_free(sorted_segments); return ret; } static int mxf_is_intra_only(MXFDescriptor *descriptor) { return mxf_get_codec_ul(mxf_intra_only_essence_container_uls, &descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE || mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls, &descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE; } static int mxf_uid_to_str(UID uid, char **str) { int i; char *p; p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1); if (!p) return AVERROR(ENOMEM); for (i = 0; i < sizeof(UID); i++) { snprintf(p, 2 + 1, "%.2x", uid[i]); p += 2; if (i == 3 || i == 5 || i == 7 || i == 9) { snprintf(p, 1 + 1, "-"); p++; } } return 0; } static int mxf_umid_to_str(UID ul, UID uid, char **str) { int i; char *p; p = *str = av_mallocz(sizeof(UID) * 4 + 2 + 1); if (!p) return AVERROR(ENOMEM); snprintf(p, 2 + 1, "0x"); p += 2; for (i = 0; i < sizeof(UID); i++) { snprintf(p, 2 + 1, "%.2X", ul[i]); p += 2; } for (i = 0; i < sizeof(UID); i++) { snprintf(p, 2 + 1, "%.2X", uid[i]); p += 2; } return 0; } static int mxf_add_umid_metadata(AVDictionary **pm, const char *key, MXFPackage* package) { char *str; int ret; if (!package) return 0; if ((ret = mxf_umid_to_str(package->package_ul, package->package_uid, &str)) < 0) return ret; av_dict_set(pm, key, str, AV_DICT_DONT_STRDUP_VAL); return 0; } static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc) { char buf[AV_TIMECODE_STR_SIZE]; av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0); return 0; } static MXFTimecodeComponent* mxf_resolve_timecode_component(MXFContext *mxf, UID *strong_ref) { MXFStructuralComponent *component = NULL; MXFPulldownComponent *pulldown = NULL; component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType); if (!component) return NULL; switch (component->type) { case TimecodeComponent: return (MXFTimecodeComponent*)component; case PulldownComponent: /* timcode component may be located on a pulldown component */ pulldown = (MXFPulldownComponent*)component; return mxf_resolve_strong_ref(mxf, &pulldown->input_segment_ref, TimecodeComponent); default: break; } return NULL; } static MXFPackage* mxf_resolve_source_package(MXFContext *mxf, UID package_uid) { MXFPackage *package = NULL; int i; for (i = 0; i < mxf->packages_count; i++) { package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], SourcePackage); if (!package) continue; if (!memcmp(package->package_uid, package_uid, 16)) return package; } return NULL; } static MXFDescriptor* mxf_resolve_multidescriptor(MXFContext *mxf, MXFDescriptor *descriptor, int track_id) { MXFDescriptor *sub_descriptor = NULL; int i; if (!descriptor) return NULL; if (descriptor->type == MultipleDescriptor) { for (i = 0; i < descriptor->sub_descriptors_count; i++) { sub_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->sub_descriptors_refs[i], Descriptor); if (!sub_descriptor) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n"); continue; } if (sub_descriptor->linked_track_id == track_id) { return sub_descriptor; } } } else if (descriptor->type == Descriptor) return descriptor; return NULL; } static MXFStructuralComponent* mxf_resolve_essence_group_choice(MXFContext *mxf, MXFEssenceGroup *essence_group) { MXFStructuralComponent *component = NULL; MXFPackage *package = NULL; MXFDescriptor *descriptor = NULL; int i; if (!essence_group || !essence_group->structural_components_count) return NULL; /* essence groups contains multiple representations of the same media, this return the first components with a valid Descriptor typically index 0 */ for (i =0; i < essence_group->structural_components_count; i++){ component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip); if (!component) continue; if (!(package = mxf_resolve_source_package(mxf, component->source_package_uid))) continue; descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor); if (descriptor) return component; } return NULL; } static MXFStructuralComponent* mxf_resolve_sourceclip(MXFContext *mxf, UID *strong_ref) { MXFStructuralComponent *component = NULL; component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType); if (!component) return NULL; switch (component->type) { case SourceClip: return component; case EssenceGroup: return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component); default: break; } return NULL; } static int mxf_parse_package_comments(MXFContext *mxf, AVDictionary **pm, MXFPackage *package) { MXFTaggedValue *tag; int size, i; char *key = NULL; for (i = 0; i < package->comment_count; i++) { tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue); if (!tag || !tag->name || !tag->value) continue; size = strlen(tag->name) + 8 + 1; key = av_mallocz(size); if (!key) return AVERROR(ENOMEM); snprintf(key, size, "comment_%s", tag->name); av_dict_set(pm, key, tag->value, AV_DICT_DONT_STRDUP_KEY); } return 0; } static int mxf_parse_physical_source_package(MXFContext *mxf, MXFTrack *source_track, AVStream *st) { MXFPackage *physical_package = NULL; MXFTrack *physical_track = NULL; MXFStructuralComponent *sourceclip = NULL; MXFTimecodeComponent *mxf_tc = NULL; int i, j, k; AVTimecode tc; int flags; int64_t start_position; for (i = 0; i < source_track->sequence->structural_components_count; i++) { sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip); if (!sourceclip) continue; if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_uid))) break; mxf_add_umid_metadata(&st->metadata, "reel_umid", physical_package); /* the name of physical source package is name of the reel or tape */ if (physical_package->name && physical_package->name[0]) av_dict_set(&st->metadata, "reel_name", physical_package->name, 0); /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track * to the start_frame of the timecode component located on one of the tracks of the physical source package. */ for (j = 0; j < physical_package->tracks_count; j++) { if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n"); continue; } if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n"); continue; } if (physical_track->edit_rate.num <= 0 || physical_track->edit_rate.den <= 0) { av_log(mxf->fc, AV_LOG_WARNING, "Invalid edit rate (%d/%d) found on structural" " component #%d, defaulting to 25/1\n", physical_track->edit_rate.num, physical_track->edit_rate.den, i); physical_track->edit_rate = (AVRational){25, 1}; } for (k = 0; k < physical_track->sequence->structural_components_count; k++) { if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k]))) continue; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; /* scale sourceclip start_position to match physical track edit rate */ start_position = av_rescale_q(sourceclip->start_position, physical_track->edit_rate, source_track->edit_rate); if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&st->metadata, "timecode", &tc); return 0; } } } } return 0; } static int mxf_add_metadata_stream(MXFContext *mxf, MXFTrack *track) { MXFStructuralComponent *component = NULL; const MXFCodecUL *codec_ul = NULL; MXFPackage tmp_package; AVStream *st; int j; for (j = 0; j < track->sequence->structural_components_count; j++) { component = mxf_resolve_sourceclip(mxf, &track->sequence->structural_components_refs[j]); if (!component) continue; break; } if (!component) return 0; st = avformat_new_stream(mxf->fc, NULL); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, "could not allocate metadata stream\n"); return AVERROR(ENOMEM); } st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->codecpar->codec_id = AV_CODEC_ID_NONE; st->id = track->track_id; memcpy(&tmp_package.package_ul, component->source_package_ul, 16); memcpy(&tmp_package.package_uid, component->source_package_uid, 16); mxf_add_umid_metadata(&st->metadata, "file_package_umid", &tmp_package); if (track->name && track->name[0]) av_dict_set(&st->metadata, "track_name", track->name, 0); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &track->sequence->data_definition_ul); av_dict_set(&st->metadata, "data_type", av_get_media_type_string(codec_ul->id), 0); return 0; } static int mxf_parse_structural_metadata(MXFContext *mxf) { MXFPackage *material_package = NULL; int i, j, k, ret; av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count); /* TODO: handle multiple material packages (OP3x) */ for (i = 0; i < mxf->packages_count; i++) { material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); if (material_package) break; } if (!material_package) { av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n"); return AVERROR_INVALIDDATA; } mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package); if (material_package->name && material_package->name[0]) av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0); mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package); for (i = 0; i < material_package->tracks_count; i++) { MXFPackage *source_package = NULL; MXFTrack *material_track = NULL; MXFTrack *source_track = NULL; MXFTrack *temp_track = NULL; MXFDescriptor *descriptor = NULL; MXFStructuralComponent *component = NULL; MXFTimecodeComponent *mxf_tc = NULL; UID *essence_container_ul = NULL; const MXFCodecUL *codec_ul = NULL; const MXFCodecUL *container_ul = NULL; const MXFCodecUL *pix_fmt_ul = NULL; AVStream *st; AVTimecode tc; int flags; if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n"); continue; } if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) { mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc); } } if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n"); continue; } for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent); if (!component) continue; mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc); break; } } /* TODO: handle multiple source clips, only finds first valid source clip */ if(material_track->sequence->structural_components_count > 1) av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n", material_track->track_id, material_track->sequence->structural_components_count); for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]); if (!component) continue; source_package = mxf_resolve_source_package(mxf, component->source_package_uid); if (!source_package) { av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id); break; } for (k = 0; k < source_package->tracks_count; k++) { if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n"); ret = AVERROR_INVALIDDATA; goto fail_and_free; } if (temp_track->track_id == component->source_track_id) { source_track = temp_track; break; } } if (!source_track) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id); break; } if(source_track && component) break; } if (!source_track || !component || !source_package) { if((ret = mxf_add_metadata_stream(mxf, material_track))) goto fail_and_free; continue; } if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n"); ret = AVERROR_INVALIDDATA; goto fail_and_free; } /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */ if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id); continue; } st = avformat_new_stream(mxf->fc, NULL); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n"); ret = AVERROR(ENOMEM); goto fail_and_free; } st->id = material_track->track_id; st->priv_data = source_track; source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id); /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */ if (descriptor && descriptor->duration != AV_NOPTS_VALUE) source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration); else source_track->original_duration = st->duration = component->duration; if (st->duration == -1) st->duration = AV_NOPTS_VALUE; st->start_time = component->start_position; if (material_track->edit_rate.num <= 0 || material_track->edit_rate.den <= 0) { av_log(mxf->fc, AV_LOG_WARNING, "Invalid edit rate (%d/%d) found on stream #%d, " "defaulting to 25/1\n", material_track->edit_rate.num, material_track->edit_rate.den, st->index); material_track->edit_rate = (AVRational){25, 1}; } avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num); /* ensure SourceTrack EditRate == MaterialTrack EditRate since only * the former is accessible via st->priv_data */ source_track->edit_rate = material_track->edit_rate; PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); st->codecpar->codec_type = codec_ul->id; if (!descriptor) { av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index); continue; } PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul); PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul); essence_container_ul = &descriptor->essence_container_ul; /* HACK: replacing the original key with mxf_encrypted_essence_container * is not allowed according to s429-6, try to find correct information anyway */ if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n"); for (k = 0; k < mxf->metadata_sets_count; k++) { MXFMetadataSet *metadata = mxf->metadata_sets[k]; if (metadata->type == CryptoContext) { essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; break; } } } /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; if (st->codecpar->codec_id == AV_CODEC_ID_NONE) { codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; } av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ", avcodec_get_name(st->codecpar->codec_id)); for (k = 0; k < 16; k++) { av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x", descriptor->essence_codec_ul[k]); if (!(k+1 & 19) || k == 5) av_log(mxf->fc, AV_LOG_VERBOSE, "."); } av_log(mxf->fc, AV_LOG_VERBOSE, "\n"); mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package); if (source_package->name && source_package->name[0]) av_dict_set(&st->metadata, "file_package_name", source_package->name, 0); if (material_track->name && material_track->name[0]) av_dict_set(&st->metadata, "track_name", material_track->name, 0); mxf_parse_physical_source_package(mxf, source_track, st); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { source_track->intra_only = mxf_is_intra_only(descriptor); container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; st->codecpar->width = descriptor->width; st->codecpar->height = descriptor->height; /* Field height, not frame height */ switch (descriptor->frame_layout) { case FullFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; break; case OneField: /* Every other line is stored and needs to be duplicated. */ av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n"); break; /* The correct thing to do here is fall through, but by breaking we might be able to decode some streams at half the vertical resolution, rather than not al all. It's also for compatibility with the old behavior. */ case MixedFields: break; case SegmentedFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; case SeparateFields: av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n", descriptor->video_line_map[0], descriptor->video_line_map[1], descriptor->field_dominance); if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) { /* Detect coded field order from VideoLineMap: * (even, even) => bottom field coded first * (even, odd) => top field coded first * (odd, even) => top field coded first * (odd, odd) => bottom field coded first */ if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_TT; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_TB; break; default: avpriv_request_sample(mxf->fc, "Field dominance %d support", descriptor->field_dominance); } } else { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_BB; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_BT; break; default: avpriv_request_sample(mxf->fc, "Field dominance %d support", descriptor->field_dominance); } } } /* Turn field height into frame height. */ st->codecpar->height *= 2; break; default: av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout); } if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { st->codecpar->format = descriptor->pix_fmt; if (st->codecpar->format == AV_PIX_FMT_NONE) { pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, &descriptor->essence_codec_ul); st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id; if (st->codecpar->format== AV_PIX_FMT_NONE) { st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls, &descriptor->essence_codec_ul)->id; if (!st->codecpar->codec_tag) { /* support files created before RP224v10 by defaulting to UYVY422 if subsampling is 4:2:2 and component depth is 8-bit */ if (descriptor->horiz_subsampling == 2 && descriptor->vert_subsampling == 1 && descriptor->component_depth == 8) { st->codecpar->format = AV_PIX_FMT_UYVY422; } } } } } st->need_parsing = AVSTREAM_PARSE_HEADERS; if (material_track->sequence->origin) { av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0); } if (source_track->sequence->origin) { av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0); } if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den) st->display_aspect_ratio = descriptor->aspect_ratio; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul); /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */ if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE)) st->codecpar->codec_id = (enum AVCodecID)container_ul->id; st->codecpar->channels = descriptor->channels; st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample; if (descriptor->sample_rate.den > 0) { st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num); } else { av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) " "found for stream #%d, time base forced to 1/48000\n", descriptor->sample_rate.num, descriptor->sample_rate.den, st->index); avpriv_set_pts_info(st, 64, 1, 48000); } /* if duration is set, rescale it from EditRate to SampleRate */ if (st->duration != AV_NOPTS_VALUE) st->duration = av_rescale_q(st->duration, av_inv_q(material_track->edit_rate), st->time_base); /* TODO: implement AV_CODEC_ID_RAWAUDIO */ if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE; } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) { st->need_parsing = AVSTREAM_PARSE_FULL; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { int codec_id = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul)->id; if (codec_id >= 0 && codec_id < FF_ARRAY_ELEMS(mxf_data_essence_descriptor)) { av_dict_set(&st->metadata, "data_type", mxf_data_essence_descriptor[codec_id], 0); } } if (descriptor->extradata) { if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) { memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size); } } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width, &descriptor->essence_codec_ul)->id; if (coded_width) st->codecpar->width = coded_width; ret = ff_generate_avci_extradata(st); if (ret < 0) return ret; } if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) { /* TODO: decode timestamps */ st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; } } ret = 0; fail_and_free: return ret; } static int64_t mxf_timestamp_to_int64(uint64_t timestamp) { struct tm time = { 0 }; time.tm_year = (timestamp >> 48) - 1900; time.tm_mon = (timestamp >> 40 & 0xFF) - 1; time.tm_mday = (timestamp >> 32 & 0xFF); time.tm_hour = (timestamp >> 24 & 0xFF); time.tm_min = (timestamp >> 16 & 0xFF); time.tm_sec = (timestamp >> 8 & 0xFF); /* msvcrt versions of strftime calls the invalid parameter handler * (aborting the process if one isn't set) if the parameters are out * of range. */ time.tm_mon = av_clip(time.tm_mon, 0, 11); time.tm_mday = av_clip(time.tm_mday, 1, 31); time.tm_hour = av_clip(time.tm_hour, 0, 23); time.tm_min = av_clip(time.tm_min, 0, 59); time.tm_sec = av_clip(time.tm_sec, 0, 59); return (int64_t)av_timegm(&time) * 1000000; } #define SET_STR_METADATA(pb, name, str) do { \ if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \ return ret; \ av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \ } while (0) #define SET_UID_METADATA(pb, name, var, str) do { \ avio_read(pb, var, 16); \ if ((ret = mxf_uid_to_str(var, &str)) < 0) \ return ret; \ av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \ } while (0) #define SET_TS_METADATA(pb, name, var, str) do { \ var = avio_rb64(pb); \ if ((ret = avpriv_dict_set_timestamp(&s->metadata, name, mxf_timestamp_to_int64(var)) < 0)) \ return ret; \ } while (0) static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset) { MXFContext *mxf = arg; AVFormatContext *s = mxf->fc; int ret; UID uid = { 0 }; char *str = NULL; uint64_t ts; switch (tag) { case 0x3C01: SET_STR_METADATA(pb, "company_name", str); break; case 0x3C02: SET_STR_METADATA(pb, "product_name", str); break; case 0x3C04: SET_STR_METADATA(pb, "product_version", str); break; case 0x3C05: SET_UID_METADATA(pb, "product_uid", uid, str); break; case 0x3C06: SET_TS_METADATA(pb, "modification_date", ts, str); break; case 0x3C08: SET_STR_METADATA(pb, "application_platform", str); break; case 0x3C09: SET_UID_METADATA(pb, "generation_uid", uid, str); break; case 0x3C0A: SET_UID_METADATA(pb, "uid", uid, str); break; } return 0; } static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; AVFormatContext *s = mxf->fc; int ret; char *str = NULL; if (tag >= 0x8000 && (IS_KLV_KEY(uid, mxf_avid_project_name))) { SET_STR_METADATA(pb, "project_name", str); } return 0; } static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = { { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_metadata }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_package, sizeof(MXFPackage), SourcePackage }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_package, sizeof(MXFPackage), MaterialPackage }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup}, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VANC/VBI - SMPTE 436M */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0c,0x00 }, mxf_read_pulldown_component, sizeof(MXFPulldownComponent), PulldownComponent }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment }, { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType }, }; static int mxf_metadataset_init(MXFMetadataSet *ctx, enum MXFMetadataSetType type) { switch (type){ case MultipleDescriptor: case Descriptor: ((MXFDescriptor*)ctx)->pix_fmt = AV_PIX_FMT_NONE; ((MXFDescriptor*)ctx)->duration = AV_NOPTS_VALUE; break; default: break; } return 0; } static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type) { AVIOContext *pb = mxf->fc->pb; MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf; uint64_t klv_end = avio_tell(pb) + klv->length; if (!ctx) return AVERROR(ENOMEM); mxf_metadataset_init(ctx, type); while (avio_tell(pb) + 4 < klv_end && !avio_feof(pb)) { int ret; int tag = avio_rb16(pb); int size = avio_rb16(pb); /* KLV specified by 0x53 */ uint64_t next = avio_tell(pb) + size; UID uid = {0}; av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x size %d\n", tag, size); if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */ av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag); continue; } if (tag > 0x7FFF) { /* dynamic tag */ int i; for (i = 0; i < mxf->local_tags_count; i++) { int local_tag = AV_RB16(mxf->local_tags+i*18); if (local_tag == tag) { memcpy(uid, mxf->local_tags+i*18+2, 16); av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x\n", local_tag); PRINT_KEY(mxf->fc, "uid", uid); } } } if (ctx_size && tag == 0x3C0A) { avio_read(pb, ctx->uid, 16); } else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0) { mxf_free_metadataset(&ctx, !!ctx_size); return ret; } /* Accept the 64k local set limit being exceeded (Avid). Don't accept * it extending past the end of the KLV though (zzuf5.mxf). */ if (avio_tell(pb) > klv_end) { if (ctx_size) { ctx->type = type; mxf_free_metadataset(&ctx, !!ctx_size); } av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x extends past end of local set @ %#"PRIx64"\n", tag, klv->offset); return AVERROR_INVALIDDATA; } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */ avio_seek(pb, next, SEEK_SET); } if (ctx_size) ctx->type = type; return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0; } /** * Matches any partition pack key, in other words: * - HeaderPartition * - BodyPartition * - FooterPartition * @return non-zero if the key is a partition pack key, zero otherwise */ static int mxf_is_partition_pack_key(UID key) { //NOTE: this is a little lax since it doesn't constraint key[14] return !memcmp(key, mxf_header_partition_pack_key, 13) && key[13] >= 2 && key[13] <= 4; } /** * Parses a metadata KLV * @return <0 on error, 0 otherwise */ static int mxf_parse_klv(MXFContext *mxf, KLVPacket klv, MXFMetadataReadFunc *read, int ctx_size, enum MXFMetadataSetType type) { AVFormatContext *s = mxf->fc; int res; if (klv.key[5] == 0x53) { res = mxf_read_local_tags(mxf, &klv, read, ctx_size, type); } else { uint64_t next = avio_tell(s->pb) + klv.length; res = read(mxf, s->pb, 0, klv.length, klv.key, klv.offset); /* only seek forward, else this can loop for a long time */ if (avio_tell(s->pb) > next) { av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n", klv.offset); return AVERROR_INVALIDDATA; } avio_seek(s->pb, next, SEEK_SET); } if (res < 0) { av_log(s, AV_LOG_ERROR, "error reading header metadata\n"); return res; } return 0; } /** * Seeks to the previous partition and parses it, if possible * @return <= 0 if we should stop parsing, > 0 if we should keep going */ static int mxf_seek_to_previous_partition(MXFContext *mxf) { AVIOContext *pb = mxf->fc->pb; KLVPacket klv; int64_t current_partition_ofs; int ret; if (!mxf->current_partition || mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell) return 0; /* we've parsed all partitions */ /* seek to previous partition */ current_partition_ofs = mxf->current_partition->pack_ofs; //includes run-in avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET); mxf->current_partition = NULL; av_log(mxf->fc, AV_LOG_TRACE, "seeking to previous partition\n"); /* Make sure this is actually a PartitionPack, and if so parse it. * See deadlock2.mxf */ if ((ret = klv_read_packet(&klv, pb)) < 0) { av_log(mxf->fc, AV_LOG_ERROR, "failed to read PartitionPack KLV\n"); return ret; } if (!mxf_is_partition_pack_key(klv.key)) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition @ %" PRIx64 " isn't a PartitionPack\n", klv.offset); return AVERROR_INVALIDDATA; } /* We can't just check ofs >= current_partition_ofs because PreviousPartition * can point to just before the current partition, causing klv_read_packet() * to sync back up to it. See deadlock3.mxf */ if (klv.offset >= current_partition_ofs) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition for PartitionPack @ %" PRIx64 " indirectly points to itself\n", current_partition_ofs); return AVERROR_INVALIDDATA; } if ((ret = mxf_parse_klv(mxf, klv, mxf_read_partition_pack, 0, 0)) < 0) return ret; return 1; } /** * Called when essence is encountered * @return <= 0 if we should stop parsing, > 0 if we should keep going */ static int mxf_parse_handle_essence(MXFContext *mxf) { AVIOContext *pb = mxf->fc->pb; int64_t ret; if (mxf->parsing_backward) { return mxf_seek_to_previous_partition(mxf); } else { if (!mxf->footer_partition) { av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n"); return 0; } av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n"); /* remember where we were so we don't end up seeking further back than this */ mxf->last_forward_tell = avio_tell(pb); if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) { av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n"); return -1; } /* seek to FooterPartition and parse backward */ if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) { av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to FooterPartition @ 0x%" PRIx64 " (%"PRId64") - partial file?\n", mxf->run_in + mxf->footer_partition, ret); return ret; } mxf->current_partition = NULL; mxf->parsing_backward = 1; } return 1; } /** * Called when the next partition or EOF is encountered * @return <= 0 if we should stop parsing, > 0 if we should keep going */ static int mxf_parse_handle_partition_or_eof(MXFContext *mxf) { return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1; } /** * Figures out the proper offset and length of the essence container in each partition */ static void mxf_compute_essence_containers(MXFContext *mxf) { int x; /* everything is already correct */ if (mxf->op == OPAtom) return; for (x = 0; x < mxf->partitions_count; x++) { MXFPartition *p = &mxf->partitions[x]; if (!p->body_sid) continue; /* BodySID == 0 -> no essence */ if (x >= mxf->partitions_count - 1) break; /* FooterPartition - can't compute length (and we don't need to) */ /* essence container spans to the next partition */ p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset; if (p->essence_length < 0) { /* next ThisPartition < essence_offset */ p->essence_length = 0; av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %"PRIX64"\n", x+1, mxf->partitions[x+1].this_partition); } } } static int64_t round_to_kag(int64_t position, int kag_size) { /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */ /* NOTE: kag_size may be any integer between 1 - 2^10 */ int64_t ret = (position / kag_size) * kag_size; return ret == position ? ret : ret + kag_size; } static int is_pcm(enum AVCodecID codec_id) { /* we only care about "normal" PCM codecs until we get samples */ return codec_id >= AV_CODEC_ID_PCM_S16LE && codec_id < AV_CODEC_ID_PCM_S24DAUD; } static AVStream* mxf_get_opatom_stream(MXFContext *mxf) { int i; if (mxf->op != OPAtom) return NULL; for (i = 0; i < mxf->fc->nb_streams; i++) { if (mxf->fc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA) continue; return mxf->fc->streams[i]; } return NULL; } /** * Deal with the case where for some audio atoms EditUnitByteCount is * very small (2, 4..). In those cases we should read more than one * sample per call to mxf_read_packet(). */ static void mxf_handle_small_eubc(AVFormatContext *s) { MXFContext *mxf = s->priv_data; /* assuming non-OPAtom == frame wrapped * no sane writer would wrap 2 byte PCM packets with 20 byte headers.. */ AVStream *st = mxf_get_opatom_stream(mxf); if (!st) return; /* expect PCM with exactly one index table segment and a small (< 32) EUBC */ if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || !is_pcm(st->codecpar->codec_id) || mxf->nb_index_tables != 1 || mxf->index_tables[0].nb_segments != 1 || mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32) return; /* arbitrarily default to 48 kHz PAL audio frame size */ /* TODO: We could compute this from the ratio between the audio * and video edit rates for 48 kHz NTSC we could use the * 1802-1802-1802-1802-1801 pattern. */ mxf->edit_units_per_packet = 1920; } /** * Deal with the case where OPAtom files does not have any IndexTableSegments. */ static int mxf_handle_missing_index_segment(MXFContext *mxf) { AVFormatContext *s = mxf->fc; AVStream *st = NULL; MXFIndexTableSegment *segment = NULL; MXFPartition *p = NULL; int essence_partition_count = 0; int i, ret; st = mxf_get_opatom_stream(mxf); if (!st) return 0; /* TODO: support raw video without an index if they exist */ if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || !is_pcm(st->codecpar->codec_id)) return 0; /* check if file already has a IndexTableSegment */ for (i = 0; i < mxf->metadata_sets_count; i++) { if (mxf->metadata_sets[i]->type == IndexTableSegment) return 0; } /* find the essence partition */ for (i = 0; i < mxf->partitions_count; i++) { /* BodySID == 0 -> no essence */ if (!mxf->partitions[i].body_sid) continue; p = &mxf->partitions[i]; essence_partition_count++; } /* only handle files with a single essence partition */ if (essence_partition_count != 1) return 0; if (!(segment = av_mallocz(sizeof(*segment)))) return AVERROR(ENOMEM); if ((ret = mxf_add_metadata_set(mxf, segment))) { mxf_free_metadataset((MXFMetadataSet**)&segment, 1); return ret; } segment->type = IndexTableSegment; /* stream will be treated as small EditUnitByteCount */ segment->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3; segment->index_start_position = 0; segment->index_duration = s->streams[0]->duration; segment->index_sid = p->index_sid; segment->body_sid = p->body_sid; return 0; } static void mxf_read_random_index_pack(AVFormatContext *s) { MXFContext *mxf = s->priv_data; uint32_t length; int64_t file_size, max_rip_length, min_rip_length; KLVPacket klv; if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) return; file_size = avio_size(s->pb); /* S377m says to check the RIP length for "silly" values, without defining "silly". * The limit below assumes a file with nothing but partition packs and a RIP. * Before changing this, consider that a muxer may place each sample in its own partition. * * 105 is the size of the smallest possible PartitionPack * 12 is the size of each RIP entry * 28 is the size of the RIP header and footer, assuming an 8-byte BER */ max_rip_length = ((file_size - mxf->run_in) / 105) * 12 + 28; max_rip_length = FFMIN(max_rip_length, INT_MAX); //2 GiB and up is also silly /* We're only interested in RIPs with at least two entries.. */ min_rip_length = 16+1+24+4; /* See S377m section 11 */ avio_seek(s->pb, file_size - 4, SEEK_SET); length = avio_rb32(s->pb); if (length < min_rip_length || length > max_rip_length) goto end; avio_seek(s->pb, file_size - length, SEEK_SET); if (klv_read_packet(&klv, s->pb) < 0 || !IS_KLV_KEY(klv.key, mxf_random_index_pack_key) || klv.length != length - 20) goto end; avio_skip(s->pb, klv.length - 12); mxf->footer_partition = avio_rb64(s->pb); /* sanity check */ if (mxf->run_in + mxf->footer_partition >= file_size) { av_log(s, AV_LOG_WARNING, "bad FooterPartition in RIP - ignoring\n"); mxf->footer_partition = 0; } end: avio_seek(s->pb, mxf->run_in, SEEK_SET); } static int mxf_read_header(AVFormatContext *s) { MXFContext *mxf = s->priv_data; KLVPacket klv; int64_t essence_offset = 0; int ret; mxf->last_forward_tell = INT64_MAX; mxf->edit_units_per_packet = 1; if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) { av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n"); return AVERROR_INVALIDDATA; } avio_seek(s->pb, -14, SEEK_CUR); mxf->fc = s; mxf->run_in = avio_tell(s->pb); mxf_read_random_index_pack(s); while (!avio_feof(s->pb)) { const MXFMetadataReadTableEntry *metadata; if (klv_read_packet(&klv, s->pb) < 0) { /* EOF - seek to previous partition or stop */ if(mxf_parse_handle_partition_or_eof(mxf) <= 0) break; else continue; } PRINT_KEY(s, "read header", klv.key); av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset); if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) || IS_KLV_KEY(klv.key, mxf_essence_element_key) || IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) || IS_KLV_KEY(klv.key, mxf_system_item_key)) { if (!mxf->current_partition) { av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n"); return AVERROR_INVALIDDATA; } if (!mxf->current_partition->essence_offset) { /* for OP1a we compute essence_offset * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25) * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset * for OPAtom we still need the actual essence_offset though (the KL's length can vary) */ int64_t op1a_essence_offset = round_to_kag(mxf->current_partition->this_partition + mxf->current_partition->pack_length, mxf->current_partition->kag_size) + round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) + round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size); if (mxf->op == OPAtom) { /* point essence_offset to the actual data * OPAtom has all the essence in one big KLV */ mxf->current_partition->essence_offset = avio_tell(s->pb); mxf->current_partition->essence_length = klv.length; } else { /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */ mxf->current_partition->essence_offset = op1a_essence_offset; } } if (!essence_offset) essence_offset = klv.offset; /* seek to footer, previous partition or stop */ if (mxf_parse_handle_essence(mxf) <= 0) break; continue; } else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) { /* next partition pack - keep going, seek to previous partition or stop */ if(mxf_parse_handle_partition_or_eof(mxf) <= 0) break; else if (mxf->parsing_backward) continue; /* we're still parsing forward. proceed to parsing this partition pack */ } for (metadata = mxf_metadata_read_table; metadata->read; metadata++) { if (IS_KLV_KEY(klv.key, metadata->key)) { if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0) goto fail; break; } } if (!metadata->read) { av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n", UID_ARG(klv.key)); avio_skip(s->pb, klv.length); } } /* FIXME avoid seek */ if (!essence_offset) { av_log(s, AV_LOG_ERROR, "no essence\n"); ret = AVERROR_INVALIDDATA; goto fail; } avio_seek(s->pb, essence_offset, SEEK_SET); mxf_compute_essence_containers(mxf); /* we need to do this before computing the index tables * to be able to fill in zero IndexDurations with st->duration */ if ((ret = mxf_parse_structural_metadata(mxf)) < 0) goto fail; mxf_handle_missing_index_segment(mxf); if ((ret = mxf_compute_index_tables(mxf)) < 0) goto fail; if (mxf->nb_index_tables > 1) { /* TODO: look up which IndexSID to use via EssenceContainerData */ av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n", mxf->nb_index_tables, mxf->index_tables[0].index_sid); } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) { av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n"); ret = AVERROR_INVALIDDATA; goto fail; } mxf_handle_small_eubc(s); return 0; fail: mxf_read_close(s); return ret; } /** * Sets mxf->current_edit_unit based on what offset we're currently at. * @return next_ofs if OK, <0 on error */ static int64_t mxf_set_current_edit_unit(MXFContext *mxf, int64_t current_offset) { int64_t last_ofs = -1, next_ofs = -1; MXFIndexTable *t = &mxf->index_tables[0]; /* this is called from the OP1a demuxing logic, which means there * may be no index tables */ if (mxf->nb_index_tables <= 0) return -1; /* find mxf->current_edit_unit so that the next edit unit starts ahead of current_offset */ while (mxf->current_edit_unit >= 0) { if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0) return -1; if (next_ofs <= last_ofs) { /* large next_ofs didn't change or current_edit_unit wrapped * around this fixes the infinite loop on zzuf3.mxf */ av_log(mxf->fc, AV_LOG_ERROR, "next_ofs didn't change. not deriving packet timestamps\n"); return -1; } if (next_ofs > current_offset) break; last_ofs = next_ofs; mxf->current_edit_unit++; } /* not checking mxf->current_edit_unit >= t->nb_ptses here since CBR files may lack IndexEntryArrays */ if (mxf->current_edit_unit < 0) return -1; return next_ofs; } static int mxf_compute_sample_count(MXFContext *mxf, int stream_index, uint64_t *sample_count) { int i, total = 0, size = 0; AVStream *st = mxf->fc->streams[stream_index]; MXFTrack *track = st->priv_data; AVRational time_base = av_inv_q(track->edit_rate); AVRational sample_rate = av_inv_q(st->time_base); const MXFSamplesPerFrame *spf = NULL; if ((sample_rate.num / sample_rate.den) == 48000) spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base); if (!spf) { int remainder = (sample_rate.num * time_base.num) % (time_base.den * sample_rate.den); *sample_count = av_q2d(av_mul_q((AVRational){mxf->current_edit_unit, 1}, av_mul_q(sample_rate, time_base))); if (remainder) av_log(mxf->fc, AV_LOG_WARNING, "seeking detected on stream #%d with time base (%d/%d) and " "sample rate (%d/%d), audio pts won't be accurate.\n", stream_index, time_base.num, time_base.den, sample_rate.num, sample_rate.den); return 0; } while (spf->samples_per_frame[size]) { total += spf->samples_per_frame[size]; size++; } av_assert2(size); *sample_count = (mxf->current_edit_unit / size) * (uint64_t)total; for (i = 0; i < mxf->current_edit_unit % size; i++) { *sample_count += spf->samples_per_frame[i]; } return 0; } static int mxf_set_audio_pts(MXFContext *mxf, AVCodecParameters *par, AVPacket *pkt) { MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data; int64_t bits_per_sample = par->bits_per_coded_sample; if (!bits_per_sample) bits_per_sample = av_get_bits_per_sample(par->codec_id); pkt->pts = track->sample_count; if ( par->channels <= 0 || bits_per_sample <= 0 || par->channels * (int64_t)bits_per_sample < 8) return AVERROR(EINVAL); track->sample_count += pkt->size / (par->channels * (int64_t)bits_per_sample / 8); return 0; } static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt) { KLVPacket klv; MXFContext *mxf = s->priv_data; int ret; while ((ret = klv_read_packet(&klv, s->pb)) == 0) { PRINT_KEY(s, "read packet", klv.key); av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset); if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) { ret = mxf_decrypt_triplet(s, pkt, &klv); if (ret < 0) { av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n"); return ret; } return 0; } if (IS_KLV_KEY(klv.key, mxf_essence_element_key) || IS_KLV_KEY(klv.key, mxf_canopus_essence_element_key) || IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) { int index = mxf_get_stream_index(s, &klv); int64_t next_ofs, next_klv; AVStream *st; MXFTrack *track; AVCodecParameters *par; if (index < 0) { av_log(s, AV_LOG_ERROR, "error getting stream index %"PRIu32"\n", AV_RB32(klv.key + 12)); goto skip; } st = s->streams[index]; track = st->priv_data; if (s->streams[index]->discard == AVDISCARD_ALL) goto skip; next_klv = avio_tell(s->pb) + klv.length; next_ofs = mxf_set_current_edit_unit(mxf, klv.offset); if (next_ofs >= 0 && next_klv > next_ofs) { /* if this check is hit then it's possible OPAtom was treated as OP1a * truncate the packet since it's probably very large (>2 GiB is common) */ avpriv_request_sample(s, "OPAtom misinterpreted as OP1a? " "KLV for edit unit %i extending into " "next edit unit", mxf->current_edit_unit); klv.length = next_ofs - avio_tell(s->pb); } /* check for 8 channels AES3 element */ if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) { ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length); if (ret < 0) { av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n"); return ret; } } else { ret = av_get_packet(s->pb, pkt, klv.length); if (ret < 0) return ret; } pkt->stream_index = index; pkt->pos = klv.offset; par = st->codecpar; if (par->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) { /* mxf->current_edit_unit good - see if we have an * index table to derive timestamps from */ MXFIndexTable *t = &mxf->index_tables[0]; if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) { pkt->dts = mxf->current_edit_unit + t->first_dts; pkt->pts = t->ptses[mxf->current_edit_unit]; } else if (track && track->intra_only) { /* intra-only -> PTS = EditUnit. * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */ pkt->pts = mxf->current_edit_unit; } } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) { ret = mxf_set_audio_pts(mxf, par, pkt); if (ret < 0) return ret; } /* seek for truncated packets */ avio_seek(s->pb, next_klv, SEEK_SET); return 0; } else skip: avio_skip(s->pb, klv.length); } return avio_feof(s->pb) ? AVERROR_EOF : ret; } static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt) { MXFContext *mxf = s->priv_data; int ret, size; int64_t ret64, pos, next_pos; AVStream *st; MXFIndexTable *t; int edit_units; if (mxf->op != OPAtom) return mxf_read_packet_old(s, pkt); // If we have no streams then we basically are at EOF st = mxf_get_opatom_stream(mxf); if (!st) return AVERROR_EOF; /* OPAtom - clip wrapped demuxing */ /* NOTE: mxf_read_header() makes sure nb_index_tables > 0 for OPAtom */ t = &mxf->index_tables[0]; if (mxf->current_edit_unit >= st->duration) return AVERROR_EOF; edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit); if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0) return ret; /* compute size by finding the next edit unit or the end of the essence container * not pretty, but it works */ if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 && (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) { av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n"); return AVERROR_INVALIDDATA; } if ((size = next_pos - pos) <= 0) { av_log(s, AV_LOG_ERROR, "bad size: %i\n", size); return AVERROR_INVALIDDATA; } if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0) return ret64; if ((size = av_get_packet(s->pb, pkt, size)) < 0) return size; pkt->stream_index = st->index; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses && mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) { pkt->dts = mxf->current_edit_unit + t->first_dts; pkt->pts = t->ptses[mxf->current_edit_unit]; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { int ret = mxf_set_audio_pts(mxf, st->codecpar, pkt); if (ret < 0) return ret; } mxf->current_edit_unit += edit_units; return 0; } static int mxf_read_close(AVFormatContext *s) { MXFContext *mxf = s->priv_data; int i; av_freep(&mxf->packages_refs); for (i = 0; i < s->nb_streams; i++) s->streams[i]->priv_data = NULL; for (i = 0; i < mxf->metadata_sets_count; i++) { mxf_free_metadataset(mxf->metadata_sets + i, 1); } av_freep(&mxf->partitions); av_freep(&mxf->metadata_sets); av_freep(&mxf->aesc); av_freep(&mxf->local_tags); if (mxf->index_tables) { for (i = 0; i < mxf->nb_index_tables; i++) { av_freep(&mxf->index_tables[i].segments); av_freep(&mxf->index_tables[i].ptses); av_freep(&mxf->index_tables[i].fake_index); av_freep(&mxf->index_tables[i].offsets); } } av_freep(&mxf->index_tables); return 0; } static int mxf_probe(AVProbeData *p) { const uint8_t *bufp = p->buf; const uint8_t *end = p->buf + p->buf_size; if (p->buf_size < sizeof(mxf_header_partition_pack_key)) return 0; /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */ end -= sizeof(mxf_header_partition_pack_key); for (; bufp < end;) { if (!((bufp[13] - 1) & 0xF2)){ if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) && AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) && AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) && AV_RN16(bufp+12) == AV_RN16(mxf_header_partition_pack_key+12)) return AVPROBE_SCORE_MAX; bufp ++; } else bufp += 10; } return 0; } /* rudimentary byte seek */ /* XXX: use MXF Index */ static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { AVStream *st = s->streams[stream_index]; int64_t seconds; MXFContext* mxf = s->priv_data; int64_t seekpos; int i, ret; MXFIndexTable *t; MXFTrack *source_track = st->priv_data; if(st->codecpar->codec_type == AVMEDIA_TYPE_DATA) return 0; /* if audio then truncate sample_time to EditRate */ if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) sample_time = av_rescale_q(sample_time, st->time_base, av_inv_q(source_track->edit_rate)); if (mxf->nb_index_tables <= 0) { if (!s->bit_rate) return AVERROR_INVALIDDATA; if (sample_time < 0) sample_time = 0; seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den); seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET); if (seekpos < 0) return seekpos; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; } else { t = &mxf->index_tables[0]; /* clamp above zero, else ff_index_search_timestamp() returns negative * this also means we allow seeking before the start */ sample_time = FFMAX(sample_time, 0); if (t->fake_index) { /* The first frames may not be keyframes in presentation order, so * we have to advance the target to be able to find the first * keyframe backwards... */ if (!(flags & AVSEEK_FLAG_ANY) && (flags & AVSEEK_FLAG_BACKWARD) && t->ptses[0] != AV_NOPTS_VALUE && sample_time < t->ptses[0] && (t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME)) sample_time = t->ptses[0]; /* behave as if we have a proper index */ if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0) return sample_time; /* get the stored order index from the display order index */ sample_time += t->offsets[sample_time]; } else { /* no IndexEntryArray (one or more CBR segments) * make sure we don't seek past the end */ sample_time = FFMIN(sample_time, source_track->original_duration - 1); } if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) < 0) return ret; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; avio_seek(s->pb, seekpos, SEEK_SET); } // Update all tracks sample count for (i = 0; i < s->nb_streams; i++) { AVStream *cur_st = s->streams[i]; MXFTrack *cur_track = cur_st->priv_data; uint64_t current_sample_count = 0; if (cur_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { ret = mxf_compute_sample_count(mxf, i, &current_sample_count); if (ret < 0) return ret; cur_track->sample_count = current_sample_count; } } return 0; } AVInputFormat ff_mxf_demuxer = { .name = "mxf", .long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"), .flags = AVFMT_SEEK_TO_PTS, .priv_data_size = sizeof(MXFContext), .read_probe = mxf_probe, .read_header = mxf_read_header, .read_packet = mxf_read_packet, .read_close = mxf_read_close, .read_seek = mxf_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2779_0
crossvul-cpp_data_good_2786_0
/* * MOV demuxer * Copyright (c) 2001 Fabrice Bellard * Copyright (c) 2009 Baptiste Coudurier <baptiste dot coudurier at gmail dot com> * * first version by Francois Revol <revol@free.fr> * seek function by Gael Chardon <gael.dev@4now.net> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include <limits.h> #include <stdint.h> #include "libavutil/attributes.h" #include "libavutil/channel_layout.h" #include "libavutil/internal.h" #include "libavutil/intreadwrite.h" #include "libavutil/intfloat.h" #include "libavutil/mathematics.h" #include "libavutil/time_internal.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/dict.h" #include "libavutil/display.h" #include "libavutil/opt.h" #include "libavutil/aes.h" #include "libavutil/aes_ctr.h" #include "libavutil/pixdesc.h" #include "libavutil/sha.h" #include "libavutil/spherical.h" #include "libavutil/stereo3d.h" #include "libavutil/timecode.h" #include "libavcodec/ac3tab.h" #include "libavcodec/flac.h" #include "libavcodec/mpegaudiodecheader.h" #include "avformat.h" #include "internal.h" #include "avio_internal.h" #include "riff.h" #include "isom.h" #include "libavcodec/get_bits.h" #include "id3v1.h" #include "mov_chan.h" #include "replaygain.h" #if CONFIG_ZLIB #include <zlib.h> #endif #include "qtpalette.h" /* those functions parse an atom */ /* links atom IDs to parse functions */ typedef struct MOVParseTableEntry { uint32_t type; int (*parse)(MOVContext *ctx, AVIOContext *pb, MOVAtom atom); } MOVParseTableEntry; static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom); static int mov_read_mfra(MOVContext *c, AVIOContext *f); static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size, int count, int duration); static int mov_metadata_track_or_disc_number(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { char buf[16]; short current, total = 0; avio_rb16(pb); // unknown current = avio_rb16(pb); if (len >= 6) total = avio_rb16(pb); if (!total) snprintf(buf, sizeof(buf), "%d", current); else snprintf(buf, sizeof(buf), "%d/%d", current, total); c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set(&c->fc->metadata, key, buf, 0); return 0; } static int mov_metadata_int8_bypass_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { /* bypass padding bytes */ avio_r8(pb); avio_r8(pb); avio_r8(pb); c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0); return 0; } static int mov_metadata_int8_no_padding(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set_int(&c->fc->metadata, key, avio_r8(pb), 0); return 0; } static int mov_metadata_gnre(MOVContext *c, AVIOContext *pb, unsigned len, const char *key) { short genre; avio_r8(pb); // unknown genre = avio_r8(pb); if (genre < 1 || genre > ID3v1_GENRE_MAX) return 0; c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set(&c->fc->metadata, key, ff_id3v1_genre_str[genre-1], 0); return 0; } static const uint32_t mac_to_unicode[128] = { 0x00C4,0x00C5,0x00C7,0x00C9,0x00D1,0x00D6,0x00DC,0x00E1, 0x00E0,0x00E2,0x00E4,0x00E3,0x00E5,0x00E7,0x00E9,0x00E8, 0x00EA,0x00EB,0x00ED,0x00EC,0x00EE,0x00EF,0x00F1,0x00F3, 0x00F2,0x00F4,0x00F6,0x00F5,0x00FA,0x00F9,0x00FB,0x00FC, 0x2020,0x00B0,0x00A2,0x00A3,0x00A7,0x2022,0x00B6,0x00DF, 0x00AE,0x00A9,0x2122,0x00B4,0x00A8,0x2260,0x00C6,0x00D8, 0x221E,0x00B1,0x2264,0x2265,0x00A5,0x00B5,0x2202,0x2211, 0x220F,0x03C0,0x222B,0x00AA,0x00BA,0x03A9,0x00E6,0x00F8, 0x00BF,0x00A1,0x00AC,0x221A,0x0192,0x2248,0x2206,0x00AB, 0x00BB,0x2026,0x00A0,0x00C0,0x00C3,0x00D5,0x0152,0x0153, 0x2013,0x2014,0x201C,0x201D,0x2018,0x2019,0x00F7,0x25CA, 0x00FF,0x0178,0x2044,0x20AC,0x2039,0x203A,0xFB01,0xFB02, 0x2021,0x00B7,0x201A,0x201E,0x2030,0x00C2,0x00CA,0x00C1, 0x00CB,0x00C8,0x00CD,0x00CE,0x00CF,0x00CC,0x00D3,0x00D4, 0xF8FF,0x00D2,0x00DA,0x00DB,0x00D9,0x0131,0x02C6,0x02DC, 0x00AF,0x02D8,0x02D9,0x02DA,0x00B8,0x02DD,0x02DB,0x02C7, }; static int mov_read_mac_string(MOVContext *c, AVIOContext *pb, int len, char *dst, int dstlen) { char *p = dst; char *end = dst+dstlen-1; int i; for (i = 0; i < len; i++) { uint8_t t, c = avio_r8(pb); if (p >= end) continue; if (c < 0x80) *p++ = c; else if (p < end) PUT_UTF8(mac_to_unicode[c-0x80], t, if (p < end) *p++ = t;); } *p = 0; return p - dst; } static int mov_read_covr(MOVContext *c, AVIOContext *pb, int type, int len) { AVPacket pkt; AVStream *st; MOVStreamContext *sc; enum AVCodecID id; int ret; switch (type) { case 0xd: id = AV_CODEC_ID_MJPEG; break; case 0xe: id = AV_CODEC_ID_PNG; break; case 0x1b: id = AV_CODEC_ID_BMP; break; default: av_log(c->fc, AV_LOG_WARNING, "Unknown cover type: 0x%x.\n", type); avio_skip(pb, len); return 0; } st = avformat_new_stream(c->fc, NULL); if (!st) return AVERROR(ENOMEM); sc = av_mallocz(sizeof(*sc)); if (!sc) return AVERROR(ENOMEM); st->priv_data = sc; ret = av_get_packet(pb, &pkt, len); if (ret < 0) return ret; if (pkt.size >= 8 && id != AV_CODEC_ID_BMP) { if (AV_RB64(pkt.data) == 0x89504e470d0a1a0a) { id = AV_CODEC_ID_PNG; } else { id = AV_CODEC_ID_MJPEG; } } st->disposition |= AV_DISPOSITION_ATTACHED_PIC; st->attached_pic = pkt; st->attached_pic.stream_index = st->index; st->attached_pic.flags |= AV_PKT_FLAG_KEY; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = id; return 0; } // 3GPP TS 26.244 static int mov_metadata_loci(MOVContext *c, AVIOContext *pb, unsigned len) { char language[4] = { 0 }; char buf[200], place[100]; uint16_t langcode = 0; double longitude, latitude, altitude; const char *key = "location"; if (len < 4 + 2 + 1 + 1 + 4 + 4 + 4) { av_log(c->fc, AV_LOG_ERROR, "loci too short\n"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); // version+flags langcode = avio_rb16(pb); ff_mov_lang_to_iso639(langcode, language); len -= 6; len -= avio_get_str(pb, len, place, sizeof(place)); if (len < 1) { av_log(c->fc, AV_LOG_ERROR, "place name too long\n"); return AVERROR_INVALIDDATA; } avio_skip(pb, 1); // role len -= 1; if (len < 12) { av_log(c->fc, AV_LOG_ERROR, "loci too short (%u bytes left, need at least %d)\n", len, 12); return AVERROR_INVALIDDATA; } longitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16); latitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16); altitude = ((int32_t) avio_rb32(pb)) / (float) (1 << 16); // Try to output in the same format as the ?xyz field snprintf(buf, sizeof(buf), "%+08.4f%+09.4f", latitude, longitude); if (altitude) av_strlcatf(buf, sizeof(buf), "%+f", altitude); av_strlcatf(buf, sizeof(buf), "/%s", place); if (*language && strcmp(language, "und")) { char key2[16]; snprintf(key2, sizeof(key2), "%s-%s", key, language); av_dict_set(&c->fc->metadata, key2, buf, 0); } c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; return av_dict_set(&c->fc->metadata, key, buf, 0); } static int mov_metadata_hmmt(MOVContext *c, AVIOContext *pb, unsigned len) { int i, n_hmmt; if (len < 2) return 0; if (c->ignore_chapters) return 0; n_hmmt = avio_rb32(pb); for (i = 0; i < n_hmmt && !pb->eof_reached; i++) { int moment_time = avio_rb32(pb); avpriv_new_chapter(c->fc, i, av_make_q(1, 1000), moment_time, AV_NOPTS_VALUE, NULL); } return 0; } static int mov_read_udta_string(MOVContext *c, AVIOContext *pb, MOVAtom atom) { char tmp_key[5]; char key2[32], language[4] = {0}; char *str = NULL; const char *key = NULL; uint16_t langcode = 0; uint32_t data_type = 0, str_size, str_size_alloc; int (*parse)(MOVContext*, AVIOContext*, unsigned, const char*) = NULL; int raw = 0; int num = 0; switch (atom.type) { case MKTAG( '@','P','R','M'): key = "premiere_version"; raw = 1; break; case MKTAG( '@','P','R','Q'): key = "quicktime_version"; raw = 1; break; case MKTAG( 'X','M','P','_'): if (c->export_xmp) { key = "xmp"; raw = 1; } break; case MKTAG( 'a','A','R','T'): key = "album_artist"; break; case MKTAG( 'a','k','I','D'): key = "account_type"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'a','p','I','D'): key = "account_id"; break; case MKTAG( 'c','a','t','g'): key = "category"; break; case MKTAG( 'c','p','i','l'): key = "compilation"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'c','p','r','t'): key = "copyright"; break; case MKTAG( 'd','e','s','c'): key = "description"; break; case MKTAG( 'd','i','s','k'): key = "disc"; parse = mov_metadata_track_or_disc_number; break; case MKTAG( 'e','g','i','d'): key = "episode_uid"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'F','I','R','M'): key = "firmware"; raw = 1; break; case MKTAG( 'g','n','r','e'): key = "genre"; parse = mov_metadata_gnre; break; case MKTAG( 'h','d','v','d'): key = "hd_video"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'H','M','M','T'): return mov_metadata_hmmt(c, pb, atom.size); case MKTAG( 'k','e','y','w'): key = "keywords"; break; case MKTAG( 'l','d','e','s'): key = "synopsis"; break; case MKTAG( 'l','o','c','i'): return mov_metadata_loci(c, pb, atom.size); case MKTAG( 'p','c','s','t'): key = "podcast"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'p','g','a','p'): key = "gapless_playback"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 'p','u','r','d'): key = "purchase_date"; break; case MKTAG( 'r','t','n','g'): key = "rating"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 's','o','a','a'): key = "sort_album_artist"; break; case MKTAG( 's','o','a','l'): key = "sort_album"; break; case MKTAG( 's','o','a','r'): key = "sort_artist"; break; case MKTAG( 's','o','c','o'): key = "sort_composer"; break; case MKTAG( 's','o','n','m'): key = "sort_name"; break; case MKTAG( 's','o','s','n'): key = "sort_show"; break; case MKTAG( 's','t','i','k'): key = "media_type"; parse = mov_metadata_int8_no_padding; break; case MKTAG( 't','r','k','n'): key = "track"; parse = mov_metadata_track_or_disc_number; break; case MKTAG( 't','v','e','n'): key = "episode_id"; break; case MKTAG( 't','v','e','s'): key = "episode_sort"; parse = mov_metadata_int8_bypass_padding; break; case MKTAG( 't','v','n','n'): key = "network"; break; case MKTAG( 't','v','s','h'): key = "show"; break; case MKTAG( 't','v','s','n'): key = "season_number"; parse = mov_metadata_int8_bypass_padding; break; case MKTAG(0xa9,'A','R','T'): key = "artist"; break; case MKTAG(0xa9,'P','R','D'): key = "producer"; break; case MKTAG(0xa9,'a','l','b'): key = "album"; break; case MKTAG(0xa9,'a','u','t'): key = "artist"; break; case MKTAG(0xa9,'c','h','p'): key = "chapter"; break; case MKTAG(0xa9,'c','m','t'): key = "comment"; break; case MKTAG(0xa9,'c','o','m'): key = "composer"; break; case MKTAG(0xa9,'c','p','y'): key = "copyright"; break; case MKTAG(0xa9,'d','a','y'): key = "date"; break; case MKTAG(0xa9,'d','i','r'): key = "director"; break; case MKTAG(0xa9,'d','i','s'): key = "disclaimer"; break; case MKTAG(0xa9,'e','d','1'): key = "edit_date"; break; case MKTAG(0xa9,'e','n','c'): key = "encoder"; break; case MKTAG(0xa9,'f','m','t'): key = "original_format"; break; case MKTAG(0xa9,'g','e','n'): key = "genre"; break; case MKTAG(0xa9,'g','r','p'): key = "grouping"; break; case MKTAG(0xa9,'h','s','t'): key = "host_computer"; break; case MKTAG(0xa9,'i','n','f'): key = "comment"; break; case MKTAG(0xa9,'l','y','r'): key = "lyrics"; break; case MKTAG(0xa9,'m','a','k'): key = "make"; break; case MKTAG(0xa9,'m','o','d'): key = "model"; break; case MKTAG(0xa9,'n','a','m'): key = "title"; break; case MKTAG(0xa9,'o','p','e'): key = "original_artist"; break; case MKTAG(0xa9,'p','r','d'): key = "producer"; break; case MKTAG(0xa9,'p','r','f'): key = "performers"; break; case MKTAG(0xa9,'r','e','q'): key = "playback_requirements"; break; case MKTAG(0xa9,'s','r','c'): key = "original_source"; break; case MKTAG(0xa9,'s','t','3'): key = "subtitle"; break; case MKTAG(0xa9,'s','w','r'): key = "encoder"; break; case MKTAG(0xa9,'t','o','o'): key = "encoder"; break; case MKTAG(0xa9,'t','r','k'): key = "track"; break; case MKTAG(0xa9,'u','r','l'): key = "URL"; break; case MKTAG(0xa9,'w','r','n'): key = "warning"; break; case MKTAG(0xa9,'w','r','t'): key = "composer"; break; case MKTAG(0xa9,'x','y','z'): key = "location"; break; } retry: if (c->itunes_metadata && atom.size > 8) { int data_size = avio_rb32(pb); int tag = avio_rl32(pb); if (tag == MKTAG('d','a','t','a') && data_size <= atom.size) { data_type = avio_rb32(pb); // type avio_rb32(pb); // unknown str_size = data_size - 16; atom.size -= 16; if (atom.type == MKTAG('c', 'o', 'v', 'r')) { int ret = mov_read_covr(c, pb, data_type, str_size); if (ret < 0) { av_log(c->fc, AV_LOG_ERROR, "Error parsing cover art.\n"); } return ret; } else if (!key && c->found_hdlr_mdta && c->meta_keys) { uint32_t index = AV_RB32(&atom.type); if (index < c->meta_keys_count && index > 0) { key = c->meta_keys[index]; } else { av_log(c->fc, AV_LOG_WARNING, "The index of 'data' is out of range: %"PRId32" < 1 or >= %d.\n", index, c->meta_keys_count); } } } else return 0; } else if (atom.size > 4 && key && !c->itunes_metadata && !raw) { str_size = avio_rb16(pb); // string length if (str_size > atom.size) { raw = 1; avio_seek(pb, -2, SEEK_CUR); av_log(c->fc, AV_LOG_WARNING, "UDTA parsing failed retrying raw\n"); goto retry; } langcode = avio_rb16(pb); ff_mov_lang_to_iso639(langcode, language); atom.size -= 4; } else str_size = atom.size; if (c->export_all && !key) { snprintf(tmp_key, 5, "%.4s", (char*)&atom.type); key = tmp_key; } if (!key) return 0; if (atom.size < 0 || str_size >= INT_MAX/2) return AVERROR_INVALIDDATA; // Allocates enough space if data_type is a int32 or float32 number, otherwise // worst-case requirement for output string in case of utf8 coded input num = (data_type >= 21 && data_type <= 23); str_size_alloc = (num ? 512 : (raw ? str_size : str_size * 2)) + 1; str = av_mallocz(str_size_alloc); if (!str) return AVERROR(ENOMEM); if (parse) parse(c, pb, str_size, key); else { if (!raw && (data_type == 3 || (data_type == 0 && (langcode < 0x400 || langcode == 0x7fff)))) { // MAC Encoded mov_read_mac_string(c, pb, str_size, str, str_size_alloc); } else if (data_type == 21) { // BE signed integer, variable size int val = 0; if (str_size == 1) val = (int8_t)avio_r8(pb); else if (str_size == 2) val = (int16_t)avio_rb16(pb); else if (str_size == 3) val = ((int32_t)(avio_rb24(pb)<<8))>>8; else if (str_size == 4) val = (int32_t)avio_rb32(pb); if (snprintf(str, str_size_alloc, "%d", val) >= str_size_alloc) { av_log(c->fc, AV_LOG_ERROR, "Failed to store the number (%d) in string.\n", val); av_free(str); return AVERROR_INVALIDDATA; } } else if (data_type == 22) { // BE unsigned integer, variable size unsigned int val = 0; if (str_size == 1) val = avio_r8(pb); else if (str_size == 2) val = avio_rb16(pb); else if (str_size == 3) val = avio_rb24(pb); else if (str_size == 4) val = avio_rb32(pb); if (snprintf(str, str_size_alloc, "%u", val) >= str_size_alloc) { av_log(c->fc, AV_LOG_ERROR, "Failed to store the number (%u) in string.\n", val); av_free(str); return AVERROR_INVALIDDATA; } } else if (data_type == 23 && str_size >= 4) { // BE float32 float val = av_int2float(avio_rb32(pb)); if (snprintf(str, str_size_alloc, "%f", val) >= str_size_alloc) { av_log(c->fc, AV_LOG_ERROR, "Failed to store the float32 number (%f) in string.\n", val); av_free(str); return AVERROR_INVALIDDATA; } } else { int ret = ffio_read_size(pb, str, str_size); if (ret < 0) { av_free(str); return ret; } str[str_size] = 0; } c->fc->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED; av_dict_set(&c->fc->metadata, key, str, 0); if (*language && strcmp(language, "und")) { snprintf(key2, sizeof(key2), "%s-%s", key, language); av_dict_set(&c->fc->metadata, key2, str, 0); } if (!strcmp(key, "encoder")) { int major, minor, micro; if (sscanf(str, "HandBrake %d.%d.%d", &major, &minor, &micro) == 3) { c->handbrake_version = 1000000*major + 1000*minor + micro; } } } av_freep(&str); return 0; } static int mov_read_chpl(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t start; int i, nb_chapters, str_len, version; char str[256+1]; int ret; if (c->ignore_chapters) return 0; if ((atom.size -= 5) < 0) return 0; version = avio_r8(pb); avio_rb24(pb); if (version) avio_rb32(pb); // ??? nb_chapters = avio_r8(pb); for (i = 0; i < nb_chapters; i++) { if (atom.size < 9) return 0; start = avio_rb64(pb); str_len = avio_r8(pb); if ((atom.size -= 9+str_len) < 0) return 0; ret = ffio_read_size(pb, str, str_len); if (ret < 0) return ret; str[str_len] = 0; avpriv_new_chapter(c->fc, i, (AVRational){1,10000000}, start, AV_NOPTS_VALUE, str); } return 0; } #define MIN_DATA_ENTRY_BOX_SIZE 12 static int mov_read_dref(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int entries, i, j; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (!entries || entries > (atom.size - 1) / MIN_DATA_ENTRY_BOX_SIZE + 1 || entries >= UINT_MAX / sizeof(*sc->drefs)) return AVERROR_INVALIDDATA; sc->drefs_count = 0; av_free(sc->drefs); sc->drefs_count = 0; sc->drefs = av_mallocz(entries * sizeof(*sc->drefs)); if (!sc->drefs) return AVERROR(ENOMEM); sc->drefs_count = entries; for (i = 0; i < entries; i++) { MOVDref *dref = &sc->drefs[i]; uint32_t size = avio_rb32(pb); int64_t next = avio_tell(pb) + size - 4; if (size < 12) return AVERROR_INVALIDDATA; dref->type = avio_rl32(pb); avio_rb32(pb); // version + flags if (dref->type == MKTAG('a','l','i','s') && size > 150) { /* macintosh alias record */ uint16_t volume_len, len; int16_t type; int ret; avio_skip(pb, 10); volume_len = avio_r8(pb); volume_len = FFMIN(volume_len, 27); ret = ffio_read_size(pb, dref->volume, 27); if (ret < 0) return ret; dref->volume[volume_len] = 0; av_log(c->fc, AV_LOG_DEBUG, "volume %s, len %d\n", dref->volume, volume_len); avio_skip(pb, 12); len = avio_r8(pb); len = FFMIN(len, 63); ret = ffio_read_size(pb, dref->filename, 63); if (ret < 0) return ret; dref->filename[len] = 0; av_log(c->fc, AV_LOG_DEBUG, "filename %s, len %d\n", dref->filename, len); avio_skip(pb, 16); /* read next level up_from_alias/down_to_target */ dref->nlvl_from = avio_rb16(pb); dref->nlvl_to = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "nlvl from %d, nlvl to %d\n", dref->nlvl_from, dref->nlvl_to); avio_skip(pb, 16); for (type = 0; type != -1 && avio_tell(pb) < next; ) { if(avio_feof(pb)) return AVERROR_EOF; type = avio_rb16(pb); len = avio_rb16(pb); av_log(c->fc, AV_LOG_DEBUG, "type %d, len %d\n", type, len); if (len&1) len += 1; if (type == 2) { // absolute path av_free(dref->path); dref->path = av_mallocz(len+1); if (!dref->path) return AVERROR(ENOMEM); ret = ffio_read_size(pb, dref->path, len); if (ret < 0) { av_freep(&dref->path); return ret; } if (len > volume_len && !strncmp(dref->path, dref->volume, volume_len)) { len -= volume_len; memmove(dref->path, dref->path+volume_len, len); dref->path[len] = 0; } // trim string of any ending zeros for (j = len - 1; j >= 0; j--) { if (dref->path[j] == 0) len--; else break; } for (j = 0; j < len; j++) if (dref->path[j] == ':' || dref->path[j] == 0) dref->path[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "path %s\n", dref->path); } else if (type == 0) { // directory name av_free(dref->dir); dref->dir = av_malloc(len+1); if (!dref->dir) return AVERROR(ENOMEM); ret = ffio_read_size(pb, dref->dir, len); if (ret < 0) { av_freep(&dref->dir); return ret; } dref->dir[len] = 0; for (j = 0; j < len; j++) if (dref->dir[j] == ':') dref->dir[j] = '/'; av_log(c->fc, AV_LOG_DEBUG, "dir %s\n", dref->dir); } else avio_skip(pb, len); } } else { av_log(c->fc, AV_LOG_DEBUG, "Unknown dref type 0x%08"PRIx32" size %"PRIu32"\n", dref->type, size); entries--; i--; } avio_seek(pb, next, SEEK_SET); } return 0; } static int mov_read_hdlr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint32_t type; uint32_t ctype; int64_t title_size; char *title_str; int ret; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ /* component type */ ctype = avio_rl32(pb); type = avio_rl32(pb); /* component subtype */ av_log(c->fc, AV_LOG_TRACE, "ctype=%s\n", av_fourcc2str(ctype)); av_log(c->fc, AV_LOG_TRACE, "stype=%s\n", av_fourcc2str(type)); if (c->trak_index < 0) { // meta not inside a trak if (type == MKTAG('m','d','t','a')) { c->found_hdlr_mdta = 1; } return 0; } st = c->fc->streams[c->fc->nb_streams-1]; if (type == MKTAG('v','i','d','e')) st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; else if (type == MKTAG('s','o','u','n')) st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; else if (type == MKTAG('m','1','a',' ')) st->codecpar->codec_id = AV_CODEC_ID_MP2; else if ((type == MKTAG('s','u','b','p')) || (type == MKTAG('c','l','c','p'))) st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; avio_rb32(pb); /* component manufacture */ avio_rb32(pb); /* component flags */ avio_rb32(pb); /* component flags mask */ title_size = atom.size - 24; if (title_size > 0) { if (title_size > FFMIN(INT_MAX, SIZE_MAX-1)) return AVERROR_INVALIDDATA; title_str = av_malloc(title_size + 1); /* Add null terminator */ if (!title_str) return AVERROR(ENOMEM); ret = ffio_read_size(pb, title_str, title_size); if (ret < 0) { av_freep(&title_str); return ret; } title_str[title_size] = 0; if (title_str[0]) { int off = (!c->isom && title_str[0] == title_size - 1); av_dict_set(&st->metadata, "handler_name", title_str + off, 0); } av_freep(&title_str); } return 0; } int ff_mov_read_esds(AVFormatContext *fc, AVIOContext *pb) { AVStream *st; int tag; if (fc->nb_streams < 1) return 0; st = fc->streams[fc->nb_streams-1]; avio_rb32(pb); /* version + flags */ ff_mp4_read_descr(fc, pb, &tag); if (tag == MP4ESDescrTag) { ff_mp4_parse_es_descr(pb, NULL); } else avio_rb16(pb); /* ID */ ff_mp4_read_descr(fc, pb, &tag); if (tag == MP4DecConfigDescrTag) ff_mp4_read_dec_config_descr(fc, st, pb); return 0; } static int mov_read_esds(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return ff_mov_read_esds(c->fc, pb); } static int mov_read_dac3(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; enum AVAudioServiceType *ast; int ac3info, acmod, lfeon, bsmod; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE, sizeof(*ast)); if (!ast) return AVERROR(ENOMEM); ac3info = avio_rb24(pb); bsmod = (ac3info >> 14) & 0x7; acmod = (ac3info >> 11) & 0x7; lfeon = (ac3info >> 10) & 0x1; st->codecpar->channels = ((int[]){2,1,2,3,3,4,4,5})[acmod] + lfeon; st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod]; if (lfeon) st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY; *ast = bsmod; if (st->codecpar->channels > 1 && bsmod == 0x7) *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->audio_service_type = *ast; FF_ENABLE_DEPRECATION_WARNINGS #endif return 0; } static int mov_read_dec3(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; enum AVAudioServiceType *ast; int eac3info, acmod, lfeon, bsmod; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; ast = (enum AVAudioServiceType*)av_stream_new_side_data(st, AV_PKT_DATA_AUDIO_SERVICE_TYPE, sizeof(*ast)); if (!ast) return AVERROR(ENOMEM); /* No need to parse fields for additional independent substreams and its * associated dependent substreams since libavcodec's E-AC-3 decoder * does not support them yet. */ avio_rb16(pb); /* data_rate and num_ind_sub */ eac3info = avio_rb24(pb); bsmod = (eac3info >> 12) & 0x1f; acmod = (eac3info >> 9) & 0x7; lfeon = (eac3info >> 8) & 0x1; st->codecpar->channel_layout = avpriv_ac3_channel_layout_tab[acmod]; if (lfeon) st->codecpar->channel_layout |= AV_CH_LOW_FREQUENCY; st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout); *ast = bsmod; if (st->codecpar->channels > 1 && bsmod == 0x7) *ast = AV_AUDIO_SERVICE_TYPE_KARAOKE; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->audio_service_type = *ast; FF_ENABLE_DEPRECATION_WARNINGS #endif return 0; } static int mov_read_ddts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { const uint32_t ddts_size = 20; AVStream *st = NULL; uint8_t *buf = NULL; uint32_t frame_duration_code = 0; uint32_t channel_layout_code = 0; GetBitContext gb; buf = av_malloc(ddts_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!buf) { return AVERROR(ENOMEM); } if (avio_read(pb, buf, ddts_size) < ddts_size) { av_free(buf); return AVERROR_INVALIDDATA; } init_get_bits(&gb, buf, 8*ddts_size); if (c->fc->nb_streams < 1) { av_free(buf); return 0; } st = c->fc->streams[c->fc->nb_streams-1]; st->codecpar->sample_rate = get_bits_long(&gb, 32); if (st->codecpar->sample_rate <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate); av_free(buf); return AVERROR_INVALIDDATA; } skip_bits_long(&gb, 32); /* max bitrate */ st->codecpar->bit_rate = get_bits_long(&gb, 32); st->codecpar->bits_per_coded_sample = get_bits(&gb, 8); frame_duration_code = get_bits(&gb, 2); skip_bits(&gb, 30); /* various fields */ channel_layout_code = get_bits(&gb, 16); st->codecpar->frame_size = (frame_duration_code == 0) ? 512 : (frame_duration_code == 1) ? 1024 : (frame_duration_code == 2) ? 2048 : (frame_duration_code == 3) ? 4096 : 0; if (channel_layout_code > 0xff) { av_log(c->fc, AV_LOG_WARNING, "Unsupported DTS audio channel layout"); } st->codecpar->channel_layout = ((channel_layout_code & 0x1) ? AV_CH_FRONT_CENTER : 0) | ((channel_layout_code & 0x2) ? AV_CH_FRONT_LEFT : 0) | ((channel_layout_code & 0x2) ? AV_CH_FRONT_RIGHT : 0) | ((channel_layout_code & 0x4) ? AV_CH_SIDE_LEFT : 0) | ((channel_layout_code & 0x4) ? AV_CH_SIDE_RIGHT : 0) | ((channel_layout_code & 0x8) ? AV_CH_LOW_FREQUENCY : 0); st->codecpar->channels = av_get_channel_layout_nb_channels(st->codecpar->channel_layout); av_free(buf); return 0; } static int mov_read_chan(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size < 16) return 0; /* skip version and flags */ avio_skip(pb, 4); ff_mov_read_chan(c->fc, pb, st, atom.size - 4); return 0; } static int mov_read_wfex(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((ret = ff_get_wav_header(c->fc, pb, st->codecpar, atom.size, 0)) < 0) av_log(c->fc, AV_LOG_WARNING, "get_wav_header failed\n"); return ret; } static int mov_read_pasp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { const int num = avio_rb32(pb); const int den = avio_rb32(pb); AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((st->sample_aspect_ratio.den != 1 || st->sample_aspect_ratio.num) && // default (den != st->sample_aspect_ratio.den || num != st->sample_aspect_ratio.num)) { av_log(c->fc, AV_LOG_WARNING, "sample aspect ratio already set to %d:%d, ignoring 'pasp' atom (%d:%d)\n", st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, num, den); } else if (den != 0) { av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, num, den, 32767); } return 0; } /* this atom contains actual media data */ static int mov_read_mdat(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (atom.size == 0) /* wrong one (MP4) */ return 0; c->found_mdat=1; return 0; /* now go for moov */ } #define DRM_BLOB_SIZE 56 static int mov_read_adrm(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint8_t intermediate_key[20]; uint8_t intermediate_iv[20]; uint8_t input[64]; uint8_t output[64]; uint8_t file_checksum[20]; uint8_t calculated_checksum[20]; struct AVSHA *sha; int i; int ret = 0; uint8_t *activation_bytes = c->activation_bytes; uint8_t *fixed_key = c->audible_fixed_key; c->aax_mode = 1; sha = av_sha_alloc(); if (!sha) return AVERROR(ENOMEM); c->aes_decrypt = av_aes_alloc(); if (!c->aes_decrypt) { ret = AVERROR(ENOMEM); goto fail; } /* drm blob processing */ avio_read(pb, output, 8); // go to offset 8, absolute position 0x251 avio_read(pb, input, DRM_BLOB_SIZE); avio_read(pb, output, 4); // go to offset 4, absolute position 0x28d avio_read(pb, file_checksum, 20); av_log(c->fc, AV_LOG_INFO, "[aax] file checksum == "); // required by external tools for (i = 0; i < 20; i++) av_log(c->fc, AV_LOG_INFO, "%02x", file_checksum[i]); av_log(c->fc, AV_LOG_INFO, "\n"); /* verify activation data */ if (!activation_bytes) { av_log(c->fc, AV_LOG_WARNING, "[aax] activation_bytes option is missing!\n"); ret = 0; /* allow ffprobe to continue working on .aax files */ goto fail; } if (c->activation_bytes_size != 4) { av_log(c->fc, AV_LOG_FATAL, "[aax] activation_bytes value needs to be 4 bytes!\n"); ret = AVERROR(EINVAL); goto fail; } /* verify fixed key */ if (c->audible_fixed_key_size != 16) { av_log(c->fc, AV_LOG_FATAL, "[aax] audible_fixed_key value needs to be 16 bytes!\n"); ret = AVERROR(EINVAL); goto fail; } /* AAX (and AAX+) key derivation */ av_sha_init(sha, 160); av_sha_update(sha, fixed_key, 16); av_sha_update(sha, activation_bytes, 4); av_sha_final(sha, intermediate_key); av_sha_init(sha, 160); av_sha_update(sha, fixed_key, 16); av_sha_update(sha, intermediate_key, 20); av_sha_update(sha, activation_bytes, 4); av_sha_final(sha, intermediate_iv); av_sha_init(sha, 160); av_sha_update(sha, intermediate_key, 16); av_sha_update(sha, intermediate_iv, 16); av_sha_final(sha, calculated_checksum); if (memcmp(calculated_checksum, file_checksum, 20)) { // critical error av_log(c->fc, AV_LOG_ERROR, "[aax] mismatch in checksums!\n"); ret = AVERROR_INVALIDDATA; goto fail; } av_aes_init(c->aes_decrypt, intermediate_key, 128, 1); av_aes_crypt(c->aes_decrypt, output, input, DRM_BLOB_SIZE >> 4, intermediate_iv, 1); for (i = 0; i < 4; i++) { // file data (in output) is stored in big-endian mode if (activation_bytes[i] != output[3 - i]) { // critical error av_log(c->fc, AV_LOG_ERROR, "[aax] error in drm blob decryption!\n"); ret = AVERROR_INVALIDDATA; goto fail; } } memcpy(c->file_key, output + 8, 16); memcpy(input, output + 26, 16); av_sha_init(sha, 160); av_sha_update(sha, input, 16); av_sha_update(sha, c->file_key, 16); av_sha_update(sha, fixed_key, 16); av_sha_final(sha, c->file_iv); fail: av_free(sha); return ret; } // Audible AAX (and AAX+) bytestream decryption static int aax_filter(uint8_t *input, int size, MOVContext *c) { int blocks = 0; unsigned char iv[16]; memcpy(iv, c->file_iv, 16); // iv is overwritten blocks = size >> 4; // trailing bytes are not encrypted! av_aes_init(c->aes_decrypt, c->file_key, 128, 1); av_aes_crypt(c->aes_decrypt, input, input, blocks, iv, 1); return 0; } /* read major brand, minor version and compatible brands and store them as metadata */ static int mov_read_ftyp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint32_t minor_ver; int comp_brand_size; char* comp_brands_str; uint8_t type[5] = {0}; int ret = ffio_read_size(pb, type, 4); if (ret < 0) return ret; if (strcmp(type, "qt ")) c->isom = 1; av_log(c->fc, AV_LOG_DEBUG, "ISO: File Type Major Brand: %.4s\n",(char *)&type); av_dict_set(&c->fc->metadata, "major_brand", type, 0); minor_ver = avio_rb32(pb); /* minor version */ av_dict_set_int(&c->fc->metadata, "minor_version", minor_ver, 0); comp_brand_size = atom.size - 8; if (comp_brand_size < 0) return AVERROR_INVALIDDATA; comp_brands_str = av_malloc(comp_brand_size + 1); /* Add null terminator */ if (!comp_brands_str) return AVERROR(ENOMEM); ret = ffio_read_size(pb, comp_brands_str, comp_brand_size); if (ret < 0) { av_freep(&comp_brands_str); return ret; } comp_brands_str[comp_brand_size] = 0; av_dict_set(&c->fc->metadata, "compatible_brands", comp_brands_str, 0); av_freep(&comp_brands_str); return 0; } /* this atom should contain all header atoms */ static int mov_read_moov(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; if (c->found_moov) { av_log(c->fc, AV_LOG_WARNING, "Found duplicated MOOV Atom. Skipped it\n"); avio_skip(pb, atom.size); return 0; } if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; /* we parsed the 'moov' atom, we can terminate the parsing as soon as we find the 'mdat' */ /* so we don't parse the whole file if over a network */ c->found_moov=1; return 0; /* now go for mdat */ } static int mov_read_moof(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (!c->has_looked_for_mfra && c->use_mfra_for > 0) { c->has_looked_for_mfra = 1; if (pb->seekable & AVIO_SEEKABLE_NORMAL) { int ret; av_log(c->fc, AV_LOG_VERBOSE, "stream has moof boxes, will look " "for a mfra\n"); if ((ret = mov_read_mfra(c, pb)) < 0) { av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but failed to " "read the mfra (may be a live ismv)\n"); } } else { av_log(c->fc, AV_LOG_VERBOSE, "found a moof box but stream is not " "seekable, can not look for mfra\n"); } } c->fragment.moof_offset = c->fragment.implicit_offset = avio_tell(pb) - 8; av_log(c->fc, AV_LOG_TRACE, "moof offset %"PRIx64"\n", c->fragment.moof_offset); return mov_read_default(c, pb, atom); } static void mov_metadata_creation_time(AVDictionary **metadata, int64_t time) { if (time) { if(time >= 2082844800) time -= 2082844800; /* seconds between 1904-01-01 and Epoch */ if ((int64_t)(time * 1000000ULL) / 1000000 != time) { av_log(NULL, AV_LOG_DEBUG, "creation_time is not representable\n"); return; } avpriv_dict_set_timestamp(metadata, "creation_time", time * 1000000); } } static int mov_read_mdhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int version; char language[4] = {0}; unsigned lang; int64_t creation_time; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; if (sc->time_scale) { av_log(c->fc, AV_LOG_ERROR, "Multiple mdhd?\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version > 1) { avpriv_request_sample(c->fc, "Version %d", version); return AVERROR_PATCHWELCOME; } avio_rb24(pb); /* flags */ if (version == 1) { creation_time = avio_rb64(pb); avio_rb64(pb); } else { creation_time = avio_rb32(pb); avio_rb32(pb); /* modification time */ } mov_metadata_creation_time(&st->metadata, creation_time); sc->time_scale = avio_rb32(pb); if (sc->time_scale <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid mdhd time scale %d, defaulting to 1\n", sc->time_scale); sc->time_scale = 1; } st->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */ lang = avio_rb16(pb); /* language */ if (ff_mov_lang_to_iso639(lang, language)) av_dict_set(&st->metadata, "language", language, 0); avio_rb16(pb); /* quality */ return 0; } static int mov_read_mvhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int i; int64_t creation_time; int version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ if (version == 1) { creation_time = avio_rb64(pb); avio_rb64(pb); } else { creation_time = avio_rb32(pb); avio_rb32(pb); /* modification time */ } mov_metadata_creation_time(&c->fc->metadata, creation_time); c->time_scale = avio_rb32(pb); /* time scale */ if (c->time_scale <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid mvhd time scale %d, defaulting to 1\n", c->time_scale); c->time_scale = 1; } av_log(c->fc, AV_LOG_TRACE, "time scale = %i\n", c->time_scale); c->duration = (version == 1) ? avio_rb64(pb) : avio_rb32(pb); /* duration */ // set the AVCodecContext duration because the duration of individual tracks // may be inaccurate if (c->time_scale > 0 && !c->trex_data) c->fc->duration = av_rescale(c->duration, AV_TIME_BASE, c->time_scale); avio_rb32(pb); /* preferred scale */ avio_rb16(pb); /* preferred volume */ avio_skip(pb, 10); /* reserved */ /* movie display matrix, store it in main context and use it later on */ for (i = 0; i < 3; i++) { c->movie_display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point c->movie_display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point c->movie_display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point } avio_rb32(pb); /* preview time */ avio_rb32(pb); /* preview duration */ avio_rb32(pb); /* poster time */ avio_rb32(pb); /* selection time */ avio_rb32(pb); /* selection duration */ avio_rb32(pb); /* current time */ avio_rb32(pb); /* next track ID */ return 0; } static int mov_read_enda(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int little_endian; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; little_endian = avio_rb16(pb) & 0xFF; av_log(c->fc, AV_LOG_TRACE, "enda %d\n", little_endian); if (little_endian == 1) { switch (st->codecpar->codec_id) { case AV_CODEC_ID_PCM_S24BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; break; case AV_CODEC_ID_PCM_S32BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; break; case AV_CODEC_ID_PCM_F32BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_F32LE; break; case AV_CODEC_ID_PCM_F64BE: st->codecpar->codec_id = AV_CODEC_ID_PCM_F64LE; break; default: break; } } return 0; } static int mov_read_colr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; char color_parameter_type[5] = { 0 }; uint16_t color_primaries, color_trc, color_matrix; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; ret = ffio_read_size(pb, color_parameter_type, 4); if (ret < 0) return ret; if (strncmp(color_parameter_type, "nclx", 4) && strncmp(color_parameter_type, "nclc", 4)) { av_log(c->fc, AV_LOG_WARNING, "unsupported color_parameter_type %s\n", color_parameter_type); return 0; } color_primaries = avio_rb16(pb); color_trc = avio_rb16(pb); color_matrix = avio_rb16(pb); av_log(c->fc, AV_LOG_TRACE, "%s: pri %d trc %d matrix %d", color_parameter_type, color_primaries, color_trc, color_matrix); if (!strncmp(color_parameter_type, "nclx", 4)) { uint8_t color_range = avio_r8(pb) >> 7; av_log(c->fc, AV_LOG_TRACE, " full %"PRIu8"", color_range); if (color_range) st->codecpar->color_range = AVCOL_RANGE_JPEG; else st->codecpar->color_range = AVCOL_RANGE_MPEG; } if (!av_color_primaries_name(color_primaries)) color_primaries = AVCOL_PRI_UNSPECIFIED; if (!av_color_transfer_name(color_trc)) color_trc = AVCOL_TRC_UNSPECIFIED; if (!av_color_space_name(color_matrix)) color_matrix = AVCOL_SPC_UNSPECIFIED; st->codecpar->color_primaries = color_primaries; st->codecpar->color_trc = color_trc; st->codecpar->color_space = color_matrix; av_log(c->fc, AV_LOG_TRACE, "\n"); return 0; } static int mov_read_fiel(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; unsigned mov_field_order; enum AVFieldOrder decoded_field_order = AV_FIELD_UNKNOWN; if (c->fc->nb_streams < 1) // will happen with jp2 files return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size < 2) return AVERROR_INVALIDDATA; mov_field_order = avio_rb16(pb); if ((mov_field_order & 0xFF00) == 0x0100) decoded_field_order = AV_FIELD_PROGRESSIVE; else if ((mov_field_order & 0xFF00) == 0x0200) { switch (mov_field_order & 0xFF) { case 0x01: decoded_field_order = AV_FIELD_TT; break; case 0x06: decoded_field_order = AV_FIELD_BB; break; case 0x09: decoded_field_order = AV_FIELD_TB; break; case 0x0E: decoded_field_order = AV_FIELD_BT; break; } } if (decoded_field_order == AV_FIELD_UNKNOWN && mov_field_order) { av_log(NULL, AV_LOG_ERROR, "Unknown MOV field order 0x%04x\n", mov_field_order); } st->codecpar->field_order = decoded_field_order; return 0; } static int mov_realloc_extradata(AVCodecParameters *par, MOVAtom atom) { int err = 0; uint64_t size = (uint64_t)par->extradata_size + atom.size + 8 + AV_INPUT_BUFFER_PADDING_SIZE; if (size > INT_MAX || (uint64_t)atom.size > INT_MAX) return AVERROR_INVALIDDATA; if ((err = av_reallocp(&par->extradata, size)) < 0) { par->extradata_size = 0; return err; } par->extradata_size = size - AV_INPUT_BUFFER_PADDING_SIZE; return 0; } /* Read a whole atom into the extradata return the size of the atom read, possibly truncated if != atom.size */ static int64_t mov_read_atom_into_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, AVCodecParameters *par, uint8_t *buf) { int64_t result = atom.size; int err; AV_WB32(buf , atom.size + 8); AV_WL32(buf + 4, atom.type); err = ffio_read_size(pb, buf + 8, atom.size); if (err < 0) { par->extradata_size -= atom.size; return err; } else if (err < atom.size) { av_log(c->fc, AV_LOG_WARNING, "truncated extradata\n"); par->extradata_size -= atom.size - err; result = err; } memset(buf + 8 + err, 0, AV_INPUT_BUFFER_PADDING_SIZE); return result; } /* FIXME modify QDM2/SVQ3/H.264 decoders to take full atom as extradata */ static int mov_read_extradata(MOVContext *c, AVIOContext *pb, MOVAtom atom, enum AVCodecID codec_id) { AVStream *st; uint64_t original_size; int err; if (c->fc->nb_streams < 1) // will happen with jp2 files return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (st->codecpar->codec_id != codec_id) return 0; /* unexpected codec_id - don't mess with extradata */ original_size = st->codecpar->extradata_size; err = mov_realloc_extradata(st->codecpar, atom); if (err) return err; err = mov_read_atom_into_extradata(c, pb, atom, st->codecpar, st->codecpar->extradata + original_size); if (err < 0) return err; return 0; // Note: this is the original behavior to ignore truncation. } /* wrapper functions for reading ALAC/AVS/MJPEG/MJPEG2000 extradata atoms only for those codecs */ static int mov_read_alac(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_ALAC); } static int mov_read_avss(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVS); } static int mov_read_jp2h(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_JPEG2000); } static int mov_read_dpxe(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_R10K); } static int mov_read_avid(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_AVUI); if(ret == 0) ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_DNXHD); return ret; } static int mov_read_targa_y216(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret = mov_read_extradata(c, pb, atom, AV_CODEC_ID_TARGA_Y216); if (!ret && c->fc->nb_streams >= 1) { AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar; if (par->extradata_size >= 40) { par->height = AV_RB16(&par->extradata[36]); par->width = AV_RB16(&par->extradata[38]); } } return ret; } static int mov_read_ares(MOVContext *c, AVIOContext *pb, MOVAtom atom) { if (c->fc->nb_streams >= 1) { AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar; if (par->codec_tag == MKTAG('A', 'V', 'i', 'n') && par->codec_id == AV_CODEC_ID_H264 && atom.size > 11) { int cid; avio_skip(pb, 10); cid = avio_rb16(pb); /* For AVID AVCI50, force width of 1440 to be able to select the correct SPS and PPS */ if (cid == 0xd4d || cid == 0xd4e) par->width = 1440; return 0; } else if ((par->codec_tag == MKTAG('A', 'V', 'd', '1') || par->codec_tag == MKTAG('A', 'V', 'd', 'n')) && atom.size >= 24) { int num, den; avio_skip(pb, 12); num = avio_rb32(pb); den = avio_rb32(pb); if (num <= 0 || den <= 0) return 0; switch (avio_rb32(pb)) { case 2: if (den >= INT_MAX / 2) return 0; den *= 2; case 1: c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.num = num; c->fc->streams[c->fc->nb_streams-1]->display_aspect_ratio.den = den; default: return 0; } } } return mov_read_avid(c, pb, atom); } static int mov_read_aclr(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret = 0; int length = 0; uint64_t original_size; if (c->fc->nb_streams >= 1) { AVCodecParameters *par = c->fc->streams[c->fc->nb_streams-1]->codecpar; if (par->codec_id == AV_CODEC_ID_H264) return 0; if (atom.size == 16) { original_size = par->extradata_size; ret = mov_realloc_extradata(par, atom); if (!ret) { length = mov_read_atom_into_extradata(c, pb, atom, par, par->extradata + original_size); if (length == atom.size) { const uint8_t range_value = par->extradata[original_size + 19]; switch (range_value) { case 1: par->color_range = AVCOL_RANGE_MPEG; break; case 2: par->color_range = AVCOL_RANGE_JPEG; break; default: av_log(c, AV_LOG_WARNING, "ignored unknown aclr value (%d)\n", range_value); break; } ff_dlog(c, "color_range: %d\n", par->color_range); } else { /* For some reason the whole atom was not added to the extradata */ av_log(c, AV_LOG_ERROR, "aclr not decoded - incomplete atom\n"); } } else { av_log(c, AV_LOG_ERROR, "aclr not decoded - unable to add atom to extradata\n"); } } else { av_log(c, AV_LOG_WARNING, "aclr not decoded - unexpected size %"PRId64"\n", atom.size); } } return ret; } static int mov_read_svq3(MOVContext *c, AVIOContext *pb, MOVAtom atom) { return mov_read_extradata(c, pb, atom, AV_CODEC_ID_SVQ3); } static int mov_read_wave(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; if (st->codecpar->codec_id == AV_CODEC_ID_QDM2 || st->codecpar->codec_id == AV_CODEC_ID_QDMC || st->codecpar->codec_id == AV_CODEC_ID_SPEEX) { // pass all frma atom to codec, needed at least for QDMC and QDM2 av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size); if (ret < 0) return ret; } else if (atom.size > 8) { /* to read frma, esds atoms */ if (st->codecpar->codec_id == AV_CODEC_ID_ALAC && atom.size >= 24) { uint64_t buffer; ret = ffio_ensure_seekback(pb, 8); if (ret < 0) return ret; buffer = avio_rb64(pb); atom.size -= 8; if ( (buffer & 0xFFFFFFFF) == MKBETAG('f','r','m','a') && buffer >> 32 <= atom.size && buffer >> 32 >= 8) { avio_skip(pb, -8); atom.size += 8; } else if (!st->codecpar->extradata_size) { #define ALAC_EXTRADATA_SIZE 36 st->codecpar->extradata = av_mallocz(ALAC_EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); st->codecpar->extradata_size = ALAC_EXTRADATA_SIZE; AV_WB32(st->codecpar->extradata , ALAC_EXTRADATA_SIZE); AV_WB32(st->codecpar->extradata + 4, MKTAG('a','l','a','c')); AV_WB64(st->codecpar->extradata + 12, buffer); avio_read(pb, st->codecpar->extradata + 20, 16); avio_skip(pb, atom.size - 24); return 0; } } if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; } else avio_skip(pb, atom.size); return 0; } /** * This function reads atom content and puts data in extradata without tag * nor size unlike mov_read_extradata. */ static int mov_read_glbl(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; if (atom.size >= 10) { // Broken files created by legacy versions of libavformat will // wrap a whole fiel atom inside of a glbl atom. unsigned size = avio_rb32(pb); unsigned type = avio_rl32(pb); avio_seek(pb, -8, SEEK_CUR); if (type == MKTAG('f','i','e','l') && size == atom.size) return mov_read_default(c, pb, atom); } if (st->codecpar->extradata_size > 1 && st->codecpar->extradata) { av_log(c, AV_LOG_WARNING, "ignoring multiple glbl\n"); return 0; } av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size); if (ret < 0) return ret; return 0; } static int mov_read_dvc1(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; uint8_t profile_level; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if (atom.size >= (1<<28) || atom.size < 7) return AVERROR_INVALIDDATA; profile_level = avio_r8(pb); if ((profile_level & 0xf0) != 0xc0) return 0; avio_seek(pb, 6, SEEK_CUR); av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 7); if (ret < 0) return ret; return 0; } /** * An strf atom is a BITMAPINFOHEADER struct. This struct is 40 bytes itself, * but can have extradata appended at the end after the 40 bytes belonging * to the struct. */ static int mov_read_strf(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int ret; if (c->fc->nb_streams < 1) return 0; if (atom.size <= 40) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30)) return AVERROR_INVALIDDATA; avio_skip(pb, 40); av_freep(&st->codecpar->extradata); ret = ff_get_extradata(c->fc, st->codecpar, pb, atom.size - 40); if (ret < 0) return ret; return 0; } static int mov_read_stco(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); if (!entries) return 0; if (sc->chunk_offsets) av_log(c->fc, AV_LOG_WARNING, "Duplicated STCO atom\n"); av_free(sc->chunk_offsets); sc->chunk_count = 0; sc->chunk_offsets = av_malloc_array(entries, sizeof(*sc->chunk_offsets)); if (!sc->chunk_offsets) return AVERROR(ENOMEM); sc->chunk_count = entries; if (atom.type == MKTAG('s','t','c','o')) for (i = 0; i < entries && !pb->eof_reached; i++) sc->chunk_offsets[i] = avio_rb32(pb); else if (atom.type == MKTAG('c','o','6','4')) for (i = 0; i < entries && !pb->eof_reached; i++) sc->chunk_offsets[i] = avio_rb64(pb); else return AVERROR_INVALIDDATA; sc->chunk_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } /** * Compute codec id for 'lpcm' tag. * See CoreAudioTypes and AudioStreamBasicDescription at Apple. */ enum AVCodecID ff_mov_get_lpcm_codec_id(int bps, int flags) { /* lpcm flags: * 0x1 = float * 0x2 = big-endian * 0x4 = signed */ return ff_get_pcm_codec_id(bps, flags & 1, flags & 2, flags & 4 ? -1 : 0); } static int mov_codec_id(AVStream *st, uint32_t format) { int id = ff_codec_get_id(ff_codec_movaudio_tags, format); if (id <= 0 && ((format & 0xFFFF) == 'm' + ('s' << 8) || (format & 0xFFFF) == 'T' + ('S' << 8))) id = ff_codec_get_id(ff_codec_wav_tags, av_bswap32(format) & 0xFFFF); if (st->codecpar->codec_type != AVMEDIA_TYPE_VIDEO && id > 0) { st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; } else if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO && /* skip old ASF MPEG-4 tag */ format && format != MKTAG('m','p','4','s')) { id = ff_codec_get_id(ff_codec_movvideo_tags, format); if (id <= 0) id = ff_codec_get_id(ff_codec_bmp_tags, format); if (id > 0) st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA || (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE && st->codecpar->codec_id == AV_CODEC_ID_NONE)) { id = ff_codec_get_id(ff_codec_movsubtitle_tags, format); if (id > 0) st->codecpar->codec_type = AVMEDIA_TYPE_SUBTITLE; } } st->codecpar->codec_tag = format; return id; } static void mov_parse_stsd_video(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc) { uint8_t codec_name[32] = { 0 }; int64_t stsd_start; unsigned int len; /* The first 16 bytes of the video sample description are already * read in ff_mov_read_stsd_entries() */ stsd_start = avio_tell(pb) - 16; avio_rb16(pb); /* version */ avio_rb16(pb); /* revision level */ avio_rb32(pb); /* vendor */ avio_rb32(pb); /* temporal quality */ avio_rb32(pb); /* spatial quality */ st->codecpar->width = avio_rb16(pb); /* width */ st->codecpar->height = avio_rb16(pb); /* height */ avio_rb32(pb); /* horiz resolution */ avio_rb32(pb); /* vert resolution */ avio_rb32(pb); /* data size, always 0 */ avio_rb16(pb); /* frames per samples */ len = avio_r8(pb); /* codec name, pascal string */ if (len > 31) len = 31; mov_read_mac_string(c, pb, len, codec_name, sizeof(codec_name)); if (len < 31) avio_skip(pb, 31 - len); if (codec_name[0]) av_dict_set(&st->metadata, "encoder", codec_name, 0); /* codec_tag YV12 triggers an UV swap in rawdec.c */ if (!memcmp(codec_name, "Planar Y'CbCr 8-bit 4:2:0", 25)) { st->codecpar->codec_tag = MKTAG('I', '4', '2', '0'); st->codecpar->width &= ~1; st->codecpar->height &= ~1; } /* Flash Media Server uses tag H.263 with Sorenson Spark */ if (st->codecpar->codec_tag == MKTAG('H','2','6','3') && !memcmp(codec_name, "Sorenson H263", 13)) st->codecpar->codec_id = AV_CODEC_ID_FLV1; st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* depth */ avio_seek(pb, stsd_start, SEEK_SET); if (ff_get_qtpalette(st->codecpar->codec_id, pb, sc->palette)) { st->codecpar->bits_per_coded_sample &= 0x1F; sc->has_palette = 1; } } static void mov_parse_stsd_audio(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc) { int bits_per_sample, flags; uint16_t version = avio_rb16(pb); AVDictionaryEntry *compatible_brands = av_dict_get(c->fc->metadata, "compatible_brands", NULL, AV_DICT_MATCH_CASE); avio_rb16(pb); /* revision level */ avio_rb32(pb); /* vendor */ st->codecpar->channels = avio_rb16(pb); /* channel count */ st->codecpar->bits_per_coded_sample = avio_rb16(pb); /* sample size */ av_log(c->fc, AV_LOG_TRACE, "audio channels %d\n", st->codecpar->channels); sc->audio_cid = avio_rb16(pb); avio_rb16(pb); /* packet size = 0 */ st->codecpar->sample_rate = ((avio_rb32(pb) >> 16)); // Read QT version 1 fields. In version 0 these do not exist. av_log(c->fc, AV_LOG_TRACE, "version =%d, isom =%d\n", version, c->isom); if (!c->isom || (compatible_brands && strstr(compatible_brands->value, "qt "))) { if (version == 1) { sc->samples_per_frame = avio_rb32(pb); avio_rb32(pb); /* bytes per packet */ sc->bytes_per_frame = avio_rb32(pb); avio_rb32(pb); /* bytes per sample */ } else if (version == 2) { avio_rb32(pb); /* sizeof struct only */ st->codecpar->sample_rate = av_int2double(avio_rb64(pb)); st->codecpar->channels = avio_rb32(pb); avio_rb32(pb); /* always 0x7F000000 */ st->codecpar->bits_per_coded_sample = avio_rb32(pb); flags = avio_rb32(pb); /* lpcm format specific flag */ sc->bytes_per_frame = avio_rb32(pb); sc->samples_per_frame = avio_rb32(pb); if (st->codecpar->codec_tag == MKTAG('l','p','c','m')) st->codecpar->codec_id = ff_mov_get_lpcm_codec_id(st->codecpar->bits_per_coded_sample, flags); } if (version == 0 || (version == 1 && sc->audio_cid != -2)) { /* can't correctly handle variable sized packet as audio unit */ switch (st->codecpar->codec_id) { case AV_CODEC_ID_MP2: case AV_CODEC_ID_MP3: st->need_parsing = AVSTREAM_PARSE_FULL; break; } } } if (sc->format == 0) { if (st->codecpar->bits_per_coded_sample == 8) st->codecpar->codec_id = mov_codec_id(st, MKTAG('r','a','w',' ')); else if (st->codecpar->bits_per_coded_sample == 16) st->codecpar->codec_id = mov_codec_id(st, MKTAG('t','w','o','s')); } switch (st->codecpar->codec_id) { case AV_CODEC_ID_PCM_S8: case AV_CODEC_ID_PCM_U8: if (st->codecpar->bits_per_coded_sample == 16) st->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; break; case AV_CODEC_ID_PCM_S16LE: case AV_CODEC_ID_PCM_S16BE: if (st->codecpar->bits_per_coded_sample == 8) st->codecpar->codec_id = AV_CODEC_ID_PCM_S8; else if (st->codecpar->bits_per_coded_sample == 24) st->codecpar->codec_id = st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ? AV_CODEC_ID_PCM_S24BE : AV_CODEC_ID_PCM_S24LE; else if (st->codecpar->bits_per_coded_sample == 32) st->codecpar->codec_id = st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE ? AV_CODEC_ID_PCM_S32BE : AV_CODEC_ID_PCM_S32LE; break; /* set values for old format before stsd version 1 appeared */ case AV_CODEC_ID_MACE3: sc->samples_per_frame = 6; sc->bytes_per_frame = 2 * st->codecpar->channels; break; case AV_CODEC_ID_MACE6: sc->samples_per_frame = 6; sc->bytes_per_frame = 1 * st->codecpar->channels; break; case AV_CODEC_ID_ADPCM_IMA_QT: sc->samples_per_frame = 64; sc->bytes_per_frame = 34 * st->codecpar->channels; break; case AV_CODEC_ID_GSM: sc->samples_per_frame = 160; sc->bytes_per_frame = 33; break; default: break; } bits_per_sample = av_get_bits_per_sample(st->codecpar->codec_id); if (bits_per_sample) { st->codecpar->bits_per_coded_sample = bits_per_sample; sc->sample_size = (bits_per_sample >> 3) * st->codecpar->channels; } } static void mov_parse_stsd_subtitle(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size) { // ttxt stsd contains display flags, justification, background // color, fonts, and default styles, so fake an atom to read it MOVAtom fake_atom = { .size = size }; // mp4s contains a regular esds atom if (st->codecpar->codec_tag != AV_RL32("mp4s")) mov_read_glbl(c, pb, fake_atom); st->codecpar->width = sc->width; st->codecpar->height = sc->height; } static uint32_t yuv_to_rgba(uint32_t ycbcr) { uint8_t r, g, b; int y, cb, cr; y = (ycbcr >> 16) & 0xFF; cr = (ycbcr >> 8) & 0xFF; cb = ycbcr & 0xFF; b = av_clip_uint8((1164 * (y - 16) + 2018 * (cb - 128)) / 1000); g = av_clip_uint8((1164 * (y - 16) - 813 * (cr - 128) - 391 * (cb - 128)) / 1000); r = av_clip_uint8((1164 * (y - 16) + 1596 * (cr - 128) ) / 1000); return (r << 16) | (g << 8) | b; } static int mov_rewrite_dvd_sub_extradata(AVStream *st) { char buf[256] = {0}; uint8_t *src = st->codecpar->extradata; int i; if (st->codecpar->extradata_size != 64) return 0; if (st->codecpar->width > 0 && st->codecpar->height > 0) snprintf(buf, sizeof(buf), "size: %dx%d\n", st->codecpar->width, st->codecpar->height); av_strlcat(buf, "palette: ", sizeof(buf)); for (i = 0; i < 16; i++) { uint32_t yuv = AV_RB32(src + i * 4); uint32_t rgba = yuv_to_rgba(yuv); av_strlcatf(buf, sizeof(buf), "%06"PRIx32"%s", rgba, i != 15 ? ", " : ""); } if (av_strlcat(buf, "\n", sizeof(buf)) >= sizeof(buf)) return 0; av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = 0; st->codecpar->extradata = av_mallocz(strlen(buf) + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); st->codecpar->extradata_size = strlen(buf); memcpy(st->codecpar->extradata, buf, st->codecpar->extradata_size); return 0; } static int mov_parse_stsd_data(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc, int64_t size) { int ret; if (st->codecpar->codec_tag == MKTAG('t','m','c','d')) { if ((int)size != size) return AVERROR(ENOMEM); ret = ff_get_extradata(c->fc, st->codecpar, pb, size); if (ret < 0) return ret; if (size > 16) { MOVStreamContext *tmcd_ctx = st->priv_data; int val; val = AV_RB32(st->codecpar->extradata + 4); tmcd_ctx->tmcd_flags = val; st->avg_frame_rate.num = st->codecpar->extradata[16]; /* number of frame */ st->avg_frame_rate.den = 1; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->time_base = av_inv_q(st->avg_frame_rate); FF_ENABLE_DEPRECATION_WARNINGS #endif /* adjust for per frame dur in counter mode */ if (tmcd_ctx->tmcd_flags & 0x0008) { int timescale = AV_RB32(st->codecpar->extradata + 8); int framedur = AV_RB32(st->codecpar->extradata + 12); st->avg_frame_rate.num *= timescale; st->avg_frame_rate.den *= framedur; #if FF_API_LAVF_AVCTX FF_DISABLE_DEPRECATION_WARNINGS st->codec->time_base.den *= timescale; st->codec->time_base.num *= framedur; FF_ENABLE_DEPRECATION_WARNINGS #endif } if (size > 30) { uint32_t len = AV_RB32(st->codecpar->extradata + 18); /* name atom length */ uint32_t format = AV_RB32(st->codecpar->extradata + 22); if (format == AV_RB32("name") && (int64_t)size >= (int64_t)len + 18) { uint16_t str_size = AV_RB16(st->codecpar->extradata + 26); /* string length */ if (str_size > 0 && size >= (int)str_size + 26) { char *reel_name = av_malloc(str_size + 1); if (!reel_name) return AVERROR(ENOMEM); memcpy(reel_name, st->codecpar->extradata + 30, str_size); reel_name[str_size] = 0; /* Add null terminator */ /* don't add reel_name if emtpy string */ if (*reel_name == 0) { av_free(reel_name); } else { av_dict_set(&st->metadata, "reel_name", reel_name, AV_DICT_DONT_STRDUP_VAL); } } } } } } else { /* other codec type, just skip (rtp, mp4s ...) */ avio_skip(pb, size); } return 0; } static int mov_finalize_stsd_codec(MOVContext *c, AVIOContext *pb, AVStream *st, MOVStreamContext *sc) { if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && !st->codecpar->sample_rate && sc->time_scale > 1) st->codecpar->sample_rate = sc->time_scale; /* special codec parameters handling */ switch (st->codecpar->codec_id) { #if CONFIG_DV_DEMUXER case AV_CODEC_ID_DVAUDIO: c->dv_fctx = avformat_alloc_context(); if (!c->dv_fctx) { av_log(c->fc, AV_LOG_ERROR, "dv demux context alloc error\n"); return AVERROR(ENOMEM); } c->dv_demux = avpriv_dv_init_demux(c->dv_fctx); if (!c->dv_demux) { av_log(c->fc, AV_LOG_ERROR, "dv demux context init error\n"); return AVERROR(ENOMEM); } sc->dv_audio_container = 1; st->codecpar->codec_id = AV_CODEC_ID_PCM_S16LE; break; #endif /* no ifdef since parameters are always those */ case AV_CODEC_ID_QCELP: st->codecpar->channels = 1; // force sample rate for qcelp when not stored in mov if (st->codecpar->codec_tag != MKTAG('Q','c','l','p')) st->codecpar->sample_rate = 8000; // FIXME: Why is the following needed for some files? sc->samples_per_frame = 160; if (!sc->bytes_per_frame) sc->bytes_per_frame = 35; break; case AV_CODEC_ID_AMR_NB: st->codecpar->channels = 1; /* force sample rate for amr, stsd in 3gp does not store sample rate */ st->codecpar->sample_rate = 8000; break; case AV_CODEC_ID_AMR_WB: st->codecpar->channels = 1; st->codecpar->sample_rate = 16000; break; case AV_CODEC_ID_MP2: case AV_CODEC_ID_MP3: /* force type after stsd for m1a hdlr */ st->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; break; case AV_CODEC_ID_GSM: case AV_CODEC_ID_ADPCM_MS: case AV_CODEC_ID_ADPCM_IMA_WAV: case AV_CODEC_ID_ILBC: case AV_CODEC_ID_MACE3: case AV_CODEC_ID_MACE6: case AV_CODEC_ID_QDM2: st->codecpar->block_align = sc->bytes_per_frame; break; case AV_CODEC_ID_ALAC: if (st->codecpar->extradata_size == 36) { st->codecpar->channels = AV_RB8 (st->codecpar->extradata + 21); st->codecpar->sample_rate = AV_RB32(st->codecpar->extradata + 32); } break; case AV_CODEC_ID_AC3: case AV_CODEC_ID_EAC3: case AV_CODEC_ID_MPEG1VIDEO: case AV_CODEC_ID_VC1: case AV_CODEC_ID_VP9: st->need_parsing = AVSTREAM_PARSE_FULL; break; default: break; } return 0; } static int mov_skip_multiple_stsd(MOVContext *c, AVIOContext *pb, int codec_tag, int format, int64_t size) { int video_codec_id = ff_codec_get_id(ff_codec_movvideo_tags, format); if (codec_tag && (codec_tag != format && // AVID 1:1 samples with differing data format and codec tag exist (codec_tag != AV_RL32("AV1x") || format != AV_RL32("AVup")) && // prores is allowed to have differing data format and codec tag codec_tag != AV_RL32("apcn") && codec_tag != AV_RL32("apch") && // so is dv (sigh) codec_tag != AV_RL32("dvpp") && codec_tag != AV_RL32("dvcp") && (c->fc->video_codec_id ? video_codec_id != c->fc->video_codec_id : codec_tag != MKTAG('j','p','e','g')))) { /* Multiple fourcc, we skip JPEG. This is not correct, we should * export it as a separate AVStream but this needs a few changes * in the MOV demuxer, patch welcome. */ av_log(c->fc, AV_LOG_WARNING, "multiple fourcc not supported\n"); avio_skip(pb, size); return 1; } return 0; } int ff_mov_read_stsd_entries(MOVContext *c, AVIOContext *pb, int entries) { AVStream *st; MOVStreamContext *sc; int pseudo_stream_id; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; for (pseudo_stream_id = 0; pseudo_stream_id < entries && !pb->eof_reached; pseudo_stream_id++) { //Parsing Sample description table enum AVCodecID id; int ret, dref_id = 1; MOVAtom a = { AV_RL32("stsd") }; int64_t start_pos = avio_tell(pb); int64_t size = avio_rb32(pb); /* size */ uint32_t format = avio_rl32(pb); /* data format */ if (size >= 16) { avio_rb32(pb); /* reserved */ avio_rb16(pb); /* reserved */ dref_id = avio_rb16(pb); } else if (size <= 7) { av_log(c->fc, AV_LOG_ERROR, "invalid size %"PRId64" in stsd\n", size); return AVERROR_INVALIDDATA; } if (mov_skip_multiple_stsd(c, pb, st->codecpar->codec_tag, format, size - (avio_tell(pb) - start_pos))) continue; sc->pseudo_stream_id = st->codecpar->codec_tag ? -1 : pseudo_stream_id; sc->dref_id= dref_id; sc->format = format; id = mov_codec_id(st, format); av_log(c->fc, AV_LOG_TRACE, "size=%"PRId64" 4CC=%s codec_type=%d\n", size, av_fourcc2str(format), st->codecpar->codec_type); if (st->codecpar->codec_type==AVMEDIA_TYPE_VIDEO) { st->codecpar->codec_id = id; mov_parse_stsd_video(c, pb, st, sc); } else if (st->codecpar->codec_type==AVMEDIA_TYPE_AUDIO) { st->codecpar->codec_id = id; mov_parse_stsd_audio(c, pb, st, sc); if (st->codecpar->sample_rate < 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample rate %d\n", st->codecpar->sample_rate); return AVERROR_INVALIDDATA; } } else if (st->codecpar->codec_type==AVMEDIA_TYPE_SUBTITLE){ st->codecpar->codec_id = id; mov_parse_stsd_subtitle(c, pb, st, sc, size - (avio_tell(pb) - start_pos)); } else { ret = mov_parse_stsd_data(c, pb, st, sc, size - (avio_tell(pb) - start_pos)); if (ret < 0) return ret; } /* this will read extra atoms at the end (wave, alac, damr, avcC, hvcC, SMI ...) */ a.size = size - (avio_tell(pb) - start_pos); if (a.size > 8) { if ((ret = mov_read_default(c, pb, a)) < 0) return ret; } else if (a.size > 0) avio_skip(pb, a.size); if (sc->extradata && st->codecpar->extradata) { int extra_size = st->codecpar->extradata_size; /* Move the current stream extradata to the stream context one. */ sc->extradata_size[pseudo_stream_id] = extra_size; sc->extradata[pseudo_stream_id] = av_malloc(extra_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!sc->extradata[pseudo_stream_id]) return AVERROR(ENOMEM); memcpy(sc->extradata[pseudo_stream_id], st->codecpar->extradata, extra_size); av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = 0; } } if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stsd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int ret, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); if (entries <= 0) { av_log(c->fc, AV_LOG_ERROR, "invalid STSD entries %d\n", entries); return AVERROR_INVALIDDATA; } if (sc->extradata) { av_log(c->fc, AV_LOG_ERROR, "Duplicate STSD\n"); return AVERROR_INVALIDDATA; } /* Prepare space for hosting multiple extradata. */ sc->extradata = av_mallocz_array(entries, sizeof(*sc->extradata)); sc->extradata_size = av_mallocz_array(entries, sizeof(*sc->extradata_size)); if (!sc->extradata_size || !sc->extradata) { ret = AVERROR(ENOMEM); goto fail; } ret = ff_mov_read_stsd_entries(c, pb, entries); if (ret < 0) return ret; sc->stsd_count = entries; /* Restore back the primary extradata. */ av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = sc->extradata_size[0]; if (sc->extradata_size[0]) { st->codecpar->extradata = av_mallocz(sc->extradata_size[0] + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); memcpy(st->codecpar->extradata, sc->extradata[0], sc->extradata_size[0]); } return mov_finalize_stsd_codec(c, pb, st, sc); fail: av_freep(&sc->extradata); av_freep(&sc->extradata_size); return ret; } static int mov_read_stsc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "track[%u].stsc.entries = %u\n", c->fc->nb_streams - 1, entries); if (!entries) return 0; if (sc->stsc_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated STSC atom\n"); av_free(sc->stsc_data); sc->stsc_count = 0; sc->stsc_data = av_malloc_array(entries, sizeof(*sc->stsc_data)); if (!sc->stsc_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->stsc_data[i].first = avio_rb32(pb); sc->stsc_data[i].count = avio_rb32(pb); sc->stsc_data[i].id = avio_rb32(pb); } sc->stsc_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } #define mov_stsc_index_valid(index, count) ((index) < (count) - 1) /* Compute the samples value for the stsc entry at the given index. */ static inline int mov_get_stsc_samples(MOVStreamContext *sc, int index) { int chunk_count; if (mov_stsc_index_valid(index, sc->stsc_count)) chunk_count = sc->stsc_data[index + 1].first - sc->stsc_data[index].first; else chunk_count = sc->chunk_count - (sc->stsc_data[index].first - 1); return sc->stsc_data[index].count * chunk_count; } static int mov_read_stps(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_rb32(pb); // version + flags entries = avio_rb32(pb); if (sc->stps_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated STPS atom\n"); av_free(sc->stps_data); sc->stps_count = 0; sc->stps_data = av_malloc_array(entries, sizeof(*sc->stps_data)); if (!sc->stps_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->stps_data[i] = avio_rb32(pb); } sc->stps_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stss(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "keyframe_count = %u\n", entries); if (!entries) { sc->keyframe_absent = 1; if (!st->need_parsing && st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) st->need_parsing = AVSTREAM_PARSE_HEADERS; return 0; } if (sc->keyframes) av_log(c->fc, AV_LOG_WARNING, "Duplicated STSS atom\n"); if (entries >= UINT_MAX / sizeof(int)) return AVERROR_INVALIDDATA; av_freep(&sc->keyframes); sc->keyframe_count = 0; sc->keyframes = av_malloc_array(entries, sizeof(*sc->keyframes)); if (!sc->keyframes) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->keyframes[i] = avio_rb32(pb); } sc->keyframe_count = i; if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stsz(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries, sample_size, field_size, num_bytes; GetBitContext gb; unsigned char* buf; int ret; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ if (atom.type == MKTAG('s','t','s','z')) { sample_size = avio_rb32(pb); if (!sc->sample_size) /* do not overwrite value computed in stsd */ sc->sample_size = sample_size; sc->stsz_sample_size = sample_size; field_size = 32; } else { sample_size = 0; avio_rb24(pb); /* reserved */ field_size = avio_r8(pb); } entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "sample_size = %u sample_count = %u\n", sc->sample_size, entries); sc->sample_count = entries; if (sample_size) return 0; if (field_size != 4 && field_size != 8 && field_size != 16 && field_size != 32) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample field size %u\n", field_size); return AVERROR_INVALIDDATA; } if (!entries) return 0; if (entries >= (UINT_MAX - 4) / field_size) return AVERROR_INVALIDDATA; if (sc->sample_sizes) av_log(c->fc, AV_LOG_WARNING, "Duplicated STSZ atom\n"); av_free(sc->sample_sizes); sc->sample_count = 0; sc->sample_sizes = av_malloc_array(entries, sizeof(*sc->sample_sizes)); if (!sc->sample_sizes) return AVERROR(ENOMEM); num_bytes = (entries*field_size+4)>>3; buf = av_malloc(num_bytes+AV_INPUT_BUFFER_PADDING_SIZE); if (!buf) { av_freep(&sc->sample_sizes); return AVERROR(ENOMEM); } ret = ffio_read_size(pb, buf, num_bytes); if (ret < 0) { av_freep(&sc->sample_sizes); av_free(buf); return ret; } init_get_bits(&gb, buf, 8*num_bytes); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->sample_sizes[i] = get_bits_long(&gb, field_size); sc->data_size += sc->sample_sizes[i]; } sc->sample_count = i; av_free(buf); if (pb->eof_reached) return AVERROR_EOF; return 0; } static int mov_read_stts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; int64_t duration=0; int64_t total_sample_count=0; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "track[%u].stts.entries = %u\n", c->fc->nb_streams-1, entries); if (sc->stts_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated STTS atom\n"); av_free(sc->stts_data); sc->stts_count = 0; sc->stts_data = av_malloc_array(entries, sizeof(*sc->stts_data)); if (!sc->stts_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { int sample_duration; int sample_count; sample_count=avio_rb32(pb); sample_duration = avio_rb32(pb); if (sample_count < 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sample_count=%d\n", sample_count); return AVERROR_INVALIDDATA; } sc->stts_data[i].count= sample_count; sc->stts_data[i].duration= sample_duration; av_log(c->fc, AV_LOG_TRACE, "sample_count=%d, sample_duration=%d\n", sample_count, sample_duration); if ( i+1 == entries && i && sample_count == 1 && total_sample_count > 100 && sample_duration/10 > duration / total_sample_count) sample_duration = duration / total_sample_count; duration+=(int64_t)sample_duration*sample_count; total_sample_count+=sample_count; } sc->stts_count = i; sc->duration_for_fps += duration; sc->nb_frames_for_fps += total_sample_count; if (pb->eof_reached) return AVERROR_EOF; st->nb_frames= total_sample_count; if (duration) st->duration= duration; sc->track_end = duration; return 0; } static void mov_update_dts_shift(MOVStreamContext *sc, int duration) { if (duration < 0) { if (duration == INT_MIN) { av_log(NULL, AV_LOG_WARNING, "mov_update_dts_shift(): dts_shift set to %d\n", INT_MAX); duration++; } sc->dts_shift = FFMAX(sc->dts_shift, -duration); } } static int mov_read_ctts(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, j, entries, ctts_count = 0; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "track[%u].ctts.entries = %u\n", c->fc->nb_streams - 1, entries); if (!entries) return 0; if (entries >= UINT_MAX / sizeof(*sc->ctts_data)) return AVERROR_INVALIDDATA; av_freep(&sc->ctts_data); sc->ctts_data = av_fast_realloc(NULL, &sc->ctts_allocated_size, entries * sizeof(*sc->ctts_data)); if (!sc->ctts_data) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { int count =avio_rb32(pb); int duration =avio_rb32(pb); if (count <= 0) { av_log(c->fc, AV_LOG_TRACE, "ignoring CTTS entry with count=%d duration=%d\n", count, duration); continue; } /* Expand entries such that we have a 1-1 mapping with samples. */ for (j = 0; j < count; j++) add_ctts_entry(&sc->ctts_data, &ctts_count, &sc->ctts_allocated_size, 1, duration); av_log(c->fc, AV_LOG_TRACE, "count=%d, duration=%d\n", count, duration); if (FFNABS(duration) < -(1<<28) && i+2<entries) { av_log(c->fc, AV_LOG_WARNING, "CTTS invalid\n"); av_freep(&sc->ctts_data); sc->ctts_count = 0; return 0; } if (i+2<entries) mov_update_dts_shift(sc, duration); } sc->ctts_count = ctts_count; if (pb->eof_reached) return AVERROR_EOF; av_log(c->fc, AV_LOG_TRACE, "dts shift %d\n", sc->dts_shift); return 0; } static int mov_read_sbgp(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; unsigned int i, entries; uint8_t version; uint32_t grouping_type; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ grouping_type = avio_rl32(pb); if (grouping_type != MKTAG( 'r','a','p',' ')) return 0; /* only support 'rap ' grouping */ if (version == 1) avio_rb32(pb); /* grouping_type_parameter */ entries = avio_rb32(pb); if (!entries) return 0; if (sc->rap_group) av_log(c->fc, AV_LOG_WARNING, "Duplicated SBGP atom\n"); av_free(sc->rap_group); sc->rap_group_count = 0; sc->rap_group = av_malloc_array(entries, sizeof(*sc->rap_group)); if (!sc->rap_group) return AVERROR(ENOMEM); for (i = 0; i < entries && !pb->eof_reached; i++) { sc->rap_group[i].count = avio_rb32(pb); /* sample_count */ sc->rap_group[i].index = avio_rb32(pb); /* group_description_index */ } sc->rap_group_count = i; return pb->eof_reached ? AVERROR_EOF : 0; } /** * Get ith edit list entry (media time, duration). */ static int get_edit_list_entry(MOVContext *mov, const MOVStreamContext *msc, unsigned int edit_list_index, int64_t *edit_list_media_time, int64_t *edit_list_duration, int64_t global_timescale) { if (edit_list_index == msc->elst_count) { return 0; } *edit_list_media_time = msc->elst_data[edit_list_index].time; *edit_list_duration = msc->elst_data[edit_list_index].duration; /* duration is in global timescale units;convert to msc timescale */ if (global_timescale == 0) { avpriv_request_sample(mov->fc, "Support for mvhd.timescale = 0 with editlists"); return 0; } *edit_list_duration = av_rescale(*edit_list_duration, msc->time_scale, global_timescale); return 1; } /** * Find the closest previous frame to the timestamp, in e_old index * entries. Searching for just any frame / just key frames can be controlled by * last argument 'flag'. * Returns the index of the entry in st->index_entries if successful, * else returns -1. */ static int64_t find_prev_closest_index(AVStream *st, AVIndexEntry *e_old, int nb_old, int64_t timestamp, int flag) { AVIndexEntry *e_keep = st->index_entries; int nb_keep = st->nb_index_entries; int64_t found = -1; int64_t i = 0; st->index_entries = e_old; st->nb_index_entries = nb_old; found = av_index_search_timestamp(st, timestamp, flag | AVSEEK_FLAG_BACKWARD); // Keep going backwards in the index entries until the timestamp is the same. if (found >= 0) { for (i = found; i > 0 && e_old[i].timestamp == e_old[i - 1].timestamp; i--) { if ((flag & AVSEEK_FLAG_ANY) || (e_old[i - 1].flags & AVINDEX_KEYFRAME)) { found = i - 1; } } } /* restore AVStream state*/ st->index_entries = e_keep; st->nb_index_entries = nb_keep; return found; } /** * Add index entry with the given values, to the end of st->index_entries. * Returns the new size st->index_entries if successful, else returns -1. * * This function is similar to ff_add_index_entry in libavformat/utils.c * except that here we are always unconditionally adding an index entry to * the end, instead of searching the entries list and skipping the add if * there is an existing entry with the same timestamp. * This is needed because the mov_fix_index calls this func with the same * unincremented timestamp for successive discarded frames. */ static int64_t add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags) { AVIndexEntry *entries, *ie; int64_t index = -1; const size_t min_size_needed = (st->nb_index_entries + 1) * sizeof(AVIndexEntry); // Double the allocation each time, to lower memory fragmentation. // Another difference from ff_add_index_entry function. const size_t requested_size = min_size_needed > st->index_entries_allocated_size ? FFMAX(min_size_needed, 2 * st->index_entries_allocated_size) : min_size_needed; if((unsigned)st->nb_index_entries + 1 >= UINT_MAX / sizeof(AVIndexEntry)) return -1; entries = av_fast_realloc(st->index_entries, &st->index_entries_allocated_size, requested_size); if(!entries) return -1; st->index_entries= entries; index= st->nb_index_entries++; ie= &entries[index]; ie->pos = pos; ie->timestamp = timestamp; ie->min_distance= distance; ie->size= size; ie->flags = flags; return index; } /** * Rewrite timestamps of index entries in the range [end_index - frame_duration_buffer_size, end_index) * by subtracting end_ts successively by the amounts given in frame_duration_buffer. */ static void fix_index_entry_timestamps(AVStream* st, int end_index, int64_t end_ts, int64_t* frame_duration_buffer, int frame_duration_buffer_size) { int i = 0; av_assert0(end_index >= 0 && end_index <= st->nb_index_entries); for (i = 0; i < frame_duration_buffer_size; i++) { end_ts -= frame_duration_buffer[frame_duration_buffer_size - 1 - i]; st->index_entries[end_index - 1 - i].timestamp = end_ts; } } /** * Append a new ctts entry to ctts_data. * Returns the new ctts_count if successful, else returns -1. */ static int64_t add_ctts_entry(MOVStts** ctts_data, unsigned int* ctts_count, unsigned int* allocated_size, int count, int duration) { MOVStts *ctts_buf_new; const size_t min_size_needed = (*ctts_count + 1) * sizeof(MOVStts); const size_t requested_size = min_size_needed > *allocated_size ? FFMAX(min_size_needed, 2 * (*allocated_size)) : min_size_needed; if((unsigned)(*ctts_count) + 1 >= UINT_MAX / sizeof(MOVStts)) return -1; ctts_buf_new = av_fast_realloc(*ctts_data, allocated_size, requested_size); if(!ctts_buf_new) return -1; *ctts_data = ctts_buf_new; ctts_buf_new[*ctts_count].count = count; ctts_buf_new[*ctts_count].duration = duration; *ctts_count = (*ctts_count) + 1; return *ctts_count; } static void mov_current_sample_inc(MOVStreamContext *sc) { sc->current_sample++; sc->current_index++; if (sc->index_ranges && sc->current_index >= sc->current_index_range->end && sc->current_index_range->end) { sc->current_index_range++; sc->current_index = sc->current_index_range->start; } } static void mov_current_sample_dec(MOVStreamContext *sc) { sc->current_sample--; sc->current_index--; if (sc->index_ranges && sc->current_index < sc->current_index_range->start && sc->current_index_range > sc->index_ranges) { sc->current_index_range--; sc->current_index = sc->current_index_range->end - 1; } } static void mov_current_sample_set(MOVStreamContext *sc, int current_sample) { int64_t range_size; sc->current_sample = current_sample; sc->current_index = current_sample; if (!sc->index_ranges) { return; } for (sc->current_index_range = sc->index_ranges; sc->current_index_range->end; sc->current_index_range++) { range_size = sc->current_index_range->end - sc->current_index_range->start; if (range_size > current_sample) { sc->current_index = sc->current_index_range->start + current_sample; break; } current_sample -= range_size; } } /** * Fix st->index_entries, so that it contains only the entries (and the entries * which are needed to decode them) that fall in the edit list time ranges. * Also fixes the timestamps of the index entries to match the timeline * specified the edit lists. */ static void mov_fix_index(MOVContext *mov, AVStream *st) { MOVStreamContext *msc = st->priv_data; AVIndexEntry *e_old = st->index_entries; int nb_old = st->nb_index_entries; const AVIndexEntry *e_old_end = e_old + nb_old; const AVIndexEntry *current = NULL; MOVStts *ctts_data_old = msc->ctts_data; int64_t ctts_index_old = 0; int64_t ctts_sample_old = 0; int64_t ctts_count_old = msc->ctts_count; int64_t edit_list_media_time = 0; int64_t edit_list_duration = 0; int64_t frame_duration = 0; int64_t edit_list_dts_counter = 0; int64_t edit_list_dts_entry_end = 0; int64_t edit_list_start_ctts_sample = 0; int64_t curr_cts; int64_t curr_ctts = 0; int64_t min_corrected_pts = -1; int64_t empty_edits_sum_duration = 0; int64_t edit_list_index = 0; int64_t index; int64_t index_ctts_count; int flags; int64_t start_dts = 0; int64_t edit_list_media_time_dts = 0; int64_t edit_list_start_encountered = 0; int64_t search_timestamp = 0; int64_t* frame_duration_buffer = NULL; int num_discarded_begin = 0; int first_non_zero_audio_edit = -1; int packet_skip_samples = 0; MOVIndexRange *current_index_range; int i; if (!msc->elst_data || msc->elst_count <= 0 || nb_old <= 0) { return; } // allocate the index ranges array msc->index_ranges = av_malloc((msc->elst_count + 1) * sizeof(msc->index_ranges[0])); if (!msc->index_ranges) { av_log(mov->fc, AV_LOG_ERROR, "Cannot allocate index ranges buffer\n"); return; } msc->current_index_range = msc->index_ranges; current_index_range = msc->index_ranges - 1; // Clean AVStream from traces of old index st->index_entries = NULL; st->index_entries_allocated_size = 0; st->nb_index_entries = 0; // Clean ctts fields of MOVStreamContext msc->ctts_data = NULL; msc->ctts_count = 0; msc->ctts_index = 0; msc->ctts_sample = 0; msc->ctts_allocated_size = 0; // If the dts_shift is positive (in case of negative ctts values in mov), // then negate the DTS by dts_shift if (msc->dts_shift > 0) { edit_list_dts_entry_end -= msc->dts_shift; av_log(mov->fc, AV_LOG_DEBUG, "Shifting DTS by %d because of negative CTTS.\n", msc->dts_shift); } start_dts = edit_list_dts_entry_end; while (get_edit_list_entry(mov, msc, edit_list_index, &edit_list_media_time, &edit_list_duration, mov->time_scale)) { av_log(mov->fc, AV_LOG_DEBUG, "Processing st: %d, edit list %"PRId64" - media time: %"PRId64", duration: %"PRId64"\n", st->index, edit_list_index, edit_list_media_time, edit_list_duration); edit_list_index++; edit_list_dts_counter = edit_list_dts_entry_end; edit_list_dts_entry_end += edit_list_duration; num_discarded_begin = 0; if (edit_list_media_time == -1) { empty_edits_sum_duration += edit_list_duration; continue; } // If we encounter a non-negative edit list reset the skip_samples/start_pad fields and set them // according to the edit list below. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { if (first_non_zero_audio_edit < 0) { first_non_zero_audio_edit = 1; } else { first_non_zero_audio_edit = 0; } if (first_non_zero_audio_edit > 0) st->skip_samples = msc->start_pad = 0; } //find closest previous key frame edit_list_media_time_dts = edit_list_media_time; if (msc->dts_shift > 0) { edit_list_media_time_dts -= msc->dts_shift; } // While reordering frame index according to edit list we must handle properly // the scenario when edit list entry starts from none key frame. // We find closest previous key frame and preserve it and consequent frames in index. // All frames which are outside edit list entry time boundaries will be dropped after decoding. search_timestamp = edit_list_media_time_dts; if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { // Audio decoders like AAC need need a decoder delay samples previous to the current sample, // to correctly decode this frame. Hence for audio we seek to a frame 1 sec. before the // edit_list_media_time to cover the decoder delay. search_timestamp = FFMAX(search_timestamp - msc->time_scale, e_old[0].timestamp); } index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, 0); if (index == -1) { av_log(mov->fc, AV_LOG_WARNING, "st: %d edit list: %"PRId64" Missing key frame while searching for timestamp: %"PRId64"\n", st->index, edit_list_index, search_timestamp); index = find_prev_closest_index(st, e_old, nb_old, search_timestamp, AVSEEK_FLAG_ANY); if (index == -1) { av_log(mov->fc, AV_LOG_WARNING, "st: %d edit list %"PRId64" Cannot find an index entry before timestamp: %"PRId64".\n" "Rounding edit list media time to zero.\n", st->index, edit_list_index, search_timestamp); index = 0; edit_list_media_time = 0; } } current = e_old + index; ctts_index_old = 0; ctts_sample_old = 0; // set ctts_index properly for the found key frame for (index_ctts_count = 0; index_ctts_count < index; index_ctts_count++) { if (ctts_data_old && ctts_index_old < ctts_count_old) { ctts_sample_old++; if (ctts_data_old[ctts_index_old].count == ctts_sample_old) { ctts_index_old++; ctts_sample_old = 0; } } } edit_list_start_ctts_sample = ctts_sample_old; // Iterate over index and arrange it according to edit list edit_list_start_encountered = 0; for (; current < e_old_end; current++, index++) { // check if frame outside edit list mark it for discard frame_duration = (current + 1 < e_old_end) ? ((current + 1)->timestamp - current->timestamp) : edit_list_duration; flags = current->flags; // frames (pts) before or after edit list curr_cts = current->timestamp + msc->dts_shift; curr_ctts = 0; if (ctts_data_old && ctts_index_old < ctts_count_old) { curr_ctts = ctts_data_old[ctts_index_old].duration; av_log(mov->fc, AV_LOG_DEBUG, "stts: %"PRId64" ctts: %"PRId64", ctts_index: %"PRId64", ctts_count: %"PRId64"\n", curr_cts, curr_ctts, ctts_index_old, ctts_count_old); curr_cts += curr_ctts; ctts_sample_old++; if (ctts_sample_old == ctts_data_old[ctts_index_old].count) { if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count, &msc->ctts_allocated_size, ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration) == -1) { av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n", ctts_index_old, ctts_data_old[ctts_index_old].count - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration); break; } ctts_index_old++; ctts_sample_old = 0; edit_list_start_ctts_sample = 0; } } if (curr_cts < edit_list_media_time || curr_cts >= (edit_list_duration + edit_list_media_time)) { if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id != AV_CODEC_ID_VORBIS && curr_cts < edit_list_media_time && curr_cts + frame_duration > edit_list_media_time && first_non_zero_audio_edit > 0) { packet_skip_samples = edit_list_media_time - curr_cts; st->skip_samples += packet_skip_samples; // Shift the index entry timestamp by packet_skip_samples to be correct. edit_list_dts_counter -= packet_skip_samples; if (edit_list_start_encountered == 0) { edit_list_start_encountered = 1; // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for // discarded packets. if (frame_duration_buffer) { fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter, frame_duration_buffer, num_discarded_begin); av_freep(&frame_duration_buffer); } } av_log(mov->fc, AV_LOG_DEBUG, "skip %d audio samples from curr_cts: %"PRId64"\n", packet_skip_samples, curr_cts); } else { flags |= AVINDEX_DISCARD_FRAME; av_log(mov->fc, AV_LOG_DEBUG, "drop a frame at curr_cts: %"PRId64" @ %"PRId64"\n", curr_cts, index); if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && edit_list_start_encountered == 0) { num_discarded_begin++; frame_duration_buffer = av_realloc(frame_duration_buffer, num_discarded_begin * sizeof(int64_t)); if (!frame_duration_buffer) { av_log(mov->fc, AV_LOG_ERROR, "Cannot reallocate frame duration buffer\n"); break; } frame_duration_buffer[num_discarded_begin - 1] = frame_duration; // Increment skip_samples for the first non-zero audio edit list if (first_non_zero_audio_edit > 0 && st->codecpar->codec_id != AV_CODEC_ID_VORBIS) { st->skip_samples += frame_duration; msc->start_pad = st->skip_samples; } } } } else { if (min_corrected_pts < 0) { min_corrected_pts = edit_list_dts_counter + curr_ctts + msc->dts_shift; } else { min_corrected_pts = FFMIN(min_corrected_pts, edit_list_dts_counter + curr_ctts + msc->dts_shift); } if (edit_list_start_encountered == 0) { edit_list_start_encountered = 1; // Make timestamps strictly monotonically increasing for audio, by rewriting timestamps for // discarded packets. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && frame_duration_buffer) { fix_index_entry_timestamps(st, st->nb_index_entries, edit_list_dts_counter, frame_duration_buffer, num_discarded_begin); av_freep(&frame_duration_buffer); } } } if (add_index_entry(st, current->pos, edit_list_dts_counter, current->size, current->min_distance, flags) == -1) { av_log(mov->fc, AV_LOG_ERROR, "Cannot add index entry\n"); break; } // Update the index ranges array if (current_index_range < msc->index_ranges || index != current_index_range->end) { current_index_range++; current_index_range->start = index; } current_index_range->end = index + 1; // Only start incrementing DTS in frame_duration amounts, when we encounter a frame in edit list. if (edit_list_start_encountered > 0) { edit_list_dts_counter = edit_list_dts_counter + frame_duration; } // Break when found first key frame after edit entry completion if (((curr_cts + frame_duration) >= (edit_list_duration + edit_list_media_time)) && ((flags & AVINDEX_KEYFRAME) || ((st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO)))) { if (ctts_data_old && ctts_sample_old != 0) { if (add_ctts_entry(&msc->ctts_data, &msc->ctts_count, &msc->ctts_allocated_size, ctts_sample_old - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration) == -1) { av_log(mov->fc, AV_LOG_ERROR, "Cannot add CTTS entry %"PRId64" - {%"PRId64", %d}\n", ctts_index_old, ctts_sample_old - edit_list_start_ctts_sample, ctts_data_old[ctts_index_old].duration); break; } } break; } } } // If there are empty edits, then min_corrected_pts might be positive intentionally. So we subtract the // sum duration of emtpy edits here. min_corrected_pts -= empty_edits_sum_duration; // If the minimum pts turns out to be greater than zero after fixing the index, then we subtract the // dts by that amount to make the first pts zero. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && min_corrected_pts > 0) { av_log(mov->fc, AV_LOG_DEBUG, "Offset DTS by %"PRId64" to make first pts zero.\n", min_corrected_pts); for (i = 0; i < st->nb_index_entries; ++i) { st->index_entries[i].timestamp -= min_corrected_pts; } } // Update av stream length st->duration = edit_list_dts_entry_end - start_dts; // Free the old index and the old CTTS structures av_free(e_old); av_free(ctts_data_old); // Null terminate the index ranges array current_index_range++; current_index_range->start = 0; current_index_range->end = 0; msc->current_index = msc->index_ranges[0].start; } static void mov_build_index(MOVContext *mov, AVStream *st) { MOVStreamContext *sc = st->priv_data; int64_t current_offset; int64_t current_dts = 0; unsigned int stts_index = 0; unsigned int stsc_index = 0; unsigned int stss_index = 0; unsigned int stps_index = 0; unsigned int i, j; uint64_t stream_size = 0; if (sc->elst_count) { int i, edit_start_index = 0, multiple_edits = 0; int64_t empty_duration = 0; // empty duration of the first edit list entry int64_t start_time = 0; // start time of the media for (i = 0; i < sc->elst_count; i++) { const MOVElst *e = &sc->elst_data[i]; if (i == 0 && e->time == -1) { /* if empty, the first entry is the start time of the stream * relative to the presentation itself */ empty_duration = e->duration; edit_start_index = 1; } else if (i == edit_start_index && e->time >= 0) { start_time = e->time; } else { multiple_edits = 1; } } if (multiple_edits && !mov->advanced_editlist) av_log(mov->fc, AV_LOG_WARNING, "multiple edit list entries, " "Use -advanced_editlist to correctly decode otherwise " "a/v desync might occur\n"); /* adjust first dts according to edit list */ if ((empty_duration || start_time) && mov->time_scale > 0) { if (empty_duration) empty_duration = av_rescale(empty_duration, sc->time_scale, mov->time_scale); sc->time_offset = start_time - empty_duration; if (!mov->advanced_editlist) current_dts = -sc->time_offset; } if (!multiple_edits && !mov->advanced_editlist && st->codecpar->codec_id == AV_CODEC_ID_AAC && start_time > 0) sc->start_pad = start_time; } /* only use old uncompressed audio chunk demuxing when stts specifies it */ if (!(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && sc->stts_count == 1 && sc->stts_data[0].duration == 1)) { unsigned int current_sample = 0; unsigned int stts_sample = 0; unsigned int sample_size; unsigned int distance = 0; unsigned int rap_group_index = 0; unsigned int rap_group_sample = 0; int64_t last_dts = 0; int64_t dts_correction = 0; int rap_group_present = sc->rap_group_count && sc->rap_group; int key_off = (sc->keyframe_count && sc->keyframes[0] > 0) || (sc->stps_count && sc->stps_data[0] > 0); current_dts -= sc->dts_shift; last_dts = current_dts; if (!sc->sample_count || st->nb_index_entries) return; if (sc->sample_count >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries) return; if (av_reallocp_array(&st->index_entries, st->nb_index_entries + sc->sample_count, sizeof(*st->index_entries)) < 0) { st->nb_index_entries = 0; return; } st->index_entries_allocated_size = (st->nb_index_entries + sc->sample_count) * sizeof(*st->index_entries); for (i = 0; i < sc->chunk_count; i++) { int64_t next_offset = i+1 < sc->chunk_count ? sc->chunk_offsets[i+1] : INT64_MAX; current_offset = sc->chunk_offsets[i]; while (mov_stsc_index_valid(stsc_index, sc->stsc_count) && i + 1 == sc->stsc_data[stsc_index + 1].first) stsc_index++; if (next_offset > current_offset && sc->sample_size>0 && sc->sample_size < sc->stsz_sample_size && sc->stsc_data[stsc_index].count * (int64_t)sc->stsz_sample_size > next_offset - current_offset) { av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too large), ignoring\n", sc->stsz_sample_size); sc->stsz_sample_size = sc->sample_size; } if (sc->stsz_sample_size>0 && sc->stsz_sample_size < sc->sample_size) { av_log(mov->fc, AV_LOG_WARNING, "STSZ sample size %d invalid (too small), ignoring\n", sc->stsz_sample_size); sc->stsz_sample_size = sc->sample_size; } for (j = 0; j < sc->stsc_data[stsc_index].count; j++) { int keyframe = 0; if (current_sample >= sc->sample_count) { av_log(mov->fc, AV_LOG_ERROR, "wrong sample count\n"); return; } if (!sc->keyframe_absent && (!sc->keyframe_count || current_sample+key_off == sc->keyframes[stss_index])) { keyframe = 1; if (stss_index + 1 < sc->keyframe_count) stss_index++; } else if (sc->stps_count && current_sample+key_off == sc->stps_data[stps_index]) { keyframe = 1; if (stps_index + 1 < sc->stps_count) stps_index++; } if (rap_group_present && rap_group_index < sc->rap_group_count) { if (sc->rap_group[rap_group_index].index > 0) keyframe = 1; if (++rap_group_sample == sc->rap_group[rap_group_index].count) { rap_group_sample = 0; rap_group_index++; } } if (sc->keyframe_absent && !sc->stps_count && !rap_group_present && (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO || (i==0 && j==0))) keyframe = 1; if (keyframe) distance = 0; sample_size = sc->stsz_sample_size > 0 ? sc->stsz_sample_size : sc->sample_sizes[current_sample]; if (sc->pseudo_stream_id == -1 || sc->stsc_data[stsc_index].id - 1 == sc->pseudo_stream_id) { AVIndexEntry *e; if (sample_size > 0x3FFFFFFF) { av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", sample_size); return; } e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; e->size = sample_size; e->min_distance = distance; e->flags = keyframe ? AVINDEX_KEYFRAME : 0; av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %u, offset %"PRIx64", dts %"PRId64", " "size %u, distance %u, keyframe %d\n", st->index, current_sample, current_offset, current_dts, sample_size, distance, keyframe); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && st->nb_index_entries < 100) ff_rfps_add_frame(mov->fc, st, current_dts); } current_offset += sample_size; stream_size += sample_size; /* A negative sample duration is invalid based on the spec, * but some samples need it to correct the DTS. */ if (sc->stts_data[stts_index].duration < 0) { av_log(mov->fc, AV_LOG_WARNING, "Invalid SampleDelta %d in STTS, at %d st:%d\n", sc->stts_data[stts_index].duration, stts_index, st->index); dts_correction += sc->stts_data[stts_index].duration - 1; sc->stts_data[stts_index].duration = 1; } current_dts += sc->stts_data[stts_index].duration; if (!dts_correction || current_dts + dts_correction > last_dts) { current_dts += dts_correction; dts_correction = 0; } else { /* Avoid creating non-monotonous DTS */ dts_correction += current_dts - last_dts - 1; current_dts = last_dts + 1; } last_dts = current_dts; distance++; stts_sample++; current_sample++; if (stts_index + 1 < sc->stts_count && stts_sample == sc->stts_data[stts_index].count) { stts_sample = 0; stts_index++; } } } if (st->duration > 0) st->codecpar->bit_rate = stream_size*8*sc->time_scale/st->duration; } else { unsigned chunk_samples, total = 0; // compute total chunk count for (i = 0; i < sc->stsc_count; i++) { unsigned count, chunk_count; chunk_samples = sc->stsc_data[i].count; if (i != sc->stsc_count - 1 && sc->samples_per_frame && chunk_samples % sc->samples_per_frame) { av_log(mov->fc, AV_LOG_ERROR, "error unaligned chunk\n"); return; } if (sc->samples_per_frame >= 160) { // gsm count = chunk_samples / sc->samples_per_frame; } else if (sc->samples_per_frame > 1) { unsigned samples = (1024/sc->samples_per_frame)*sc->samples_per_frame; count = (chunk_samples+samples-1) / samples; } else { count = (chunk_samples+1023) / 1024; } if (mov_stsc_index_valid(i, sc->stsc_count)) chunk_count = sc->stsc_data[i+1].first - sc->stsc_data[i].first; else chunk_count = sc->chunk_count - (sc->stsc_data[i].first - 1); total += chunk_count * count; } av_log(mov->fc, AV_LOG_TRACE, "chunk count %u\n", total); if (total >= UINT_MAX / sizeof(*st->index_entries) - st->nb_index_entries) return; if (av_reallocp_array(&st->index_entries, st->nb_index_entries + total, sizeof(*st->index_entries)) < 0) { st->nb_index_entries = 0; return; } st->index_entries_allocated_size = (st->nb_index_entries + total) * sizeof(*st->index_entries); // populate index for (i = 0; i < sc->chunk_count; i++) { current_offset = sc->chunk_offsets[i]; if (mov_stsc_index_valid(stsc_index, sc->stsc_count) && i + 1 == sc->stsc_data[stsc_index + 1].first) stsc_index++; chunk_samples = sc->stsc_data[stsc_index].count; while (chunk_samples > 0) { AVIndexEntry *e; unsigned size, samples; if (sc->samples_per_frame > 1 && !sc->bytes_per_frame) { avpriv_request_sample(mov->fc, "Zero bytes per frame, but %d samples per frame", sc->samples_per_frame); return; } if (sc->samples_per_frame >= 160) { // gsm samples = sc->samples_per_frame; size = sc->bytes_per_frame; } else { if (sc->samples_per_frame > 1) { samples = FFMIN((1024 / sc->samples_per_frame)* sc->samples_per_frame, chunk_samples); size = (samples / sc->samples_per_frame) * sc->bytes_per_frame; } else { samples = FFMIN(1024, chunk_samples); size = samples * sc->sample_size; } } if (st->nb_index_entries >= total) { av_log(mov->fc, AV_LOG_ERROR, "wrong chunk count %u\n", total); return; } if (size > 0x3FFFFFFF) { av_log(mov->fc, AV_LOG_ERROR, "Sample size %u is too large\n", size); return; } e = &st->index_entries[st->nb_index_entries++]; e->pos = current_offset; e->timestamp = current_dts; e->size = size; e->min_distance = 0; e->flags = AVINDEX_KEYFRAME; av_log(mov->fc, AV_LOG_TRACE, "AVIndex stream %d, chunk %u, offset %"PRIx64", dts %"PRId64", " "size %u, duration %u\n", st->index, i, current_offset, current_dts, size, samples); current_offset += size; current_dts += samples; chunk_samples -= samples; } } } if (!mov->ignore_editlist && mov->advanced_editlist) { // Fix index according to edit lists. mov_fix_index(mov, st); } } static int test_same_origin(const char *src, const char *ref) { char src_proto[64]; char ref_proto[64]; char src_auth[256]; char ref_auth[256]; char src_host[256]; char ref_host[256]; int src_port=-1; int ref_port=-1; av_url_split(src_proto, sizeof(src_proto), src_auth, sizeof(src_auth), src_host, sizeof(src_host), &src_port, NULL, 0, src); av_url_split(ref_proto, sizeof(ref_proto), ref_auth, sizeof(ref_auth), ref_host, sizeof(ref_host), &ref_port, NULL, 0, ref); if (strlen(src) == 0) { return -1; } else if (strlen(src_auth) + 1 >= sizeof(src_auth) || strlen(ref_auth) + 1 >= sizeof(ref_auth) || strlen(src_host) + 1 >= sizeof(src_host) || strlen(ref_host) + 1 >= sizeof(ref_host)) { return 0; } else if (strcmp(src_proto, ref_proto) || strcmp(src_auth, ref_auth) || strcmp(src_host, ref_host) || src_port != ref_port) { return 0; } else return 1; } static int mov_open_dref(MOVContext *c, AVIOContext **pb, const char *src, MOVDref *ref) { /* try relative path, we do not try the absolute because it can leak information about our system to an attacker */ if (ref->nlvl_to > 0 && ref->nlvl_from > 0) { char filename[1025]; const char *src_path; int i, l; /* find a source dir */ src_path = strrchr(src, '/'); if (src_path) src_path++; else src_path = src; /* find a next level down to target */ for (i = 0, l = strlen(ref->path) - 1; l >= 0; l--) if (ref->path[l] == '/') { if (i == ref->nlvl_to - 1) break; else i++; } /* compose filename if next level down to target was found */ if (i == ref->nlvl_to - 1 && src_path - src < sizeof(filename)) { memcpy(filename, src, src_path - src); filename[src_path - src] = 0; for (i = 1; i < ref->nlvl_from; i++) av_strlcat(filename, "../", sizeof(filename)); av_strlcat(filename, ref->path + l + 1, sizeof(filename)); if (!c->use_absolute_path) { int same_origin = test_same_origin(src, filename); if (!same_origin) { av_log(c->fc, AV_LOG_ERROR, "Reference with mismatching origin, %s not tried for security reasons, " "set demuxer option use_absolute_path to allow it anyway\n", ref->path); return AVERROR(ENOENT); } if(strstr(ref->path + l + 1, "..") || strstr(ref->path + l + 1, ":") || (ref->nlvl_from > 1 && same_origin < 0) || (filename[0] == '/' && src_path == src)) return AVERROR(ENOENT); } if (strlen(filename) + 1 == sizeof(filename)) return AVERROR(ENOENT); if (!c->fc->io_open(c->fc, pb, filename, AVIO_FLAG_READ, NULL)) return 0; } } else if (c->use_absolute_path) { av_log(c->fc, AV_LOG_WARNING, "Using absolute path on user request, " "this is a possible security issue\n"); if (!c->fc->io_open(c->fc, pb, ref->path, AVIO_FLAG_READ, NULL)) return 0; } else { av_log(c->fc, AV_LOG_ERROR, "Absolute path %s not tried for security reasons, " "set demuxer option use_absolute_path to allow absolute paths\n", ref->path); } return AVERROR(ENOENT); } static void fix_timescale(MOVContext *c, MOVStreamContext *sc) { if (sc->time_scale <= 0) { av_log(c->fc, AV_LOG_WARNING, "stream %d, timescale not set\n", sc->ffindex); sc->time_scale = c->time_scale; if (sc->time_scale <= 0) sc->time_scale = 1; } } static int mov_read_trak(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int ret; st = avformat_new_stream(c->fc, NULL); if (!st) return AVERROR(ENOMEM); st->id = c->fc->nb_streams; sc = av_mallocz(sizeof(MOVStreamContext)); if (!sc) return AVERROR(ENOMEM); st->priv_data = sc; st->codecpar->codec_type = AVMEDIA_TYPE_DATA; sc->ffindex = st->index; c->trak_index = st->index; if ((ret = mov_read_default(c, pb, atom)) < 0) return ret; c->trak_index = -1; /* sanity checks */ if ((sc->chunk_count && (!sc->stts_count || !sc->stsc_count || (!sc->sample_size && !sc->sample_count))) || (!sc->chunk_count && sc->sample_count)) { av_log(c->fc, AV_LOG_ERROR, "stream %d, missing mandatory atoms, broken header\n", st->index); return 0; } fix_timescale(c, sc); avpriv_set_pts_info(st, 64, 1, sc->time_scale); mov_build_index(c, st); if (sc->dref_id-1 < sc->drefs_count && sc->drefs[sc->dref_id-1].path) { MOVDref *dref = &sc->drefs[sc->dref_id - 1]; if (c->enable_drefs) { if (mov_open_dref(c, &sc->pb, c->fc->filename, dref) < 0) av_log(c->fc, AV_LOG_ERROR, "stream %d, error opening alias: path='%s', dir='%s', " "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d\n", st->index, dref->path, dref->dir, dref->filename, dref->volume, dref->nlvl_from, dref->nlvl_to); } else { av_log(c->fc, AV_LOG_WARNING, "Skipped opening external track: " "stream %d, alias: path='%s', dir='%s', " "filename='%s', volume='%s', nlvl_from=%d, nlvl_to=%d." "Set enable_drefs to allow this.\n", st->index, dref->path, dref->dir, dref->filename, dref->volume, dref->nlvl_from, dref->nlvl_to); } } else { sc->pb = c->fc->pb; sc->pb_is_copied = 1; } if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { if (!st->sample_aspect_ratio.num && st->codecpar->width && st->codecpar->height && sc->height && sc->width && (st->codecpar->width != sc->width || st->codecpar->height != sc->height)) { st->sample_aspect_ratio = av_d2q(((double)st->codecpar->height * sc->width) / ((double)st->codecpar->width * sc->height), INT_MAX); } #if FF_API_R_FRAME_RATE if (sc->stts_count == 1 || (sc->stts_count == 2 && sc->stts_data[1].count == 1)) av_reduce(&st->r_frame_rate.num, &st->r_frame_rate.den, sc->time_scale, sc->stts_data[0].duration, INT_MAX); #endif } // done for ai5q, ai52, ai55, ai1q, ai12 and ai15. if (!st->codecpar->extradata_size && st->codecpar->codec_id == AV_CODEC_ID_H264 && TAG_IS_AVCI(st->codecpar->codec_tag)) { ret = ff_generate_avci_extradata(st); if (ret < 0) return ret; } switch (st->codecpar->codec_id) { #if CONFIG_H261_DECODER case AV_CODEC_ID_H261: #endif #if CONFIG_H263_DECODER case AV_CODEC_ID_H263: #endif #if CONFIG_MPEG4_DECODER case AV_CODEC_ID_MPEG4: #endif st->codecpar->width = 0; /* let decoder init width/height */ st->codecpar->height= 0; break; } // If the duration of the mp3 packets is not constant, then they could need a parser if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && sc->stts_count > 3 && sc->stts_count*10 > st->nb_frames && sc->time_scale == st->codecpar->sample_rate) { st->need_parsing = AVSTREAM_PARSE_FULL; } /* Do not need those anymore. */ av_freep(&sc->chunk_offsets); av_freep(&sc->sample_sizes); av_freep(&sc->keyframes); av_freep(&sc->stts_data); av_freep(&sc->stps_data); av_freep(&sc->elst_data); av_freep(&sc->rap_group); return 0; } static int mov_read_ilst(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; c->itunes_metadata = 1; ret = mov_read_default(c, pb, atom); c->itunes_metadata = 0; return ret; } static int mov_read_keys(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint32_t count; uint32_t i; if (atom.size < 8) return 0; avio_skip(pb, 4); count = avio_rb32(pb); if (count > UINT_MAX / sizeof(*c->meta_keys) - 1) { av_log(c->fc, AV_LOG_ERROR, "The 'keys' atom with the invalid key count: %"PRIu32"\n", count); return AVERROR_INVALIDDATA; } c->meta_keys_count = count + 1; c->meta_keys = av_mallocz(c->meta_keys_count * sizeof(*c->meta_keys)); if (!c->meta_keys) return AVERROR(ENOMEM); for (i = 1; i <= count; ++i) { uint32_t key_size = avio_rb32(pb); uint32_t type = avio_rl32(pb); if (key_size < 8) { av_log(c->fc, AV_LOG_ERROR, "The key# %"PRIu32" in meta has invalid size:" "%"PRIu32"\n", i, key_size); return AVERROR_INVALIDDATA; } key_size -= 8; if (type != MKTAG('m','d','t','a')) { avio_skip(pb, key_size); } c->meta_keys[i] = av_mallocz(key_size + 1); if (!c->meta_keys[i]) return AVERROR(ENOMEM); avio_read(pb, c->meta_keys[i], key_size); } return 0; } static int mov_read_custom(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t end = avio_tell(pb) + atom.size; uint8_t *key = NULL, *val = NULL, *mean = NULL; int i; int ret = 0; AVStream *st; MOVStreamContext *sc; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; for (i = 0; i < 3; i++) { uint8_t **p; uint32_t len, tag; if (end - avio_tell(pb) <= 12) break; len = avio_rb32(pb); tag = avio_rl32(pb); avio_skip(pb, 4); // flags if (len < 12 || len - 12 > end - avio_tell(pb)) break; len -= 12; if (tag == MKTAG('m', 'e', 'a', 'n')) p = &mean; else if (tag == MKTAG('n', 'a', 'm', 'e')) p = &key; else if (tag == MKTAG('d', 'a', 't', 'a') && len > 4) { avio_skip(pb, 4); len -= 4; p = &val; } else break; *p = av_malloc(len + 1); if (!*p) break; ret = ffio_read_size(pb, *p, len); if (ret < 0) { av_freep(p); break; } (*p)[len] = 0; } if (mean && key && val) { if (strcmp(key, "iTunSMPB") == 0) { int priming, remainder, samples; if(sscanf(val, "%*X %X %X %X", &priming, &remainder, &samples) == 3){ if(priming>0 && priming<16384) sc->start_pad = priming; } } if (strcmp(key, "cdec") != 0) { av_dict_set(&c->fc->metadata, key, val, AV_DICT_DONT_STRDUP_KEY | AV_DICT_DONT_STRDUP_VAL); key = val = NULL; } } else { av_log(c->fc, AV_LOG_VERBOSE, "Unhandled or malformed custom metadata of size %"PRId64"\n", atom.size); } avio_seek(pb, end, SEEK_SET); av_freep(&key); av_freep(&val); av_freep(&mean); return ret; } static int mov_read_meta(MOVContext *c, AVIOContext *pb, MOVAtom atom) { while (atom.size > 8) { uint32_t tag = avio_rl32(pb); atom.size -= 4; if (tag == MKTAG('h','d','l','r')) { avio_seek(pb, -8, SEEK_CUR); atom.size += 8; return mov_read_default(c, pb, atom); } } return 0; } // return 1 when matrix is identity, 0 otherwise #define IS_MATRIX_IDENT(matrix) \ ( (matrix)[0][0] == (1 << 16) && \ (matrix)[1][1] == (1 << 16) && \ (matrix)[2][2] == (1 << 30) && \ !(matrix)[0][1] && !(matrix)[0][2] && \ !(matrix)[1][0] && !(matrix)[1][2] && \ !(matrix)[2][0] && !(matrix)[2][1]) static int mov_read_tkhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int i, j, e; int width; int height; int display_matrix[3][3]; int res_display_matrix[3][3] = { { 0 } }; AVStream *st; MOVStreamContext *sc; int version; int flags; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; sc = st->priv_data; version = avio_r8(pb); flags = avio_rb24(pb); st->disposition |= (flags & MOV_TKHD_FLAG_ENABLED) ? AV_DISPOSITION_DEFAULT : 0; if (version == 1) { avio_rb64(pb); avio_rb64(pb); } else { avio_rb32(pb); /* creation time */ avio_rb32(pb); /* modification time */ } st->id = (int)avio_rb32(pb); /* track id (NOT 0 !)*/ avio_rb32(pb); /* reserved */ /* highlevel (considering edits) duration in movie timebase */ (version == 1) ? avio_rb64(pb) : avio_rb32(pb); avio_rb32(pb); /* reserved */ avio_rb32(pb); /* reserved */ avio_rb16(pb); /* layer */ avio_rb16(pb); /* alternate group */ avio_rb16(pb); /* volume */ avio_rb16(pb); /* reserved */ //read in the display matrix (outlined in ISO 14496-12, Section 6.2.2) // they're kept in fixed point format through all calculations // save u,v,z to store the whole matrix in the AV_PKT_DATA_DISPLAYMATRIX // side data, but the scale factor is not needed to calculate aspect ratio for (i = 0; i < 3; i++) { display_matrix[i][0] = avio_rb32(pb); // 16.16 fixed point display_matrix[i][1] = avio_rb32(pb); // 16.16 fixed point display_matrix[i][2] = avio_rb32(pb); // 2.30 fixed point } width = avio_rb32(pb); // 16.16 fixed point track width height = avio_rb32(pb); // 16.16 fixed point track height sc->width = width >> 16; sc->height = height >> 16; // apply the moov display matrix (after the tkhd one) for (i = 0; i < 3; i++) { const int sh[3] = { 16, 16, 30 }; for (j = 0; j < 3; j++) { for (e = 0; e < 3; e++) { res_display_matrix[i][j] += ((int64_t) display_matrix[i][e] * c->movie_display_matrix[e][j]) >> sh[e]; } } } // save the matrix when it is not the default identity if (!IS_MATRIX_IDENT(res_display_matrix)) { double rotate; av_freep(&sc->display_matrix); sc->display_matrix = av_malloc(sizeof(int32_t) * 9); if (!sc->display_matrix) return AVERROR(ENOMEM); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) sc->display_matrix[i * 3 + j] = res_display_matrix[i][j]; #if FF_API_OLD_ROTATE_API rotate = av_display_rotation_get(sc->display_matrix); if (!isnan(rotate)) { char rotate_buf[64]; rotate = -rotate; if (rotate < 0) // for backward compatibility rotate += 360; snprintf(rotate_buf, sizeof(rotate_buf), "%g", rotate); av_dict_set(&st->metadata, "rotate", rotate_buf, 0); } #endif } // transform the display width/height according to the matrix // to keep the same scale, use [width height 1<<16] if (width && height && sc->display_matrix) { double disp_transform[2]; for (i = 0; i < 2; i++) disp_transform[i] = hypot(sc->display_matrix[0 + i], sc->display_matrix[3 + i]); if (disp_transform[0] > 0 && disp_transform[1] > 0 && disp_transform[0] < (1<<24) && disp_transform[1] < (1<<24) && fabs((disp_transform[0] / disp_transform[1]) - 1.0) > 0.01) st->sample_aspect_ratio = av_d2q( disp_transform[0] / disp_transform[1], INT_MAX); } return 0; } static int mov_read_tfhd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; MOVTrackExt *trex = NULL; MOVFragmentIndex* index = NULL; int flags, track_id, i, found = 0; avio_r8(pb); /* version */ flags = avio_rb24(pb); track_id = avio_rb32(pb); if (!track_id) return AVERROR_INVALIDDATA; frag->track_id = track_id; for (i = 0; i < c->trex_count; i++) if (c->trex_data[i].track_id == frag->track_id) { trex = &c->trex_data[i]; break; } if (!trex) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding trex\n"); return AVERROR_INVALIDDATA; } frag->base_data_offset = flags & MOV_TFHD_BASE_DATA_OFFSET ? avio_rb64(pb) : flags & MOV_TFHD_DEFAULT_BASE_IS_MOOF ? frag->moof_offset : frag->implicit_offset; frag->stsd_id = flags & MOV_TFHD_STSD_ID ? avio_rb32(pb) : trex->stsd_id; frag->duration = flags & MOV_TFHD_DEFAULT_DURATION ? avio_rb32(pb) : trex->duration; frag->size = flags & MOV_TFHD_DEFAULT_SIZE ? avio_rb32(pb) : trex->size; frag->flags = flags & MOV_TFHD_DEFAULT_FLAGS ? avio_rb32(pb) : trex->flags; frag->time = AV_NOPTS_VALUE; for (i = 0; i < c->fragment_index_count; i++) { int j; MOVFragmentIndex* candidate = c->fragment_index_data[i]; if (candidate->track_id == frag->track_id) { av_log(c->fc, AV_LOG_DEBUG, "found fragment index for track %u\n", frag->track_id); index = candidate; for (j = index->current_item; j < index->item_count; j++) { if (frag->implicit_offset == index->items[j].moof_offset) { av_log(c->fc, AV_LOG_DEBUG, "found fragment index entry " "for track %u and moof_offset %"PRId64"\n", frag->track_id, index->items[j].moof_offset); frag->time = index->items[j].time; index->current_item = j + 1; found = 1; break; } } if (found) break; } } if (index && !found) { av_log(c->fc, AV_LOG_DEBUG, "track %u has a fragment index but " "it doesn't have an (in-order) entry for moof_offset " "%"PRId64"\n", frag->track_id, frag->implicit_offset); } av_log(c->fc, AV_LOG_TRACE, "frag flags 0x%x\n", frag->flags); return 0; } static int mov_read_chap(MOVContext *c, AVIOContext *pb, MOVAtom atom) { unsigned i, num; void *new_tracks; num = atom.size / 4; if (!(new_tracks = av_malloc_array(num, sizeof(int)))) return AVERROR(ENOMEM); av_free(c->chapter_tracks); c->chapter_tracks = new_tracks; c->nb_chapter_tracks = num; for (i = 0; i < num && !pb->eof_reached; i++) c->chapter_tracks[i] = avio_rb32(pb); return 0; } static int mov_read_trex(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVTrackExt *trex; int err; if ((uint64_t)c->trex_count+1 >= UINT_MAX / sizeof(*c->trex_data)) return AVERROR_INVALIDDATA; if ((err = av_reallocp_array(&c->trex_data, c->trex_count + 1, sizeof(*c->trex_data))) < 0) { c->trex_count = 0; return err; } c->fc->duration = AV_NOPTS_VALUE; // the duration from mvhd is not representing the whole file when fragments are used. trex = &c->trex_data[c->trex_count++]; avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ trex->track_id = avio_rb32(pb); trex->stsd_id = avio_rb32(pb); trex->duration = avio_rb32(pb); trex->size = avio_rb32(pb); trex->flags = avio_rb32(pb); return 0; } static int mov_read_tfdt(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; AVStream *st = NULL; MOVStreamContext *sc; int version, i; for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == frag->track_id) { st = c->fc->streams[i]; break; } } if (!st) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id); return AVERROR_INVALIDDATA; } sc = st->priv_data; if (sc->pseudo_stream_id + 1 != frag->stsd_id) return 0; version = avio_r8(pb); avio_rb24(pb); /* flags */ if (version) { sc->track_end = avio_rb64(pb); } else { sc->track_end = avio_rb32(pb); } return 0; } static int mov_read_trun(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVFragment *frag = &c->fragment; AVStream *st = NULL; MOVStreamContext *sc; MOVStts *ctts_data; uint64_t offset; int64_t dts; int data_offset = 0; unsigned entries, first_sample_flags = frag->flags; int flags, distance, i; for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == frag->track_id) { st = c->fc->streams[i]; break; } } if (!st) { av_log(c->fc, AV_LOG_ERROR, "could not find corresponding track id %u\n", frag->track_id); return AVERROR_INVALIDDATA; } sc = st->priv_data; if (sc->pseudo_stream_id+1 != frag->stsd_id && sc->pseudo_stream_id != -1) return 0; avio_r8(pb); /* version */ flags = avio_rb24(pb); entries = avio_rb32(pb); av_log(c->fc, AV_LOG_TRACE, "flags 0x%x entries %u\n", flags, entries); if ((uint64_t)entries+sc->ctts_count >= UINT_MAX/sizeof(*sc->ctts_data)) return AVERROR_INVALIDDATA; if (flags & MOV_TRUN_DATA_OFFSET) data_offset = avio_rb32(pb); if (flags & MOV_TRUN_FIRST_SAMPLE_FLAGS) first_sample_flags = avio_rb32(pb); dts = sc->track_end - sc->time_offset; offset = frag->base_data_offset + data_offset; distance = 0; av_log(c->fc, AV_LOG_TRACE, "first sample flags 0x%x\n", first_sample_flags); for (i = 0; i < entries && !pb->eof_reached; i++) { unsigned sample_size = frag->size; int sample_flags = i ? frag->flags : first_sample_flags; unsigned sample_duration = frag->duration; unsigned ctts_duration = 0; int keyframe = 0; int ctts_index = 0; int old_nb_index_entries = st->nb_index_entries; if (flags & MOV_TRUN_SAMPLE_DURATION) sample_duration = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_SIZE) sample_size = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_FLAGS) sample_flags = avio_rb32(pb); if (flags & MOV_TRUN_SAMPLE_CTS) ctts_duration = avio_rb32(pb); mov_update_dts_shift(sc, ctts_duration); if (frag->time != AV_NOPTS_VALUE) { if (c->use_mfra_for == FF_MOV_FLAG_MFRA_PTS) { int64_t pts = frag->time; av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64 " sc->dts_shift %d ctts.duration %d" " sc->time_offset %"PRId64" flags & MOV_TRUN_SAMPLE_CTS %d\n", pts, sc->dts_shift, ctts_duration, sc->time_offset, flags & MOV_TRUN_SAMPLE_CTS); dts = pts - sc->dts_shift; if (flags & MOV_TRUN_SAMPLE_CTS) { dts -= ctts_duration; } else { dts -= sc->time_offset; } av_log(c->fc, AV_LOG_DEBUG, "calculated into dts %"PRId64"\n", dts); } else { dts = frag->time - sc->time_offset; av_log(c->fc, AV_LOG_DEBUG, "found frag time %"PRId64 ", using it for dts\n", dts); } frag->time = AV_NOPTS_VALUE; } if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) keyframe = 1; else keyframe = !(sample_flags & (MOV_FRAG_SAMPLE_FLAG_IS_NON_SYNC | MOV_FRAG_SAMPLE_FLAG_DEPENDS_YES)); if (keyframe) distance = 0; ctts_index = av_add_index_entry(st, offset, dts, sample_size, distance, keyframe ? AVINDEX_KEYFRAME : 0); if (ctts_index >= 0 && old_nb_index_entries < st->nb_index_entries) { unsigned int size_needed = st->nb_index_entries * sizeof(*sc->ctts_data); unsigned int request_size = size_needed > sc->ctts_allocated_size ? FFMAX(size_needed, 2 * sc->ctts_allocated_size) : size_needed; unsigned int old_ctts_size = sc->ctts_allocated_size; ctts_data = av_fast_realloc(sc->ctts_data, &sc->ctts_allocated_size, request_size); if (!ctts_data) { av_freep(&sc->ctts_data); return AVERROR(ENOMEM); } sc->ctts_data = ctts_data; // In case there were samples without ctts entries, ensure they get // zero valued entries. This ensures clips which mix boxes with and // without ctts entries don't pickup uninitialized data. memset((uint8_t*)(sc->ctts_data) + old_ctts_size, 0, sc->ctts_allocated_size - old_ctts_size); if (ctts_index != old_nb_index_entries) { memmove(sc->ctts_data + ctts_index + 1, sc->ctts_data + ctts_index, sizeof(*sc->ctts_data) * (sc->ctts_count - ctts_index)); if (ctts_index <= sc->current_sample) { // if we inserted a new item before the current sample, move the // counter ahead so it is still pointing to the same sample. sc->current_sample++; } } sc->ctts_data[ctts_index].count = 1; sc->ctts_data[ctts_index].duration = ctts_duration; sc->ctts_count++; } else { av_log(c->fc, AV_LOG_ERROR, "Failed to add index entry\n"); } av_log(c->fc, AV_LOG_TRACE, "AVIndex stream %d, sample %d, offset %"PRIx64", dts %"PRId64", " "size %u, distance %d, keyframe %d\n", st->index, ctts_index, offset, dts, sample_size, distance, keyframe); distance++; dts += sample_duration; offset += sample_size; sc->data_size += sample_size; sc->duration_for_fps += sample_duration; sc->nb_frames_for_fps ++; } if (pb->eof_reached) return AVERROR_EOF; frag->implicit_offset = offset; sc->track_end = dts + sc->time_offset; if (st->duration < sc->track_end) st->duration = sc->track_end; return 0; } static int mov_read_sidx(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t offset = avio_tell(pb) + atom.size, pts; uint8_t version; unsigned i, track_id; AVStream *st = NULL; AVStream *ref_st = NULL; MOVStreamContext *sc, *ref_sc = NULL; MOVFragmentIndex *index = NULL; MOVFragmentIndex **tmp; AVRational timescale; version = avio_r8(pb); if (version > 1) { avpriv_request_sample(c->fc, "sidx version %u", version); return 0; } avio_rb24(pb); // flags track_id = avio_rb32(pb); // Reference ID for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == track_id) { st = c->fc->streams[i]; break; } } if (!st) { av_log(c->fc, AV_LOG_WARNING, "could not find corresponding track id %d\n", track_id); return 0; } sc = st->priv_data; timescale = av_make_q(1, avio_rb32(pb)); if (timescale.den <= 0) { av_log(c->fc, AV_LOG_ERROR, "Invalid sidx timescale 1/%d\n", timescale.den); return AVERROR_INVALIDDATA; } if (version == 0) { pts = avio_rb32(pb); offset += avio_rb32(pb); } else { pts = avio_rb64(pb); offset += avio_rb64(pb); } avio_rb16(pb); // reserved index = av_mallocz(sizeof(MOVFragmentIndex)); if (!index) return AVERROR(ENOMEM); index->track_id = track_id; index->item_count = avio_rb16(pb); index->items = av_mallocz_array(index->item_count, sizeof(MOVFragmentIndexItem)); if (!index->items) { av_freep(&index); return AVERROR(ENOMEM); } for (i = 0; i < index->item_count; i++) { uint32_t size = avio_rb32(pb); uint32_t duration = avio_rb32(pb); if (size & 0x80000000) { avpriv_request_sample(c->fc, "sidx reference_type 1"); av_freep(&index->items); av_freep(&index); return AVERROR_PATCHWELCOME; } avio_rb32(pb); // sap_flags index->items[i].moof_offset = offset; index->items[i].time = av_rescale_q(pts, st->time_base, timescale); offset += size; pts += duration; } st->duration = sc->track_end = pts; tmp = av_realloc_array(c->fragment_index_data, c->fragment_index_count + 1, sizeof(MOVFragmentIndex*)); if (!tmp) { av_freep(&index->items); av_freep(&index); return AVERROR(ENOMEM); } c->fragment_index_data = tmp; c->fragment_index_data[c->fragment_index_count++] = index; sc->has_sidx = 1; if (offset == avio_size(pb)) { for (i = 0; i < c->fc->nb_streams; i++) { if (c->fc->streams[i]->id == c->fragment_index_data[0]->track_id) { ref_st = c->fc->streams[i]; ref_sc = ref_st->priv_data; break; } } for (i = 0; i < c->fc->nb_streams; i++) { st = c->fc->streams[i]; sc = st->priv_data; if (!sc->has_sidx) { st->duration = sc->track_end = av_rescale(ref_st->duration, sc->time_scale, ref_sc->time_scale); } } c->fragment_index_complete = 1; } return 0; } /* this atom should be null (from specs), but some buggy files put the 'moov' atom inside it... */ /* like the files created with Adobe Premiere 5.0, for samples see */ /* http://graphics.tudelft.nl/~wouter/publications/soundtests/ */ static int mov_read_wide(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int err; if (atom.size < 8) return 0; /* continue */ if (avio_rb32(pb) != 0) { /* 0 sized mdat atom... use the 'wide' atom size */ avio_skip(pb, atom.size - 4); return 0; } atom.type = avio_rl32(pb); atom.size -= 8; if (atom.type != MKTAG('m','d','a','t')) { avio_skip(pb, atom.size); return 0; } err = mov_read_mdat(c, pb, atom); return err; } static int mov_read_cmov(MOVContext *c, AVIOContext *pb, MOVAtom atom) { #if CONFIG_ZLIB AVIOContext ctx; uint8_t *cmov_data; uint8_t *moov_data; /* uncompressed data */ long cmov_len, moov_len; int ret = -1; avio_rb32(pb); /* dcom atom */ if (avio_rl32(pb) != MKTAG('d','c','o','m')) return AVERROR_INVALIDDATA; if (avio_rl32(pb) != MKTAG('z','l','i','b')) { av_log(c->fc, AV_LOG_ERROR, "unknown compression for cmov atom !\n"); return AVERROR_INVALIDDATA; } avio_rb32(pb); /* cmvd atom */ if (avio_rl32(pb) != MKTAG('c','m','v','d')) return AVERROR_INVALIDDATA; moov_len = avio_rb32(pb); /* uncompressed size */ cmov_len = atom.size - 6 * 4; cmov_data = av_malloc(cmov_len); if (!cmov_data) return AVERROR(ENOMEM); moov_data = av_malloc(moov_len); if (!moov_data) { av_free(cmov_data); return AVERROR(ENOMEM); } ret = ffio_read_size(pb, cmov_data, cmov_len); if (ret < 0) goto free_and_return; if (uncompress (moov_data, (uLongf *) &moov_len, (const Bytef *)cmov_data, cmov_len) != Z_OK) goto free_and_return; if (ffio_init_context(&ctx, moov_data, moov_len, 0, NULL, NULL, NULL, NULL) != 0) goto free_and_return; ctx.seekable = AVIO_SEEKABLE_NORMAL; atom.type = MKTAG('m','o','o','v'); atom.size = moov_len; ret = mov_read_default(c, &ctx, atom); free_and_return: av_free(moov_data); av_free(cmov_data); return ret; #else av_log(c->fc, AV_LOG_ERROR, "this file requires zlib support compiled in\n"); return AVERROR(ENOSYS); #endif } /* edit list atom */ static int mov_read_elst(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; int i, edit_count, version; if (c->fc->nb_streams < 1 || c->ignore_editlist) return 0; sc = c->fc->streams[c->fc->nb_streams-1]->priv_data; version = avio_r8(pb); /* version */ avio_rb24(pb); /* flags */ edit_count = avio_rb32(pb); /* entries */ if (!edit_count) return 0; if (sc->elst_data) av_log(c->fc, AV_LOG_WARNING, "Duplicated ELST atom\n"); av_free(sc->elst_data); sc->elst_count = 0; sc->elst_data = av_malloc_array(edit_count, sizeof(*sc->elst_data)); if (!sc->elst_data) return AVERROR(ENOMEM); av_log(c->fc, AV_LOG_TRACE, "track[%u].edit_count = %i\n", c->fc->nb_streams - 1, edit_count); for (i = 0; i < edit_count && !pb->eof_reached; i++) { MOVElst *e = &sc->elst_data[i]; if (version == 1) { e->duration = avio_rb64(pb); e->time = avio_rb64(pb); } else { e->duration = avio_rb32(pb); /* segment duration */ e->time = (int32_t)avio_rb32(pb); /* media time */ } e->rate = avio_rb32(pb) / 65536.0; av_log(c->fc, AV_LOG_TRACE, "duration=%"PRId64" time=%"PRId64" rate=%f\n", e->duration, e->time, e->rate); if (e->time < 0 && e->time != -1 && c->fc->strict_std_compliance >= FF_COMPLIANCE_STRICT) { av_log(c->fc, AV_LOG_ERROR, "Track %d, edit %d: Invalid edit list media time=%"PRId64"\n", c->fc->nb_streams-1, i, e->time); return AVERROR_INVALIDDATA; } } sc->elst_count = i; return 0; } static int mov_read_tmcd(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; if (c->fc->nb_streams < 1) return AVERROR_INVALIDDATA; sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data; sc->timecode_track = avio_rb32(pb); return 0; } static int mov_read_vpcc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int version, color_range, color_primaries, color_trc, color_space; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty VP Codec Configuration box\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version != 1) { av_log(c->fc, AV_LOG_WARNING, "Unsupported VP Codec Configuration box version %d\n", version); return 0; } avio_skip(pb, 3); /* flags */ avio_skip(pb, 2); /* profile + level */ color_range = avio_r8(pb); /* bitDepth, chromaSubsampling, videoFullRangeFlag */ color_primaries = avio_r8(pb); color_trc = avio_r8(pb); color_space = avio_r8(pb); if (avio_rb16(pb)) /* codecIntializationDataSize */ return AVERROR_INVALIDDATA; if (!av_color_primaries_name(color_primaries)) color_primaries = AVCOL_PRI_UNSPECIFIED; if (!av_color_transfer_name(color_trc)) color_trc = AVCOL_TRC_UNSPECIFIED; if (!av_color_space_name(color_space)) color_space = AVCOL_SPC_UNSPECIFIED; st->codecpar->color_range = (color_range & 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; st->codecpar->color_primaries = color_primaries; st->codecpar->color_trc = color_trc; st->codecpar->color_space = color_space; return 0; } static int mov_read_smdm(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; const int chroma_den = 50000; const int luma_den = 10000; int i, j, version; if (c->fc->nb_streams < 1) return AVERROR_INVALIDDATA; sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty Mastering Display Metadata box\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version) { av_log(c->fc, AV_LOG_WARNING, "Unsupported Mastering Display Metadata box version %d\n", version); return 0; } avio_skip(pb, 3); /* flags */ sc->mastering = av_mastering_display_metadata_alloc(); if (!sc->mastering) return AVERROR(ENOMEM); for (i = 0; i < 3; i++) for (j = 0; j < 2; j++) sc->mastering->display_primaries[i][j] = av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den); for (i = 0; i < 2; i++) sc->mastering->white_point[i] = av_make_q(lrint(((double)avio_rb16(pb) / (1 << 16)) * chroma_den), chroma_den); sc->mastering->max_luminance = av_make_q(lrint(((double)avio_rb32(pb) / (1 << 8)) * luma_den), luma_den); sc->mastering->min_luminance = av_make_q(lrint(((double)avio_rb32(pb) / (1 << 14)) * luma_den), luma_den); sc->mastering->has_primaries = 1; sc->mastering->has_luminance = 1; return 0; } static int mov_read_coll(MOVContext *c, AVIOContext *pb, MOVAtom atom) { MOVStreamContext *sc; int version; if (c->fc->nb_streams < 1) return AVERROR_INVALIDDATA; sc = c->fc->streams[c->fc->nb_streams - 1]->priv_data; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty Content Light Level box\n"); return AVERROR_INVALIDDATA; } version = avio_r8(pb); if (version) { av_log(c->fc, AV_LOG_WARNING, "Unsupported Content Light Level box version %d\n", version); return 0; } avio_skip(pb, 3); /* flags */ sc->coll = av_content_light_metadata_alloc(&sc->coll_size); if (!sc->coll) return AVERROR(ENOMEM); sc->coll->MaxCLL = avio_rb16(pb); sc->coll->MaxFALL = avio_rb16(pb); return 0; } static int mov_read_st3d(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; enum AVStereo3DType type; int mode; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (atom.size < 5) { av_log(c->fc, AV_LOG_ERROR, "Empty stereoscopic video box\n"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); /* version + flags */ mode = avio_r8(pb); switch (mode) { case 0: type = AV_STEREO3D_2D; break; case 1: type = AV_STEREO3D_TOPBOTTOM; break; case 2: type = AV_STEREO3D_SIDEBYSIDE; break; default: av_log(c->fc, AV_LOG_WARNING, "Unknown st3d mode value %d\n", mode); return 0; } sc->stereo3d = av_stereo3d_alloc(); if (!sc->stereo3d) return AVERROR(ENOMEM); sc->stereo3d->type = type; return 0; } static int mov_read_sv3d(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int size, layout; int32_t yaw, pitch, roll; uint32_t l = 0, t = 0, r = 0, b = 0; uint32_t tag, padding = 0; enum AVSphericalProjection projection; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (atom.size < 8) { av_log(c->fc, AV_LOG_ERROR, "Empty spherical video box\n"); return AVERROR_INVALIDDATA; } size = avio_rb32(pb); if (size <= 12 || size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('s','v','h','d')) { av_log(c->fc, AV_LOG_ERROR, "Missing spherical video header\n"); return 0; } avio_skip(pb, 4); /* version + flags */ avio_skip(pb, size - 12); /* metadata_source */ size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('p','r','o','j')) { av_log(c->fc, AV_LOG_ERROR, "Missing projection box\n"); return 0; } size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); if (tag != MKTAG('p','r','h','d')) { av_log(c->fc, AV_LOG_ERROR, "Missing projection header box\n"); return 0; } avio_skip(pb, 4); /* version + flags */ /* 16.16 fixed point */ yaw = avio_rb32(pb); pitch = avio_rb32(pb); roll = avio_rb32(pb); size = avio_rb32(pb); if (size > atom.size) return AVERROR_INVALIDDATA; tag = avio_rl32(pb); avio_skip(pb, 4); /* version + flags */ switch (tag) { case MKTAG('c','b','m','p'): layout = avio_rb32(pb); if (layout) { av_log(c->fc, AV_LOG_WARNING, "Unsupported cubemap layout %d\n", layout); return 0; } projection = AV_SPHERICAL_CUBEMAP; padding = avio_rb32(pb); break; case MKTAG('e','q','u','i'): t = avio_rb32(pb); b = avio_rb32(pb); l = avio_rb32(pb); r = avio_rb32(pb); if (b >= UINT_MAX - t || r >= UINT_MAX - l) { av_log(c->fc, AV_LOG_ERROR, "Invalid bounding rectangle coordinates " "%"PRIu32",%"PRIu32",%"PRIu32",%"PRIu32"\n", l, t, r, b); return AVERROR_INVALIDDATA; } if (l || t || r || b) projection = AV_SPHERICAL_EQUIRECTANGULAR_TILE; else projection = AV_SPHERICAL_EQUIRECTANGULAR; break; default: av_log(c->fc, AV_LOG_ERROR, "Unknown projection type\n"); return 0; } sc->spherical = av_spherical_alloc(&sc->spherical_size); if (!sc->spherical) return AVERROR(ENOMEM); sc->spherical->projection = projection; sc->spherical->yaw = yaw; sc->spherical->pitch = pitch; sc->spherical->roll = roll; sc->spherical->padding = padding; sc->spherical->bound_left = l; sc->spherical->bound_top = t; sc->spherical->bound_right = r; sc->spherical->bound_bottom = b; return 0; } static int mov_parse_uuid_spherical(MOVStreamContext *sc, AVIOContext *pb, size_t len) { int ret = 0; uint8_t *buffer = av_malloc(len + 1); const char *val; if (!buffer) return AVERROR(ENOMEM); buffer[len] = '\0'; ret = ffio_read_size(pb, buffer, len); if (ret < 0) goto out; /* Check for mandatory keys and values, try to support XML as best-effort */ if (av_stristr(buffer, "<GSpherical:StitchingSoftware>") && (val = av_stristr(buffer, "<GSpherical:Spherical>")) && av_stristr(val, "true") && (val = av_stristr(buffer, "<GSpherical:Stitched>")) && av_stristr(val, "true") && (val = av_stristr(buffer, "<GSpherical:ProjectionType>")) && av_stristr(val, "equirectangular")) { sc->spherical = av_spherical_alloc(&sc->spherical_size); if (!sc->spherical) goto out; sc->spherical->projection = AV_SPHERICAL_EQUIRECTANGULAR; if (av_stristr(buffer, "<GSpherical:StereoMode>")) { enum AVStereo3DType mode; if (av_stristr(buffer, "left-right")) mode = AV_STEREO3D_SIDEBYSIDE; else if (av_stristr(buffer, "top-bottom")) mode = AV_STEREO3D_TOPBOTTOM; else mode = AV_STEREO3D_2D; sc->stereo3d = av_stereo3d_alloc(); if (!sc->stereo3d) goto out; sc->stereo3d->type = mode; } /* orientation */ val = av_stristr(buffer, "<GSpherical:InitialViewHeadingDegrees>"); if (val) sc->spherical->yaw = strtol(val, NULL, 10) * (1 << 16); val = av_stristr(buffer, "<GSpherical:InitialViewPitchDegrees>"); if (val) sc->spherical->pitch = strtol(val, NULL, 10) * (1 << 16); val = av_stristr(buffer, "<GSpherical:InitialViewRollDegrees>"); if (val) sc->spherical->roll = strtol(val, NULL, 10) * (1 << 16); } out: av_free(buffer); return ret; } static int mov_read_uuid(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; int64_t ret; uint8_t uuid[16]; static const uint8_t uuid_isml_manifest[] = { 0xa5, 0xd4, 0x0b, 0x30, 0xe8, 0x14, 0x11, 0xdd, 0xba, 0x2f, 0x08, 0x00, 0x20, 0x0c, 0x9a, 0x66 }; static const uint8_t uuid_xmp[] = { 0xbe, 0x7a, 0xcf, 0xcb, 0x97, 0xa9, 0x42, 0xe8, 0x9c, 0x71, 0x99, 0x94, 0x91, 0xe3, 0xaf, 0xac }; static const uint8_t uuid_spherical[] = { 0xff, 0xcc, 0x82, 0x63, 0xf8, 0x55, 0x4a, 0x93, 0x88, 0x14, 0x58, 0x7a, 0x02, 0x52, 0x1f, 0xdd, }; if (atom.size < sizeof(uuid) || atom.size >= FFMIN(INT_MAX, SIZE_MAX)) return AVERROR_INVALIDDATA; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; ret = avio_read(pb, uuid, sizeof(uuid)); if (ret < 0) { return ret; } else if (ret != sizeof(uuid)) { return AVERROR_INVALIDDATA; } if (!memcmp(uuid, uuid_isml_manifest, sizeof(uuid))) { uint8_t *buffer, *ptr; char *endptr; size_t len = atom.size - sizeof(uuid); if (len < 4) { return AVERROR_INVALIDDATA; } ret = avio_skip(pb, 4); // zeroes len -= 4; buffer = av_mallocz(len + 1); if (!buffer) { return AVERROR(ENOMEM); } ret = avio_read(pb, buffer, len); if (ret < 0) { av_free(buffer); return ret; } else if (ret != len) { av_free(buffer); return AVERROR_INVALIDDATA; } ptr = buffer; while ((ptr = av_stristr(ptr, "systemBitrate=\""))) { ptr += sizeof("systemBitrate=\"") - 1; c->bitrates_count++; c->bitrates = av_realloc_f(c->bitrates, c->bitrates_count, sizeof(*c->bitrates)); if (!c->bitrates) { c->bitrates_count = 0; av_free(buffer); return AVERROR(ENOMEM); } errno = 0; ret = strtol(ptr, &endptr, 10); if (ret < 0 || errno || *endptr != '"') { c->bitrates[c->bitrates_count - 1] = 0; } else { c->bitrates[c->bitrates_count - 1] = ret; } } av_free(buffer); } else if (!memcmp(uuid, uuid_xmp, sizeof(uuid))) { uint8_t *buffer; size_t len = atom.size - sizeof(uuid); if (c->export_xmp) { buffer = av_mallocz(len + 1); if (!buffer) { return AVERROR(ENOMEM); } ret = avio_read(pb, buffer, len); if (ret < 0) { av_free(buffer); return ret; } else if (ret != len) { av_free(buffer); return AVERROR_INVALIDDATA; } buffer[len] = '\0'; av_dict_set(&c->fc->metadata, "xmp", buffer, 0); av_free(buffer); } else { // skip all uuid atom, which makes it fast for long uuid-xmp file ret = avio_skip(pb, len); if (ret < 0) return ret; } } else if (!memcmp(uuid, uuid_spherical, sizeof(uuid))) { size_t len = atom.size - sizeof(uuid); ret = mov_parse_uuid_spherical(sc, pb, len); if (ret < 0) return ret; if (!sc->spherical) av_log(c->fc, AV_LOG_WARNING, "Invalid spherical metadata found\n"); } return 0; } static int mov_read_free(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int ret; uint8_t content[16]; if (atom.size < 8) return 0; ret = avio_read(pb, content, FFMIN(sizeof(content), atom.size)); if (ret < 0) return ret; if ( !c->found_moov && !c->found_mdat && !memcmp(content, "Anevia\x1A\x1A", 8) && c->use_mfra_for == FF_MOV_FLAG_MFRA_AUTO) { c->use_mfra_for = FF_MOV_FLAG_MFRA_PTS; } return 0; } static int mov_read_frma(MOVContext *c, AVIOContext *pb, MOVAtom atom) { uint32_t format = avio_rl32(pb); MOVStreamContext *sc; enum AVCodecID id; AVStream *st; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; switch (sc->format) { case MKTAG('e','n','c','v'): // encrypted video case MKTAG('e','n','c','a'): // encrypted audio id = mov_codec_id(st, format); if (st->codecpar->codec_id != AV_CODEC_ID_NONE && st->codecpar->codec_id != id) { av_log(c->fc, AV_LOG_WARNING, "ignoring 'frma' atom of '%.4s', stream has codec id %d\n", (char*)&format, st->codecpar->codec_id); break; } st->codecpar->codec_id = id; sc->format = format; break; default: if (format != sc->format) { av_log(c->fc, AV_LOG_WARNING, "ignoring 'frma' atom of '%.4s', stream format is '%.4s'\n", (char*)&format, (char*)&sc->format); } break; } return 0; } static int mov_read_senc(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; size_t auxiliary_info_size; if (c->decryption_key_len == 0 || c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (sc->cenc.aes_ctr) { av_log(c->fc, AV_LOG_ERROR, "duplicate senc atom\n"); return AVERROR_INVALIDDATA; } avio_r8(pb); /* version */ sc->cenc.use_subsamples = avio_rb24(pb) & 0x02; /* flags */ avio_rb32(pb); /* entries */ if (atom.size < 8 || atom.size > FFMIN(INT_MAX, SIZE_MAX)) { av_log(c->fc, AV_LOG_ERROR, "senc atom size %"PRId64" invalid\n", atom.size); return AVERROR_INVALIDDATA; } /* save the auxiliary info as is */ auxiliary_info_size = atom.size - 8; sc->cenc.auxiliary_info = av_malloc(auxiliary_info_size); if (!sc->cenc.auxiliary_info) { return AVERROR(ENOMEM); } sc->cenc.auxiliary_info_end = sc->cenc.auxiliary_info + auxiliary_info_size; sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info; sc->cenc.auxiliary_info_index = 0; if (avio_read(pb, sc->cenc.auxiliary_info, auxiliary_info_size) != auxiliary_info_size) { av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info"); return AVERROR_INVALIDDATA; } /* initialize the cipher */ sc->cenc.aes_ctr = av_aes_ctr_alloc(); if (!sc->cenc.aes_ctr) { return AVERROR(ENOMEM); } return av_aes_ctr_init(sc->cenc.aes_ctr, c->decryption_key); } static int mov_read_saiz(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; MOVStreamContext *sc; size_t data_size; int atom_header_size; int flags; if (c->decryption_key_len == 0 || c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams - 1]; sc = st->priv_data; if (sc->cenc.auxiliary_info_sizes || sc->cenc.auxiliary_info_default_size) { av_log(c->fc, AV_LOG_ERROR, "duplicate saiz atom\n"); return AVERROR_INVALIDDATA; } atom_header_size = 9; avio_r8(pb); /* version */ flags = avio_rb24(pb); if ((flags & 0x01) != 0) { atom_header_size += 8; avio_rb32(pb); /* info type */ avio_rb32(pb); /* info type param */ } sc->cenc.auxiliary_info_default_size = avio_r8(pb); avio_rb32(pb); /* entries */ if (atom.size <= atom_header_size) { return 0; } if (atom.size > FFMIN(INT_MAX, SIZE_MAX)) { av_log(c->fc, AV_LOG_ERROR, "saiz atom auxiliary_info_sizes size %"PRId64" invalid\n", atom.size); return AVERROR_INVALIDDATA; } /* save the auxiliary info sizes as is */ data_size = atom.size - atom_header_size; sc->cenc.auxiliary_info_sizes = av_malloc(data_size); if (!sc->cenc.auxiliary_info_sizes) { return AVERROR(ENOMEM); } sc->cenc.auxiliary_info_sizes_count = data_size; if (avio_read(pb, sc->cenc.auxiliary_info_sizes, data_size) != data_size) { av_log(c->fc, AV_LOG_ERROR, "failed to read the auxiliary info sizes"); return AVERROR_INVALIDDATA; } return 0; } static int mov_read_dfla(MOVContext *c, AVIOContext *pb, MOVAtom atom) { AVStream *st; int last, type, size, ret; uint8_t buf[4]; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30) || atom.size < 42) return AVERROR_INVALIDDATA; /* Check FlacSpecificBox version. */ if (avio_r8(pb) != 0) return AVERROR_INVALIDDATA; avio_rb24(pb); /* Flags */ avio_read(pb, buf, sizeof(buf)); flac_parse_block_header(buf, &last, &type, &size); if (type != FLAC_METADATA_TYPE_STREAMINFO || size != FLAC_STREAMINFO_SIZE) { av_log(c->fc, AV_LOG_ERROR, "STREAMINFO must be first FLACMetadataBlock\n"); return AVERROR_INVALIDDATA; } ret = ff_get_extradata(c->fc, st->codecpar, pb, size); if (ret < 0) return ret; if (!last) av_log(c->fc, AV_LOG_WARNING, "non-STREAMINFO FLACMetadataBlock(s) ignored\n"); return 0; } static int mov_seek_auxiliary_info(MOVContext *c, MOVStreamContext *sc, int64_t index) { size_t auxiliary_info_seek_offset = 0; int i; if (sc->cenc.auxiliary_info_default_size) { auxiliary_info_seek_offset = (size_t)sc->cenc.auxiliary_info_default_size * index; } else if (sc->cenc.auxiliary_info_sizes) { if (index > sc->cenc.auxiliary_info_sizes_count) { av_log(c, AV_LOG_ERROR, "current sample %"PRId64" greater than the number of auxiliary info sample sizes %"SIZE_SPECIFIER"\n", index, sc->cenc.auxiliary_info_sizes_count); return AVERROR_INVALIDDATA; } for (i = 0; i < index; i++) { auxiliary_info_seek_offset += sc->cenc.auxiliary_info_sizes[i]; } } if (auxiliary_info_seek_offset > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info) { av_log(c, AV_LOG_ERROR, "auxiliary info offset %"SIZE_SPECIFIER" greater than auxiliary info size %"SIZE_SPECIFIER"\n", auxiliary_info_seek_offset, (size_t)(sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info)); return AVERROR_INVALIDDATA; } sc->cenc.auxiliary_info_pos = sc->cenc.auxiliary_info + auxiliary_info_seek_offset; sc->cenc.auxiliary_info_index = index; return 0; } static int cenc_filter(MOVContext *c, MOVStreamContext *sc, int64_t index, uint8_t *input, int size) { uint32_t encrypted_bytes; uint16_t subsample_count; uint16_t clear_bytes; uint8_t* input_end = input + size; int ret; if (index != sc->cenc.auxiliary_info_index) { ret = mov_seek_auxiliary_info(c, sc, index); if (ret < 0) { return ret; } } /* read the iv */ if (AES_CTR_IV_SIZE > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) { av_log(c->fc, AV_LOG_ERROR, "failed to read iv from the auxiliary info\n"); return AVERROR_INVALIDDATA; } av_aes_ctr_set_iv(sc->cenc.aes_ctr, sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += AES_CTR_IV_SIZE; if (!sc->cenc.use_subsamples) { /* decrypt the whole packet */ av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, size); return 0; } /* read the subsample count */ if (sizeof(uint16_t) > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) { av_log(c->fc, AV_LOG_ERROR, "failed to read subsample count from the auxiliary info\n"); return AVERROR_INVALIDDATA; } subsample_count = AV_RB16(sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += sizeof(uint16_t); for (; subsample_count > 0; subsample_count--) { if (6 > sc->cenc.auxiliary_info_end - sc->cenc.auxiliary_info_pos) { av_log(c->fc, AV_LOG_ERROR, "failed to read subsample from the auxiliary info\n"); return AVERROR_INVALIDDATA; } /* read the number of clear / encrypted bytes */ clear_bytes = AV_RB16(sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += sizeof(uint16_t); encrypted_bytes = AV_RB32(sc->cenc.auxiliary_info_pos); sc->cenc.auxiliary_info_pos += sizeof(uint32_t); if ((uint64_t)clear_bytes + encrypted_bytes > input_end - input) { av_log(c->fc, AV_LOG_ERROR, "subsample size exceeds the packet size left\n"); return AVERROR_INVALIDDATA; } /* skip the clear bytes */ input += clear_bytes; /* decrypt the encrypted bytes */ av_aes_ctr_crypt(sc->cenc.aes_ctr, input, input, encrypted_bytes); input += encrypted_bytes; } if (input < input_end) { av_log(c->fc, AV_LOG_ERROR, "leftover packet bytes after subsample processing\n"); return AVERROR_INVALIDDATA; } sc->cenc.auxiliary_info_index++; return 0; } static int mov_read_dops(MOVContext *c, AVIOContext *pb, MOVAtom atom) { const int OPUS_SEEK_PREROLL_MS = 80; AVStream *st; size_t size; int16_t pre_skip; if (c->fc->nb_streams < 1) return 0; st = c->fc->streams[c->fc->nb_streams-1]; if ((uint64_t)atom.size > (1<<30) || atom.size < 11) return AVERROR_INVALIDDATA; /* Check OpusSpecificBox version. */ if (avio_r8(pb) != 0) { av_log(c->fc, AV_LOG_ERROR, "unsupported OpusSpecificBox version\n"); return AVERROR_INVALIDDATA; } /* OpusSpecificBox size plus magic for Ogg OpusHead header. */ size = atom.size + 8; if (ff_alloc_extradata(st->codecpar, size)) return AVERROR(ENOMEM); AV_WL32(st->codecpar->extradata, MKTAG('O','p','u','s')); AV_WL32(st->codecpar->extradata + 4, MKTAG('H','e','a','d')); AV_WB8(st->codecpar->extradata + 8, 1); /* OpusHead version */ avio_read(pb, st->codecpar->extradata + 9, size - 9); /* OpusSpecificBox is stored in big-endian, but OpusHead is little-endian; aside from the preceeding magic and version they're otherwise currently identical. Data after output gain at offset 16 doesn't need to be bytewapped. */ pre_skip = AV_RB16(st->codecpar->extradata + 10); AV_WL16(st->codecpar->extradata + 10, pre_skip); AV_WL32(st->codecpar->extradata + 12, AV_RB32(st->codecpar->extradata + 12)); AV_WL16(st->codecpar->extradata + 16, AV_RB16(st->codecpar->extradata + 16)); st->codecpar->initial_padding = pre_skip; st->codecpar->seek_preroll = av_rescale_q(OPUS_SEEK_PREROLL_MS, (AVRational){1, 1000}, (AVRational){1, 48000}); return 0; } static const MOVParseTableEntry mov_default_parse_table[] = { { MKTAG('A','C','L','R'), mov_read_aclr }, { MKTAG('A','P','R','G'), mov_read_avid }, { MKTAG('A','A','L','P'), mov_read_avid }, { MKTAG('A','R','E','S'), mov_read_ares }, { MKTAG('a','v','s','s'), mov_read_avss }, { MKTAG('c','h','p','l'), mov_read_chpl }, { MKTAG('c','o','6','4'), mov_read_stco }, { MKTAG('c','o','l','r'), mov_read_colr }, { MKTAG('c','t','t','s'), mov_read_ctts }, /* composition time to sample */ { MKTAG('d','i','n','f'), mov_read_default }, { MKTAG('D','p','x','E'), mov_read_dpxe }, { MKTAG('d','r','e','f'), mov_read_dref }, { MKTAG('e','d','t','s'), mov_read_default }, { MKTAG('e','l','s','t'), mov_read_elst }, { MKTAG('e','n','d','a'), mov_read_enda }, { MKTAG('f','i','e','l'), mov_read_fiel }, { MKTAG('a','d','r','m'), mov_read_adrm }, { MKTAG('f','t','y','p'), mov_read_ftyp }, { MKTAG('g','l','b','l'), mov_read_glbl }, { MKTAG('h','d','l','r'), mov_read_hdlr }, { MKTAG('i','l','s','t'), mov_read_ilst }, { MKTAG('j','p','2','h'), mov_read_jp2h }, { MKTAG('m','d','a','t'), mov_read_mdat }, { MKTAG('m','d','h','d'), mov_read_mdhd }, { MKTAG('m','d','i','a'), mov_read_default }, { MKTAG('m','e','t','a'), mov_read_meta }, { MKTAG('m','i','n','f'), mov_read_default }, { MKTAG('m','o','o','f'), mov_read_moof }, { MKTAG('m','o','o','v'), mov_read_moov }, { MKTAG('m','v','e','x'), mov_read_default }, { MKTAG('m','v','h','d'), mov_read_mvhd }, { MKTAG('S','M','I',' '), mov_read_svq3 }, { MKTAG('a','l','a','c'), mov_read_alac }, /* alac specific atom */ { MKTAG('a','v','c','C'), mov_read_glbl }, { MKTAG('p','a','s','p'), mov_read_pasp }, { MKTAG('s','i','d','x'), mov_read_sidx }, { MKTAG('s','t','b','l'), mov_read_default }, { MKTAG('s','t','c','o'), mov_read_stco }, { MKTAG('s','t','p','s'), mov_read_stps }, { MKTAG('s','t','r','f'), mov_read_strf }, { MKTAG('s','t','s','c'), mov_read_stsc }, { MKTAG('s','t','s','d'), mov_read_stsd }, /* sample description */ { MKTAG('s','t','s','s'), mov_read_stss }, /* sync sample */ { MKTAG('s','t','s','z'), mov_read_stsz }, /* sample size */ { MKTAG('s','t','t','s'), mov_read_stts }, { MKTAG('s','t','z','2'), mov_read_stsz }, /* compact sample size */ { MKTAG('t','k','h','d'), mov_read_tkhd }, /* track header */ { MKTAG('t','f','d','t'), mov_read_tfdt }, { MKTAG('t','f','h','d'), mov_read_tfhd }, /* track fragment header */ { MKTAG('t','r','a','k'), mov_read_trak }, { MKTAG('t','r','a','f'), mov_read_default }, { MKTAG('t','r','e','f'), mov_read_default }, { MKTAG('t','m','c','d'), mov_read_tmcd }, { MKTAG('c','h','a','p'), mov_read_chap }, { MKTAG('t','r','e','x'), mov_read_trex }, { MKTAG('t','r','u','n'), mov_read_trun }, { MKTAG('u','d','t','a'), mov_read_default }, { MKTAG('w','a','v','e'), mov_read_wave }, { MKTAG('e','s','d','s'), mov_read_esds }, { MKTAG('d','a','c','3'), mov_read_dac3 }, /* AC-3 info */ { MKTAG('d','e','c','3'), mov_read_dec3 }, /* EAC-3 info */ { MKTAG('d','d','t','s'), mov_read_ddts }, /* DTS audio descriptor */ { MKTAG('w','i','d','e'), mov_read_wide }, /* place holder */ { MKTAG('w','f','e','x'), mov_read_wfex }, { MKTAG('c','m','o','v'), mov_read_cmov }, { MKTAG('c','h','a','n'), mov_read_chan }, /* channel layout */ { MKTAG('d','v','c','1'), mov_read_dvc1 }, { MKTAG('s','b','g','p'), mov_read_sbgp }, { MKTAG('h','v','c','C'), mov_read_glbl }, { MKTAG('u','u','i','d'), mov_read_uuid }, { MKTAG('C','i','n', 0x8e), mov_read_targa_y216 }, { MKTAG('f','r','e','e'), mov_read_free }, { MKTAG('-','-','-','-'), mov_read_custom }, { MKTAG('s','i','n','f'), mov_read_default }, { MKTAG('f','r','m','a'), mov_read_frma }, { MKTAG('s','e','n','c'), mov_read_senc }, { MKTAG('s','a','i','z'), mov_read_saiz }, { MKTAG('d','f','L','a'), mov_read_dfla }, { MKTAG('s','t','3','d'), mov_read_st3d }, /* stereoscopic 3D video box */ { MKTAG('s','v','3','d'), mov_read_sv3d }, /* spherical video box */ { MKTAG('d','O','p','s'), mov_read_dops }, { MKTAG('S','m','D','m'), mov_read_smdm }, { MKTAG('C','o','L','L'), mov_read_coll }, { MKTAG('v','p','c','C'), mov_read_vpcc }, { 0, NULL } }; static int mov_read_default(MOVContext *c, AVIOContext *pb, MOVAtom atom) { int64_t total_size = 0; MOVAtom a; int i; if (c->atom_depth > 10) { av_log(c->fc, AV_LOG_ERROR, "Atoms too deeply nested\n"); return AVERROR_INVALIDDATA; } c->atom_depth ++; if (atom.size < 0) atom.size = INT64_MAX; while (total_size <= atom.size - 8 && !avio_feof(pb)) { int (*parse)(MOVContext*, AVIOContext*, MOVAtom) = NULL; a.size = atom.size; a.type=0; if (atom.size >= 8) { a.size = avio_rb32(pb); a.type = avio_rl32(pb); if (a.type == MKTAG('f','r','e','e') && a.size >= 8 && c->fc->strict_std_compliance < FF_COMPLIANCE_STRICT && c->moov_retry) { uint8_t buf[8]; uint32_t *type = (uint32_t *)buf + 1; if (avio_read(pb, buf, 8) != 8) return AVERROR_INVALIDDATA; avio_seek(pb, -8, SEEK_CUR); if (*type == MKTAG('m','v','h','d') || *type == MKTAG('c','m','o','v')) { av_log(c->fc, AV_LOG_ERROR, "Detected moov in a free atom.\n"); a.type = MKTAG('m','o','o','v'); } } if (atom.type != MKTAG('r','o','o','t') && atom.type != MKTAG('m','o','o','v')) { if (a.type == MKTAG('t','r','a','k') || a.type == MKTAG('m','d','a','t')) { av_log(c->fc, AV_LOG_ERROR, "Broken file, trak/mdat not at top-level\n"); avio_skip(pb, -8); c->atom_depth --; return 0; } } total_size += 8; if (a.size == 1 && total_size + 8 <= atom.size) { /* 64 bit extended size */ a.size = avio_rb64(pb) - 8; total_size += 8; } } av_log(c->fc, AV_LOG_TRACE, "type:'%s' parent:'%s' sz: %"PRId64" %"PRId64" %"PRId64"\n", av_fourcc2str(a.type), av_fourcc2str(atom.type), a.size, total_size, atom.size); if (a.size == 0) { a.size = atom.size - total_size + 8; } a.size -= 8; if (a.size < 0) break; a.size = FFMIN(a.size, atom.size - total_size); for (i = 0; mov_default_parse_table[i].type; i++) if (mov_default_parse_table[i].type == a.type) { parse = mov_default_parse_table[i].parse; break; } // container is user data if (!parse && (atom.type == MKTAG('u','d','t','a') || atom.type == MKTAG('i','l','s','t'))) parse = mov_read_udta_string; // Supports parsing the QuickTime Metadata Keys. // https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html if (!parse && c->found_hdlr_mdta && atom.type == MKTAG('m','e','t','a') && a.type == MKTAG('k','e','y','s')) { parse = mov_read_keys; } if (!parse) { /* skip leaf atoms data */ avio_skip(pb, a.size); } else { int64_t start_pos = avio_tell(pb); int64_t left; int err = parse(c, pb, a); if (err < 0) { c->atom_depth --; return err; } if (c->found_moov && c->found_mdat && ((!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) || start_pos + a.size == avio_size(pb))) { if (!(pb->seekable & AVIO_SEEKABLE_NORMAL) || c->fc->flags & AVFMT_FLAG_IGNIDX || c->fragment_index_complete) c->next_root_atom = start_pos + a.size; c->atom_depth --; return 0; } left = a.size - avio_tell(pb) + start_pos; if (left > 0) /* skip garbage at atom end */ avio_skip(pb, left); else if (left < 0) { av_log(c->fc, AV_LOG_WARNING, "overread end of atom '%.4s' by %"PRId64" bytes\n", (char*)&a.type, -left); avio_seek(pb, left, SEEK_CUR); } } total_size += a.size; } if (total_size < atom.size && atom.size < 0x7ffff) avio_skip(pb, atom.size - total_size); c->atom_depth --; return 0; } static int mov_probe(AVProbeData *p) { int64_t offset; uint32_t tag; int score = 0; int moov_offset = -1; /* check file header */ offset = 0; for (;;) { /* ignore invalid offset */ if ((offset + 8) > (unsigned int)p->buf_size) break; tag = AV_RL32(p->buf + offset + 4); switch(tag) { /* check for obvious tags */ case MKTAG('m','o','o','v'): moov_offset = offset + 4; case MKTAG('m','d','a','t'): case MKTAG('p','n','o','t'): /* detect movs with preview pics like ew.mov and april.mov */ case MKTAG('u','d','t','a'): /* Packet Video PVAuthor adds this and a lot of more junk */ case MKTAG('f','t','y','p'): if (AV_RB32(p->buf+offset) < 8 && (AV_RB32(p->buf+offset) != 1 || offset + 12 > (unsigned int)p->buf_size || AV_RB64(p->buf+offset + 8) == 0)) { score = FFMAX(score, AVPROBE_SCORE_EXTENSION); } else if (tag == MKTAG('f','t','y','p') && ( AV_RL32(p->buf + offset + 8) == MKTAG('j','p','2',' ') || AV_RL32(p->buf + offset + 8) == MKTAG('j','p','x',' ') )) { score = FFMAX(score, 5); } else { score = AVPROBE_SCORE_MAX; } offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; break; /* those are more common words, so rate then a bit less */ case MKTAG('e','d','i','w'): /* xdcam files have reverted first tags */ case MKTAG('w','i','d','e'): case MKTAG('f','r','e','e'): case MKTAG('j','u','n','k'): case MKTAG('p','i','c','t'): score = FFMAX(score, AVPROBE_SCORE_MAX - 5); offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; break; case MKTAG(0x82,0x82,0x7f,0x7d): case MKTAG('s','k','i','p'): case MKTAG('u','u','i','d'): case MKTAG('p','r','f','l'): /* if we only find those cause probedata is too small at least rate them */ score = FFMAX(score, AVPROBE_SCORE_EXTENSION); offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; break; default: offset = FFMAX(4, AV_RB32(p->buf+offset)) + offset; } } if(score > AVPROBE_SCORE_MAX - 50 && moov_offset != -1) { /* moov atom in the header - we should make sure that this is not a * MOV-packed MPEG-PS */ offset = moov_offset; while(offset < (p->buf_size - 16)){ /* Sufficient space */ /* We found an actual hdlr atom */ if(AV_RL32(p->buf + offset ) == MKTAG('h','d','l','r') && AV_RL32(p->buf + offset + 8) == MKTAG('m','h','l','r') && AV_RL32(p->buf + offset + 12) == MKTAG('M','P','E','G')){ av_log(NULL, AV_LOG_WARNING, "Found media data tag MPEG indicating this is a MOV-packed MPEG-PS.\n"); /* We found a media handler reference atom describing an * MPEG-PS-in-MOV, return a * low score to force expanding the probe window until * mpegps_probe finds what it needs */ return 5; }else /* Keep looking */ offset+=2; } } return score; } // must be done after parsing all trak because there's no order requirement static void mov_read_chapters(AVFormatContext *s) { MOVContext *mov = s->priv_data; AVStream *st; MOVStreamContext *sc; int64_t cur_pos; int i, j; int chapter_track; for (j = 0; j < mov->nb_chapter_tracks; j++) { chapter_track = mov->chapter_tracks[j]; st = NULL; for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->id == chapter_track) { st = s->streams[i]; break; } if (!st) { av_log(s, AV_LOG_ERROR, "Referenced QT chapter track not found\n"); continue; } sc = st->priv_data; cur_pos = avio_tell(sc->pb); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { st->disposition |= AV_DISPOSITION_ATTACHED_PIC | AV_DISPOSITION_TIMED_THUMBNAILS; if (st->nb_index_entries) { // Retrieve the first frame, if possible AVPacket pkt; AVIndexEntry *sample = &st->index_entries[0]; if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) { av_log(s, AV_LOG_ERROR, "Failed to retrieve first frame\n"); goto finish; } if (av_get_packet(sc->pb, &pkt, sample->size) < 0) goto finish; st->attached_pic = pkt; st->attached_pic.stream_index = st->index; st->attached_pic.flags |= AV_PKT_FLAG_KEY; } } else { st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->codecpar->codec_id = AV_CODEC_ID_BIN_DATA; st->discard = AVDISCARD_ALL; for (i = 0; i < st->nb_index_entries; i++) { AVIndexEntry *sample = &st->index_entries[i]; int64_t end = i+1 < st->nb_index_entries ? st->index_entries[i+1].timestamp : st->duration; uint8_t *title; uint16_t ch; int len, title_len; if (end < sample->timestamp) { av_log(s, AV_LOG_WARNING, "ignoring stream duration which is shorter than chapters\n"); end = AV_NOPTS_VALUE; } if (avio_seek(sc->pb, sample->pos, SEEK_SET) != sample->pos) { av_log(s, AV_LOG_ERROR, "Chapter %d not found in file\n", i); goto finish; } // the first two bytes are the length of the title len = avio_rb16(sc->pb); if (len > sample->size-2) continue; title_len = 2*len + 1; if (!(title = av_mallocz(title_len))) goto finish; // The samples could theoretically be in any encoding if there's an encd // atom following, but in practice are only utf-8 or utf-16, distinguished // instead by the presence of a BOM if (!len) { title[0] = 0; } else { ch = avio_rb16(sc->pb); if (ch == 0xfeff) avio_get_str16be(sc->pb, len, title, title_len); else if (ch == 0xfffe) avio_get_str16le(sc->pb, len, title, title_len); else { AV_WB16(title, ch); if (len == 1 || len == 2) title[len] = 0; else avio_get_str(sc->pb, INT_MAX, title + 2, len - 1); } } avpriv_new_chapter(s, i, st->time_base, sample->timestamp, end, title); av_freep(&title); } } finish: avio_seek(sc->pb, cur_pos, SEEK_SET); } } static int parse_timecode_in_framenum_format(AVFormatContext *s, AVStream *st, uint32_t value, int flags) { AVTimecode tc; char buf[AV_TIMECODE_STR_SIZE]; AVRational rate = st->avg_frame_rate; int ret = av_timecode_init(&tc, rate, flags, 0, s); if (ret < 0) return ret; av_dict_set(&st->metadata, "timecode", av_timecode_make_string(&tc, buf, value), 0); return 0; } static int mov_read_rtmd_track(AVFormatContext *s, AVStream *st) { MOVStreamContext *sc = st->priv_data; char buf[AV_TIMECODE_STR_SIZE]; int64_t cur_pos = avio_tell(sc->pb); int hh, mm, ss, ff, drop; if (!st->nb_index_entries) return -1; avio_seek(sc->pb, st->index_entries->pos, SEEK_SET); avio_skip(s->pb, 13); hh = avio_r8(s->pb); mm = avio_r8(s->pb); ss = avio_r8(s->pb); drop = avio_r8(s->pb); ff = avio_r8(s->pb); snprintf(buf, AV_TIMECODE_STR_SIZE, "%02d:%02d:%02d%c%02d", hh, mm, ss, drop ? ';' : ':', ff); av_dict_set(&st->metadata, "timecode", buf, 0); avio_seek(sc->pb, cur_pos, SEEK_SET); return 0; } static int mov_read_timecode_track(AVFormatContext *s, AVStream *st) { MOVStreamContext *sc = st->priv_data; int flags = 0; int64_t cur_pos = avio_tell(sc->pb); uint32_t value; if (!st->nb_index_entries) return -1; avio_seek(sc->pb, st->index_entries->pos, SEEK_SET); value = avio_rb32(s->pb); if (sc->tmcd_flags & 0x0001) flags |= AV_TIMECODE_FLAG_DROPFRAME; if (sc->tmcd_flags & 0x0002) flags |= AV_TIMECODE_FLAG_24HOURSMAX; if (sc->tmcd_flags & 0x0004) flags |= AV_TIMECODE_FLAG_ALLOWNEGATIVE; /* Assume Counter flag is set to 1 in tmcd track (even though it is likely * not the case) and thus assume "frame number format" instead of QT one. * No sample with tmcd track can be found with a QT timecode at the moment, * despite what the tmcd track "suggests" (Counter flag set to 0 means QT * format). */ parse_timecode_in_framenum_format(s, st, value, flags); avio_seek(sc->pb, cur_pos, SEEK_SET); return 0; } static int mov_read_close(AVFormatContext *s) { MOVContext *mov = s->priv_data; int i, j; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (!sc) continue; av_freep(&sc->ctts_data); for (j = 0; j < sc->drefs_count; j++) { av_freep(&sc->drefs[j].path); av_freep(&sc->drefs[j].dir); } av_freep(&sc->drefs); sc->drefs_count = 0; if (!sc->pb_is_copied) ff_format_io_close(s, &sc->pb); sc->pb = NULL; av_freep(&sc->chunk_offsets); av_freep(&sc->stsc_data); av_freep(&sc->sample_sizes); av_freep(&sc->keyframes); av_freep(&sc->stts_data); av_freep(&sc->stps_data); av_freep(&sc->elst_data); av_freep(&sc->rap_group); av_freep(&sc->display_matrix); av_freep(&sc->index_ranges); if (sc->extradata) for (j = 0; j < sc->stsd_count; j++) av_free(sc->extradata[j]); av_freep(&sc->extradata); av_freep(&sc->extradata_size); av_freep(&sc->cenc.auxiliary_info); av_freep(&sc->cenc.auxiliary_info_sizes); av_aes_ctr_free(sc->cenc.aes_ctr); av_freep(&sc->stereo3d); av_freep(&sc->spherical); av_freep(&sc->mastering); av_freep(&sc->coll); } if (mov->dv_demux) { avformat_free_context(mov->dv_fctx); mov->dv_fctx = NULL; } if (mov->meta_keys) { for (i = 1; i < mov->meta_keys_count; i++) { av_freep(&mov->meta_keys[i]); } av_freep(&mov->meta_keys); } av_freep(&mov->trex_data); av_freep(&mov->bitrates); for (i = 0; i < mov->fragment_index_count; i++) { MOVFragmentIndex* index = mov->fragment_index_data[i]; av_freep(&index->items); av_freep(&mov->fragment_index_data[i]); } av_freep(&mov->fragment_index_data); av_freep(&mov->aes_decrypt); av_freep(&mov->chapter_tracks); return 0; } static int tmcd_is_referenced(AVFormatContext *s, int tmcd_id) { int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->timecode_track == tmcd_id) return 1; } return 0; } /* look for a tmcd track not referenced by any video track, and export it globally */ static void export_orphan_timecode(AVFormatContext *s) { int i; for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; if (st->codecpar->codec_tag == MKTAG('t','m','c','d') && !tmcd_is_referenced(s, i + 1)) { AVDictionaryEntry *tcr = av_dict_get(st->metadata, "timecode", NULL, 0); if (tcr) { av_dict_set(&s->metadata, "timecode", tcr->value, 0); break; } } } } static int read_tfra(MOVContext *mov, AVIOContext *f) { MOVFragmentIndex* index = NULL; int version, fieldlength, i, j; int64_t pos = avio_tell(f); uint32_t size = avio_rb32(f); void *tmp; if (avio_rb32(f) != MKBETAG('t', 'f', 'r', 'a')) { return 1; } av_log(mov->fc, AV_LOG_VERBOSE, "found tfra\n"); index = av_mallocz(sizeof(MOVFragmentIndex)); if (!index) { return AVERROR(ENOMEM); } tmp = av_realloc_array(mov->fragment_index_data, mov->fragment_index_count + 1, sizeof(MOVFragmentIndex*)); if (!tmp) { av_freep(&index); return AVERROR(ENOMEM); } mov->fragment_index_data = tmp; mov->fragment_index_data[mov->fragment_index_count++] = index; version = avio_r8(f); avio_rb24(f); index->track_id = avio_rb32(f); fieldlength = avio_rb32(f); index->item_count = avio_rb32(f); index->items = av_mallocz_array( index->item_count, sizeof(MOVFragmentIndexItem)); if (!index->items) { index->item_count = 0; return AVERROR(ENOMEM); } for (i = 0; i < index->item_count; i++) { int64_t time, offset; if (avio_feof(f)) { index->item_count = 0; av_freep(&index->items); return AVERROR_INVALIDDATA; } if (version == 1) { time = avio_rb64(f); offset = avio_rb64(f); } else { time = avio_rb32(f); offset = avio_rb32(f); } index->items[i].time = time; index->items[i].moof_offset = offset; for (j = 0; j < ((fieldlength >> 4) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 2) & 3) + 1; j++) avio_r8(f); for (j = 0; j < ((fieldlength >> 0) & 3) + 1; j++) avio_r8(f); } avio_seek(f, pos + size, SEEK_SET); return 0; } static int mov_read_mfra(MOVContext *c, AVIOContext *f) { int64_t stream_size = avio_size(f); int64_t original_pos = avio_tell(f); int64_t seek_ret; int32_t mfra_size; int ret = -1; if ((seek_ret = avio_seek(f, stream_size - 4, SEEK_SET)) < 0) { ret = seek_ret; goto fail; } mfra_size = avio_rb32(f); if (mfra_size < 0 || mfra_size > stream_size) { av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (unreasonable size)\n"); goto fail; } if ((seek_ret = avio_seek(f, -mfra_size, SEEK_CUR)) < 0) { ret = seek_ret; goto fail; } if (avio_rb32(f) != mfra_size) { av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (size mismatch)\n"); goto fail; } if (avio_rb32(f) != MKBETAG('m', 'f', 'r', 'a')) { av_log(c->fc, AV_LOG_DEBUG, "doesn't look like mfra (tag mismatch)\n"); goto fail; } av_log(c->fc, AV_LOG_VERBOSE, "stream has mfra\n"); do { ret = read_tfra(c, f); if (ret < 0) goto fail; } while (!ret); ret = 0; fail: seek_ret = avio_seek(f, original_pos, SEEK_SET); if (seek_ret < 0) { av_log(c->fc, AV_LOG_ERROR, "failed to seek back after looking for mfra\n"); ret = seek_ret; } return ret; } static int mov_read_header(AVFormatContext *s) { MOVContext *mov = s->priv_data; AVIOContext *pb = s->pb; int j, err; MOVAtom atom = { AV_RL32("root") }; int i; if (mov->decryption_key_len != 0 && mov->decryption_key_len != AES_CTR_KEY_SIZE) { av_log(s, AV_LOG_ERROR, "Invalid decryption key len %d expected %d\n", mov->decryption_key_len, AES_CTR_KEY_SIZE); return AVERROR(EINVAL); } mov->fc = s; mov->trak_index = -1; /* .mov and .mp4 aren't streamable anyway (only progressive download if moov is before mdat) */ if (pb->seekable & AVIO_SEEKABLE_NORMAL) atom.size = avio_size(pb); else atom.size = INT64_MAX; /* check MOV header */ do { if (mov->moov_retry) avio_seek(pb, 0, SEEK_SET); if ((err = mov_read_default(mov, pb, atom)) < 0) { av_log(s, AV_LOG_ERROR, "error reading header\n"); mov_read_close(s); return err; } } while ((pb->seekable & AVIO_SEEKABLE_NORMAL) && !mov->found_moov && !mov->moov_retry++); if (!mov->found_moov) { av_log(s, AV_LOG_ERROR, "moov atom not found\n"); mov_read_close(s); return AVERROR_INVALIDDATA; } av_log(mov->fc, AV_LOG_TRACE, "on_parse_exit_offset=%"PRId64"\n", avio_tell(pb)); if (pb->seekable & AVIO_SEEKABLE_NORMAL) { if (mov->nb_chapter_tracks > 0 && !mov->ignore_chapters) mov_read_chapters(s); for (i = 0; i < s->nb_streams; i++) if (s->streams[i]->codecpar->codec_tag == AV_RL32("tmcd")) { mov_read_timecode_track(s, s->streams[i]); } else if (s->streams[i]->codecpar->codec_tag == AV_RL32("rtmd")) { mov_read_rtmd_track(s, s->streams[i]); } } /* copy timecode metadata from tmcd tracks to the related video streams */ for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (sc->timecode_track > 0) { AVDictionaryEntry *tcr; int tmcd_st_id = -1; for (j = 0; j < s->nb_streams; j++) if (s->streams[j]->id == sc->timecode_track) tmcd_st_id = j; if (tmcd_st_id < 0 || tmcd_st_id == i) continue; tcr = av_dict_get(s->streams[tmcd_st_id]->metadata, "timecode", NULL, 0); if (tcr) av_dict_set(&st->metadata, "timecode", tcr->value, 0); } } export_orphan_timecode(s); for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; fix_timescale(mov, sc); if(st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO && st->codecpar->codec_id == AV_CODEC_ID_AAC) { st->skip_samples = sc->start_pad; } if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && sc->nb_frames_for_fps > 0 && sc->duration_for_fps > 0) av_reduce(&st->avg_frame_rate.num, &st->avg_frame_rate.den, sc->time_scale*(int64_t)sc->nb_frames_for_fps, sc->duration_for_fps, INT_MAX); if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE) { if (st->codecpar->width <= 0 || st->codecpar->height <= 0) { st->codecpar->width = sc->width; st->codecpar->height = sc->height; } if (st->codecpar->codec_id == AV_CODEC_ID_DVD_SUBTITLE) { if ((err = mov_rewrite_dvd_sub_extradata(st)) < 0) return err; } } if (mov->handbrake_version && mov->handbrake_version <= 1000000*0 + 1000*10 + 2 && // 0.10.2 st->codecpar->codec_id == AV_CODEC_ID_MP3 ) { av_log(s, AV_LOG_VERBOSE, "Forcing full parsing for mp3 stream\n"); st->need_parsing = AVSTREAM_PARSE_FULL; } } if (mov->trex_data) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (st->duration > 0) { if (sc->data_size > INT64_MAX / sc->time_scale / 8) { av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n", sc->data_size, sc->time_scale); mov_read_close(s); return AVERROR_INVALIDDATA; } st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / st->duration; } } } if (mov->use_mfra_for > 0) { for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; if (sc->duration_for_fps > 0) { if (sc->data_size > INT64_MAX / sc->time_scale / 8) { av_log(s, AV_LOG_ERROR, "Overflow during bit rate calculation %"PRId64" * 8 * %d\n", sc->data_size, sc->time_scale); mov_read_close(s); return AVERROR_INVALIDDATA; } st->codecpar->bit_rate = sc->data_size * 8 * sc->time_scale / sc->duration_for_fps; } } } for (i = 0; i < mov->bitrates_count && i < s->nb_streams; i++) { if (mov->bitrates[i]) { s->streams[i]->codecpar->bit_rate = mov->bitrates[i]; } } ff_rfps_calculate(s); for (i = 0; i < s->nb_streams; i++) { AVStream *st = s->streams[i]; MOVStreamContext *sc = st->priv_data; switch (st->codecpar->codec_type) { case AVMEDIA_TYPE_AUDIO: err = ff_replaygain_export(st, s->metadata); if (err < 0) { mov_read_close(s); return err; } break; case AVMEDIA_TYPE_VIDEO: if (sc->display_matrix) { err = av_stream_add_side_data(st, AV_PKT_DATA_DISPLAYMATRIX, (uint8_t*)sc->display_matrix, sizeof(int32_t) * 9); if (err < 0) return err; sc->display_matrix = NULL; } if (sc->stereo3d) { err = av_stream_add_side_data(st, AV_PKT_DATA_STEREO3D, (uint8_t *)sc->stereo3d, sizeof(*sc->stereo3d)); if (err < 0) return err; sc->stereo3d = NULL; } if (sc->spherical) { err = av_stream_add_side_data(st, AV_PKT_DATA_SPHERICAL, (uint8_t *)sc->spherical, sc->spherical_size); if (err < 0) return err; sc->spherical = NULL; } if (sc->mastering) { err = av_stream_add_side_data(st, AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)sc->mastering, sizeof(*sc->mastering)); if (err < 0) return err; sc->mastering = NULL; } if (sc->coll) { err = av_stream_add_side_data(st, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)sc->coll, sc->coll_size); if (err < 0) return err; sc->coll = NULL; } break; } } ff_configure_buffers_for_index(s, AV_TIME_BASE); for (i = 0; i < mov->fragment_index_count; i++) { MOVFragmentIndex *idx = mov->fragment_index_data[i]; for (j = 0; j < idx->item_count; j++) if (idx->items[j].moof_offset <= mov->fragment.moof_offset) idx->items[j].headers_read = 1; } return 0; } static AVIndexEntry *mov_find_next_sample(AVFormatContext *s, AVStream **st) { AVIndexEntry *sample = NULL; int64_t best_dts = INT64_MAX; int i; for (i = 0; i < s->nb_streams; i++) { AVStream *avst = s->streams[i]; MOVStreamContext *msc = avst->priv_data; if (msc->pb && msc->current_sample < avst->nb_index_entries) { AVIndexEntry *current_sample = &avst->index_entries[msc->current_sample]; int64_t dts = av_rescale(current_sample->timestamp, AV_TIME_BASE, msc->time_scale); av_log(s, AV_LOG_TRACE, "stream %d, sample %d, dts %"PRId64"\n", i, msc->current_sample, dts); if (!sample || (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL) && current_sample->pos < sample->pos) || ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) && ((msc->pb != s->pb && dts < best_dts) || (msc->pb == s->pb && ((FFABS(best_dts - dts) <= AV_TIME_BASE && current_sample->pos < sample->pos) || (FFABS(best_dts - dts) > AV_TIME_BASE && dts < best_dts)))))) { sample = current_sample; best_dts = dts; *st = avst; } } } return sample; } static int should_retry(AVIOContext *pb, int error_code) { if (error_code == AVERROR_EOF || avio_feof(pb)) return 0; return 1; } static int mov_switch_root(AVFormatContext *s, int64_t target) { MOVContext *mov = s->priv_data; int i, j; int already_read = 0; if (avio_seek(s->pb, target, SEEK_SET) != target) { av_log(mov->fc, AV_LOG_ERROR, "root atom offset 0x%"PRIx64": partial file\n", target); return AVERROR_INVALIDDATA; } mov->next_root_atom = 0; for (i = 0; i < mov->fragment_index_count; i++) { MOVFragmentIndex *index = mov->fragment_index_data[i]; int found = 0; for (j = 0; j < index->item_count; j++) { MOVFragmentIndexItem *item = &index->items[j]; if (found) { mov->next_root_atom = item->moof_offset; break; // Advance to next index in outer loop } else if (item->moof_offset == target) { index->current_item = FFMIN(j, index->current_item); if (item->headers_read) already_read = 1; item->headers_read = 1; found = 1; } } if (!found) index->current_item = 0; } if (already_read) return 0; mov->found_mdat = 0; if (mov_read_default(mov, s->pb, (MOVAtom){ AV_RL32("root"), INT64_MAX }) < 0 || avio_feof(s->pb)) return AVERROR_EOF; av_log(s, AV_LOG_TRACE, "read fragments, offset 0x%"PRIx64"\n", avio_tell(s->pb)); return 1; } static int mov_change_extradata(MOVStreamContext *sc, AVPacket *pkt) { uint8_t *side, *extradata; int extradata_size; /* Save the current index. */ sc->last_stsd_index = sc->stsc_data[sc->stsc_index].id - 1; /* Notify the decoder that extradata changed. */ extradata_size = sc->extradata_size[sc->last_stsd_index]; extradata = sc->extradata[sc->last_stsd_index]; if (extradata_size > 0 && extradata) { side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, extradata_size); if (!side) return AVERROR(ENOMEM); memcpy(side, extradata, extradata_size); } return 0; } static int mov_read_packet(AVFormatContext *s, AVPacket *pkt) { MOVContext *mov = s->priv_data; MOVStreamContext *sc; AVIndexEntry *sample; AVStream *st = NULL; int64_t current_index; int ret; mov->fc = s; retry: sample = mov_find_next_sample(s, &st); if (!sample || (mov->next_root_atom && sample->pos > mov->next_root_atom)) { if (!mov->next_root_atom) return AVERROR_EOF; if ((ret = mov_switch_root(s, mov->next_root_atom)) < 0) return ret; goto retry; } sc = st->priv_data; /* must be done just before reading, to avoid infinite loop on sample */ current_index = sc->current_index; mov_current_sample_inc(sc); if (mov->next_root_atom) { sample->pos = FFMIN(sample->pos, mov->next_root_atom); sample->size = FFMIN(sample->size, (mov->next_root_atom - sample->pos)); } if (st->discard != AVDISCARD_ALL) { int64_t ret64 = avio_seek(sc->pb, sample->pos, SEEK_SET); if (ret64 != sample->pos) { av_log(mov->fc, AV_LOG_ERROR, "stream %d, offset 0x%"PRIx64": partial file\n", sc->ffindex, sample->pos); if (should_retry(sc->pb, ret64)) { mov_current_sample_dec(sc); } return AVERROR_INVALIDDATA; } if( st->discard == AVDISCARD_NONKEY && 0==(sample->flags & AVINDEX_KEYFRAME) ) { av_log(mov->fc, AV_LOG_DEBUG, "Nonkey frame from stream %d discarded due to AVDISCARD_NONKEY\n", sc->ffindex); goto retry; } ret = av_get_packet(sc->pb, pkt, sample->size); if (ret < 0) { if (should_retry(sc->pb, ret)) { mov_current_sample_dec(sc); } return ret; } if (sc->has_palette) { uint8_t *pal; pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); if (!pal) { av_log(mov->fc, AV_LOG_ERROR, "Cannot append palette to packet\n"); } else { memcpy(pal, sc->palette, AVPALETTE_SIZE); sc->has_palette = 0; } } #if CONFIG_DV_DEMUXER if (mov->dv_demux && sc->dv_audio_container) { avpriv_dv_produce_packet(mov->dv_demux, pkt, pkt->data, pkt->size, pkt->pos); av_freep(&pkt->data); pkt->size = 0; ret = avpriv_dv_get_packet(mov->dv_demux, pkt); if (ret < 0) return ret; } #endif if (st->codecpar->codec_id == AV_CODEC_ID_MP3 && !st->need_parsing && pkt->size > 4) { if (ff_mpa_check_header(AV_RB32(pkt->data)) < 0) st->need_parsing = AVSTREAM_PARSE_FULL; } } pkt->stream_index = sc->ffindex; pkt->dts = sample->timestamp; if (sample->flags & AVINDEX_DISCARD_FRAME) { pkt->flags |= AV_PKT_FLAG_DISCARD; } if (sc->ctts_data && sc->ctts_index < sc->ctts_count) { pkt->pts = pkt->dts + sc->dts_shift + sc->ctts_data[sc->ctts_index].duration; /* update ctts context */ sc->ctts_sample++; if (sc->ctts_index < sc->ctts_count && sc->ctts_data[sc->ctts_index].count == sc->ctts_sample) { sc->ctts_index++; sc->ctts_sample = 0; } } else { int64_t next_dts = (sc->current_sample < st->nb_index_entries) ? st->index_entries[sc->current_sample].timestamp : st->duration; pkt->duration = next_dts - pkt->dts; pkt->pts = pkt->dts; } if (st->discard == AVDISCARD_ALL) goto retry; pkt->flags |= sample->flags & AVINDEX_KEYFRAME ? AV_PKT_FLAG_KEY : 0; pkt->pos = sample->pos; /* Multiple stsd handling. */ if (sc->stsc_data) { /* Keep track of the stsc index for the given sample, then check * if the stsd index is different from the last used one. */ sc->stsc_sample++; if (mov_stsc_index_valid(sc->stsc_index, sc->stsc_count) && mov_get_stsc_samples(sc, sc->stsc_index) == sc->stsc_sample) { sc->stsc_index++; sc->stsc_sample = 0; /* Do not check indexes after a switch. */ } else if (sc->stsc_data[sc->stsc_index].id > 0 && sc->stsc_data[sc->stsc_index].id - 1 < sc->stsd_count && sc->stsc_data[sc->stsc_index].id - 1 != sc->last_stsd_index) { ret = mov_change_extradata(sc, pkt); if (ret < 0) return ret; } } if (mov->aax_mode) aax_filter(pkt->data, pkt->size, mov); if (sc->cenc.aes_ctr) { ret = cenc_filter(mov, sc, current_index, pkt->data, pkt->size); if (ret) { return ret; } } return 0; } static int mov_seek_fragment(AVFormatContext *s, AVStream *st, int64_t timestamp) { MOVContext *mov = s->priv_data; MOVStreamContext *sc = st->priv_data; int i, j; if (!mov->fragment_index_complete) return 0; for (i = 0; i < mov->fragment_index_count; i++) { if (mov->fragment_index_data[i]->track_id == st->id || !sc->has_sidx) { MOVFragmentIndex *index = mov->fragment_index_data[i]; for (j = index->item_count - 1; j >= 0; j--) { if (index->items[j].time <= timestamp) { if (index->items[j].headers_read) return 0; return mov_switch_root(s, index->items[j].moof_offset); } } } } return 0; } static int mov_seek_stream(AVFormatContext *s, AVStream *st, int64_t timestamp, int flags) { MOVStreamContext *sc = st->priv_data; int sample, time_sample; int i; int ret = mov_seek_fragment(s, st, timestamp); if (ret < 0) return ret; sample = av_index_search_timestamp(st, timestamp, flags); av_log(s, AV_LOG_TRACE, "stream %d, timestamp %"PRId64", sample %d\n", st->index, timestamp, sample); if (sample < 0 && st->nb_index_entries && timestamp < st->index_entries[0].timestamp) sample = 0; if (sample < 0) /* not sure what to do */ return AVERROR_INVALIDDATA; mov_current_sample_set(sc, sample); av_log(s, AV_LOG_TRACE, "stream %d, found sample %d\n", st->index, sc->current_sample); /* adjust ctts index */ if (sc->ctts_data) { time_sample = 0; for (i = 0; i < sc->ctts_count; i++) { int next = time_sample + sc->ctts_data[i].count; if (next > sc->current_sample) { sc->ctts_index = i; sc->ctts_sample = sc->current_sample - time_sample; break; } time_sample = next; } } /* adjust stsd index */ time_sample = 0; for (i = 0; i < sc->stsc_count; i++) { int next = time_sample + mov_get_stsc_samples(sc, i); if (next > sc->current_sample) { sc->stsc_index = i; sc->stsc_sample = sc->current_sample - time_sample; break; } time_sample = next; } return sample; } static int mov_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { MOVContext *mc = s->priv_data; AVStream *st; int sample; int i; if (stream_index >= s->nb_streams) return AVERROR_INVALIDDATA; st = s->streams[stream_index]; sample = mov_seek_stream(s, st, sample_time, flags); if (sample < 0) return sample; if (mc->seek_individually) { /* adjust seek timestamp to found sample timestamp */ int64_t seek_timestamp = st->index_entries[sample].timestamp; for (i = 0; i < s->nb_streams; i++) { int64_t timestamp; MOVStreamContext *sc = s->streams[i]->priv_data; st = s->streams[i]; st->skip_samples = (sample_time <= 0) ? sc->start_pad : 0; if (stream_index == i) continue; timestamp = av_rescale_q(seek_timestamp, s->streams[stream_index]->time_base, st->time_base); mov_seek_stream(s, st, timestamp, flags); } } else { for (i = 0; i < s->nb_streams; i++) { MOVStreamContext *sc; st = s->streams[i]; sc = st->priv_data; mov_current_sample_set(sc, 0); } while (1) { MOVStreamContext *sc; AVIndexEntry *entry = mov_find_next_sample(s, &st); if (!entry) return AVERROR_INVALIDDATA; sc = st->priv_data; if (sc->ffindex == stream_index && sc->current_sample == sample) break; mov_current_sample_inc(sc); } } return 0; } #define OFFSET(x) offsetof(MOVContext, x) #define FLAGS AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM static const AVOption mov_options[] = { {"use_absolute_path", "allow using absolute path when opening alias, this is a possible security issue", OFFSET(use_absolute_path), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS}, {"seek_streams_individually", "Seek each stream individually to the to the closest point", OFFSET(seek_individually), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS}, {"ignore_editlist", "Ignore the edit list atom.", OFFSET(ignore_editlist), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS}, {"advanced_editlist", "Modify the AVIndex according to the editlists. Use this option to decode in the order specified by the edits.", OFFSET(advanced_editlist), AV_OPT_TYPE_BOOL, {.i64 = 1}, 0, 1, FLAGS}, {"ignore_chapters", "", OFFSET(ignore_chapters), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS}, {"use_mfra_for", "use mfra for fragment timestamps", OFFSET(use_mfra_for), AV_OPT_TYPE_INT, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, -1, FF_MOV_FLAG_MFRA_PTS, FLAGS, "use_mfra_for"}, {"auto", "auto", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_AUTO}, 0, 0, FLAGS, "use_mfra_for" }, {"dts", "dts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_DTS}, 0, 0, FLAGS, "use_mfra_for" }, {"pts", "pts", 0, AV_OPT_TYPE_CONST, {.i64 = FF_MOV_FLAG_MFRA_PTS}, 0, 0, FLAGS, "use_mfra_for" }, { "export_all", "Export unrecognized metadata entries", OFFSET(export_all), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS }, { "export_xmp", "Export full XMP metadata", OFFSET(export_xmp), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, .flags = FLAGS }, { "activation_bytes", "Secret bytes for Audible AAX files", OFFSET(activation_bytes), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM }, { "audible_fixed_key", // extracted from libAAX_SDK.so and AAXSDKWin.dll files! "Fixed key used for handling Audible AAX files", OFFSET(audible_fixed_key), AV_OPT_TYPE_BINARY, {.str="77214d4b196a87cd520045fd20a51d67"}, .flags = AV_OPT_FLAG_DECODING_PARAM }, { "decryption_key", "The media decryption key (hex)", OFFSET(decryption_key), AV_OPT_TYPE_BINARY, .flags = AV_OPT_FLAG_DECODING_PARAM }, { "enable_drefs", "Enable external track support.", OFFSET(enable_drefs), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, FLAGS }, { NULL }, }; static const AVClass mov_class = { .class_name = "mov,mp4,m4a,3gp,3g2,mj2", .item_name = av_default_item_name, .option = mov_options, .version = LIBAVUTIL_VERSION_INT, }; AVInputFormat ff_mov_demuxer = { .name = "mov,mp4,m4a,3gp,3g2,mj2", .long_name = NULL_IF_CONFIG_SMALL("QuickTime / MOV"), .priv_class = &mov_class, .priv_data_size = sizeof(MOVContext), .extensions = "mov,mp4,m4a,3gp,3g2,mj2", .read_probe = mov_probe, .read_header = mov_read_header, .read_packet = mov_read_packet, .read_close = mov_read_close, .read_seek = mov_read_seek, .flags = AVFMT_NO_BYTE_SEEK, };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2786_0
crossvul-cpp_data_good_2762_0
/* * Silicon Graphics Movie demuxer * Copyright (c) 2012 Peter Ross * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Silicon Graphics Movie demuxer */ #include "libavutil/channel_layout.h" #include "libavutil/eval.h" #include "libavutil/intreadwrite.h" #include "libavutil/rational.h" #include "avformat.h" #include "internal.h" typedef struct MvContext { int nb_video_tracks; int nb_audio_tracks; int eof_count; ///< number of streams that have finished int stream_index; ///< current stream index int frame[2]; ///< frame nb for current stream int acompression; ///< compression level for audio stream int aformat; ///< audio format } MvContext; #define AUDIO_FORMAT_SIGNED 401 static int mv_probe(AVProbeData *p) { if (AV_RB32(p->buf) == MKBETAG('M', 'O', 'V', 'I') && AV_RB16(p->buf + 4) < 3) return AVPROBE_SCORE_MAX; return 0; } static char *var_read_string(AVIOContext *pb, int size) { int n; char *str; if (size < 0 || size == INT_MAX) return NULL; str = av_malloc(size + 1); if (!str) return NULL; n = avio_get_str(pb, size, str, size + 1); if (n < size) avio_skip(pb, size - n); return str; } static int var_read_int(AVIOContext *pb, int size) { int v; char *s = var_read_string(pb, size); if (!s) return 0; v = strtol(s, NULL, 10); av_free(s); return v; } static AVRational var_read_float(AVIOContext *pb, int size) { AVRational v; char *s = var_read_string(pb, size); if (!s) return (AVRational) { 0, 0 }; v = av_d2q(av_strtod(s, NULL), INT_MAX); av_free(s); return v; } static void var_read_metadata(AVFormatContext *avctx, const char *tag, int size) { char *value = var_read_string(avctx->pb, size); if (value) av_dict_set(&avctx->metadata, tag, value, AV_DICT_DONT_STRDUP_VAL); } static int set_channels(AVFormatContext *avctx, AVStream *st, int channels) { if (channels <= 0) { av_log(avctx, AV_LOG_ERROR, "Channel count %d invalid.\n", channels); return AVERROR_INVALIDDATA; } st->codecpar->channels = channels; st->codecpar->channel_layout = (st->codecpar->channels == 1) ? AV_CH_LAYOUT_MONO : AV_CH_LAYOUT_STEREO; return 0; } /** * Parse global variable * @return < 0 if unknown */ static int parse_global_var(AVFormatContext *avctx, AVStream *st, const char *name, int size) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; if (!strcmp(name, "__NUM_I_TRACKS")) { mv->nb_video_tracks = var_read_int(pb, size); } else if (!strcmp(name, "__NUM_A_TRACKS")) { mv->nb_audio_tracks = var_read_int(pb, size); } else if (!strcmp(name, "COMMENT") || !strcmp(name, "TITLE")) { var_read_metadata(avctx, name, size); } else if (!strcmp(name, "LOOP_MODE") || !strcmp(name, "NUM_LOOPS") || !strcmp(name, "OPTIMIZED")) { avio_skip(pb, size); // ignore } else return AVERROR_INVALIDDATA; return 0; } /** * Parse audio variable * @return < 0 if unknown */ static int parse_audio_var(AVFormatContext *avctx, AVStream *st, const char *name, int size) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; if (!strcmp(name, "__DIR_COUNT")) { st->nb_frames = var_read_int(pb, size); } else if (!strcmp(name, "AUDIO_FORMAT")) { mv->aformat = var_read_int(pb, size); } else if (!strcmp(name, "COMPRESSION")) { mv->acompression = var_read_int(pb, size); } else if (!strcmp(name, "DEFAULT_VOL")) { var_read_metadata(avctx, name, size); } else if (!strcmp(name, "NUM_CHANNELS")) { return set_channels(avctx, st, var_read_int(pb, size)); } else if (!strcmp(name, "SAMPLE_RATE")) { st->codecpar->sample_rate = var_read_int(pb, size); avpriv_set_pts_info(st, 33, 1, st->codecpar->sample_rate); } else if (!strcmp(name, "SAMPLE_WIDTH")) { st->codecpar->bits_per_coded_sample = var_read_int(pb, size) * 8; } else return AVERROR_INVALIDDATA; return 0; } /** * Parse video variable * @return < 0 if unknown */ static int parse_video_var(AVFormatContext *avctx, AVStream *st, const char *name, int size) { AVIOContext *pb = avctx->pb; if (!strcmp(name, "__DIR_COUNT")) { st->nb_frames = st->duration = var_read_int(pb, size); } else if (!strcmp(name, "COMPRESSION")) { char *str = var_read_string(pb, size); if (!str) return AVERROR_INVALIDDATA; if (!strcmp(str, "1")) { st->codecpar->codec_id = AV_CODEC_ID_MVC1; } else if (!strcmp(str, "2")) { st->codecpar->format = AV_PIX_FMT_ABGR; st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; } else if (!strcmp(str, "3")) { st->codecpar->codec_id = AV_CODEC_ID_SGIRLE; } else if (!strcmp(str, "10")) { st->codecpar->codec_id = AV_CODEC_ID_MJPEG; } else if (!strcmp(str, "MVC2")) { st->codecpar->codec_id = AV_CODEC_ID_MVC2; } else { avpriv_request_sample(avctx, "Video compression %s", str); } av_free(str); } else if (!strcmp(name, "FPS")) { AVRational fps = var_read_float(pb, size); avpriv_set_pts_info(st, 64, fps.den, fps.num); st->avg_frame_rate = fps; } else if (!strcmp(name, "HEIGHT")) { st->codecpar->height = var_read_int(pb, size); } else if (!strcmp(name, "PIXEL_ASPECT")) { st->sample_aspect_ratio = var_read_float(pb, size); av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den, INT_MAX); } else if (!strcmp(name, "WIDTH")) { st->codecpar->width = var_read_int(pb, size); } else if (!strcmp(name, "ORIENTATION")) { if (var_read_int(pb, size) == 1101) { st->codecpar->extradata = av_strdup("BottomUp"); st->codecpar->extradata_size = 9; } } else if (!strcmp(name, "Q_SPATIAL") || !strcmp(name, "Q_TEMPORAL")) { var_read_metadata(avctx, name, size); } else if (!strcmp(name, "INTERLACING") || !strcmp(name, "PACKING")) { avio_skip(pb, size); // ignore } else return AVERROR_INVALIDDATA; return 0; } static int read_table(AVFormatContext *avctx, AVStream *st, int (*parse)(AVFormatContext *avctx, AVStream *st, const char *name, int size)) { int count, i; AVIOContext *pb = avctx->pb; avio_skip(pb, 4); count = avio_rb32(pb); avio_skip(pb, 4); for (i = 0; i < count; i++) { char name[17]; int size; avio_read(pb, name, 16); name[sizeof(name) - 1] = 0; size = avio_rb32(pb); if (size < 0) { av_log(avctx, AV_LOG_ERROR, "entry size %d is invalid\n", size); return AVERROR_INVALIDDATA; } if (parse(avctx, st, name, size) < 0) { avpriv_request_sample(avctx, "Variable %s", name); avio_skip(pb, size); } } return 0; } static void read_index(AVIOContext *pb, AVStream *st) { uint64_t timestamp = 0; int i; for (i = 0; i < st->nb_frames; i++) { uint32_t pos = avio_rb32(pb); uint32_t size = avio_rb32(pb); avio_skip(pb, 8); av_add_index_entry(st, pos, timestamp, size, 0, AVINDEX_KEYFRAME); if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { timestamp += size / (st->codecpar->channels * 2); } else { timestamp++; } } } static int mv_read_header(AVFormatContext *avctx) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; AVStream *ast = NULL, *vst = NULL; //initialization to suppress warning int version, i; int ret; avio_skip(pb, 4); version = avio_rb16(pb); if (version == 2) { uint64_t timestamp; int v; avio_skip(pb, 22); /* allocate audio track first to prevent unnecessary seeking * (audio packet always precede video packet for a given frame) */ ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); avpriv_set_pts_info(vst, 64, 1, 15); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; vst->avg_frame_rate = av_inv_q(vst->time_base); vst->nb_frames = avio_rb32(pb); v = avio_rb32(pb); switch (v) { case 1: vst->codecpar->codec_id = AV_CODEC_ID_MVC1; break; case 2: vst->codecpar->format = AV_PIX_FMT_ARGB; vst->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; break; default: avpriv_request_sample(avctx, "Video compression %i", v); break; } vst->codecpar->codec_tag = 0; vst->codecpar->width = avio_rb32(pb); vst->codecpar->height = avio_rb32(pb); avio_skip(pb, 12); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; ast->nb_frames = vst->nb_frames; ast->codecpar->sample_rate = avio_rb32(pb); if (ast->codecpar->sample_rate <= 0) { av_log(avctx, AV_LOG_ERROR, "Invalid sample rate %d\n", ast->codecpar->sample_rate); return AVERROR_INVALIDDATA; } avpriv_set_pts_info(ast, 33, 1, ast->codecpar->sample_rate); if (set_channels(avctx, ast, avio_rb32(pb)) < 0) return AVERROR_INVALIDDATA; v = avio_rb32(pb); if (v == AUDIO_FORMAT_SIGNED) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression (format %i)", v); } avio_skip(pb, 12); var_read_metadata(avctx, "title", 0x80); var_read_metadata(avctx, "comment", 0x100); avio_skip(pb, 0x80); timestamp = 0; for (i = 0; i < vst->nb_frames; i++) { uint32_t pos = avio_rb32(pb); uint32_t asize = avio_rb32(pb); uint32_t vsize = avio_rb32(pb); if (avio_feof(pb)) return AVERROR_INVALIDDATA; avio_skip(pb, 8); av_add_index_entry(ast, pos, timestamp, asize, 0, AVINDEX_KEYFRAME); av_add_index_entry(vst, pos + asize, i, vsize, 0, AVINDEX_KEYFRAME); timestamp += asize / (ast->codecpar->channels * 2); } } else if (!version && avio_rb16(pb) == 3) { avio_skip(pb, 4); if ((ret = read_table(avctx, NULL, parse_global_var)) < 0) return ret; if (mv->nb_audio_tracks > 1) { avpriv_request_sample(avctx, "Multiple audio streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_audio_tracks) { ast = avformat_new_stream(avctx, NULL); if (!ast) return AVERROR(ENOMEM); ast->codecpar->codec_type = AVMEDIA_TYPE_AUDIO; if ((read_table(avctx, ast, parse_audio_var)) < 0) return ret; if (mv->acompression == 100 && mv->aformat == AUDIO_FORMAT_SIGNED && ast->codecpar->bits_per_coded_sample == 16) { ast->codecpar->codec_id = AV_CODEC_ID_PCM_S16BE; } else { avpriv_request_sample(avctx, "Audio compression %i (format %i, sr %i)", mv->acompression, mv->aformat, ast->codecpar->bits_per_coded_sample); ast->codecpar->codec_id = AV_CODEC_ID_NONE; } if (ast->codecpar->channels <= 0) { av_log(avctx, AV_LOG_ERROR, "No valid channel count found.\n"); return AVERROR_INVALIDDATA; } } if (mv->nb_video_tracks > 1) { avpriv_request_sample(avctx, "Multiple video streams support"); return AVERROR_PATCHWELCOME; } else if (mv->nb_video_tracks) { vst = avformat_new_stream(avctx, NULL); if (!vst) return AVERROR(ENOMEM); vst->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; if ((ret = read_table(avctx, vst, parse_video_var))<0) return ret; } if (mv->nb_audio_tracks) read_index(pb, ast); if (mv->nb_video_tracks) read_index(pb, vst); } else { avpriv_request_sample(avctx, "Version %i", version); return AVERROR_PATCHWELCOME; } return 0; } static int mv_read_packet(AVFormatContext *avctx, AVPacket *pkt) { MvContext *mv = avctx->priv_data; AVIOContext *pb = avctx->pb; AVStream *st = avctx->streams[mv->stream_index]; const AVIndexEntry *index; int frame = mv->frame[mv->stream_index]; int64_t ret; uint64_t pos; if (frame < st->nb_index_entries) { index = &st->index_entries[frame]; pos = avio_tell(pb); if (index->pos > pos) avio_skip(pb, index->pos - pos); else if (index->pos < pos) { if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) return AVERROR(EIO); ret = avio_seek(pb, index->pos, SEEK_SET); if (ret < 0) return ret; } ret = av_get_packet(pb, pkt, index->size); if (ret < 0) return ret; pkt->stream_index = mv->stream_index; pkt->pts = index->timestamp; pkt->flags |= AV_PKT_FLAG_KEY; mv->frame[mv->stream_index]++; mv->eof_count = 0; } else { mv->eof_count++; if (mv->eof_count >= avctx->nb_streams) return AVERROR_EOF; // avoid returning 0 without a packet return AVERROR(EAGAIN); } mv->stream_index++; if (mv->stream_index >= avctx->nb_streams) mv->stream_index = 0; return 0; } static int mv_read_seek(AVFormatContext *avctx, int stream_index, int64_t timestamp, int flags) { MvContext *mv = avctx->priv_data; AVStream *st = avctx->streams[stream_index]; int frame, i; if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE)) return AVERROR(ENOSYS); if (!(avctx->pb->seekable & AVIO_SEEKABLE_NORMAL)) return AVERROR(EIO); frame = av_index_search_timestamp(st, timestamp, flags); if (frame < 0) return AVERROR_INVALIDDATA; for (i = 0; i < avctx->nb_streams; i++) mv->frame[i] = frame; return 0; } AVInputFormat ff_mv_demuxer = { .name = "mv", .long_name = NULL_IF_CONFIG_SMALL("Silicon Graphics Movie"), .priv_data_size = sizeof(MvContext), .read_probe = mv_probe, .read_header = mv_read_header, .read_packet = mv_read_packet, .read_seek = mv_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2762_0
crossvul-cpp_data_good_2779_0
/* * MXF demuxer. * Copyright (c) 2006 SmartJog S.A., Baptiste Coudurier <baptiste dot coudurier at smartjog dot com> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* * References * SMPTE 336M KLV Data Encoding Protocol Using Key-Length-Value * SMPTE 377M MXF File Format Specifications * SMPTE 378M Operational Pattern 1a * SMPTE 379M MXF Generic Container * SMPTE 381M Mapping MPEG Streams into the MXF Generic Container * SMPTE 382M Mapping AES3 and Broadcast Wave Audio into the MXF Generic Container * SMPTE 383M Mapping DV-DIF Data to the MXF Generic Container * * Principle * Search for Track numbers which will identify essence element KLV packets. * Search for SourcePackage which define tracks which contains Track numbers. * Material Package contains tracks with reference to SourcePackage tracks. * Search for Descriptors (Picture, Sound) which contains codec info and parameters. * Assign Descriptors to correct Tracks. * * Metadata reading functions read Local Tags, get InstanceUID(0x3C0A) then add MetaDataSet to MXFContext. * Metadata parsing resolves Strong References to objects. * * Simple demuxer, only OP1A supported and some files might not work at all. * Only tracks with associated descriptors will be decoded. "Highly Desirable" SMPTE 377M D.1 */ #include <inttypes.h> #include "libavutil/aes.h" #include "libavutil/avassert.h" #include "libavutil/mathematics.h" #include "libavcodec/bytestream.h" #include "libavutil/intreadwrite.h" #include "libavutil/parseutils.h" #include "libavutil/timecode.h" #include "avformat.h" #include "internal.h" #include "mxf.h" typedef enum { Header, BodyPartition, Footer } MXFPartitionType; typedef enum { OP1a = 1, OP1b, OP1c, OP2a, OP2b, OP2c, OP3a, OP3b, OP3c, OPAtom, OPSONYOpt, /* FATE sample, violates the spec in places */ } MXFOP; typedef struct MXFPartition { int closed; int complete; MXFPartitionType type; uint64_t previous_partition; int index_sid; int body_sid; int64_t this_partition; int64_t essence_offset; ///< absolute offset of essence int64_t essence_length; int32_t kag_size; int64_t header_byte_count; int64_t index_byte_count; int pack_length; int64_t pack_ofs; ///< absolute offset of pack in file, including run-in } MXFPartition; typedef struct MXFCryptoContext { UID uid; enum MXFMetadataSetType type; UID source_container_ul; } MXFCryptoContext; typedef struct MXFStructuralComponent { UID uid; enum MXFMetadataSetType type; UID source_package_ul; UID source_package_uid; UID data_definition_ul; int64_t duration; int64_t start_position; int source_track_id; } MXFStructuralComponent; typedef struct MXFSequence { UID uid; enum MXFMetadataSetType type; UID data_definition_ul; UID *structural_components_refs; int structural_components_count; int64_t duration; uint8_t origin; } MXFSequence; typedef struct MXFTrack { UID uid; enum MXFMetadataSetType type; int drop_frame; int start_frame; struct AVRational rate; AVTimecode tc; } MXFTimecodeComponent; typedef struct { UID uid; enum MXFMetadataSetType type; UID input_segment_ref; } MXFPulldownComponent; typedef struct { UID uid; enum MXFMetadataSetType type; UID *structural_components_refs; int structural_components_count; int64_t duration; } MXFEssenceGroup; typedef struct { UID uid; enum MXFMetadataSetType type; char *name; char *value; } MXFTaggedValue; typedef struct { UID uid; enum MXFMetadataSetType type; MXFSequence *sequence; /* mandatory, and only one */ UID sequence_ref; int track_id; char *name; uint8_t track_number[4]; AVRational edit_rate; int intra_only; uint64_t sample_count; int64_t original_duration; /* st->duration in SampleRate/EditRate units */ } MXFTrack; typedef struct MXFDescriptor { UID uid; enum MXFMetadataSetType type; UID essence_container_ul; UID essence_codec_ul; UID codec_ul; AVRational sample_rate; AVRational aspect_ratio; int width; int height; /* Field height, not frame height */ int frame_layout; /* See MXFFrameLayout enum */ int video_line_map[2]; #define MXF_FIELD_DOMINANCE_DEFAULT 0 #define MXF_FIELD_DOMINANCE_FF 1 /* coded first, displayed first */ #define MXF_FIELD_DOMINANCE_FL 2 /* coded first, displayed last */ int field_dominance; int channels; int bits_per_sample; int64_t duration; /* ContainerDuration optional property */ unsigned int component_depth; unsigned int horiz_subsampling; unsigned int vert_subsampling; UID *sub_descriptors_refs; int sub_descriptors_count; int linked_track_id; uint8_t *extradata; int extradata_size; enum AVPixelFormat pix_fmt; } MXFDescriptor; typedef struct MXFIndexTableSegment { UID uid; enum MXFMetadataSetType type; int edit_unit_byte_count; int index_sid; int body_sid; AVRational index_edit_rate; uint64_t index_start_position; uint64_t index_duration; int8_t *temporal_offset_entries; int *flag_entries; uint64_t *stream_offset_entries; int nb_index_entries; } MXFIndexTableSegment; typedef struct MXFPackage { UID uid; enum MXFMetadataSetType type; UID package_uid; UID package_ul; UID *tracks_refs; int tracks_count; MXFDescriptor *descriptor; /* only one */ UID descriptor_ref; char *name; UID *comment_refs; int comment_count; } MXFPackage; typedef struct MXFMetadataSet { UID uid; enum MXFMetadataSetType type; } MXFMetadataSet; /* decoded index table */ typedef struct MXFIndexTable { int index_sid; int body_sid; int nb_ptses; /* number of PTSes or total duration of index */ int64_t first_dts; /* DTS = EditUnit + first_dts */ int64_t *ptses; /* maps EditUnit -> PTS */ int nb_segments; MXFIndexTableSegment **segments; /* sorted by IndexStartPosition */ AVIndexEntry *fake_index; /* used for calling ff_index_search_timestamp() */ int8_t *offsets; /* temporal offsets for display order to stored order conversion */ } MXFIndexTable; typedef struct MXFContext { MXFPartition *partitions; unsigned partitions_count; MXFOP op; UID *packages_refs; int packages_count; MXFMetadataSet **metadata_sets; int metadata_sets_count; AVFormatContext *fc; struct AVAES *aesc; uint8_t *local_tags; int local_tags_count; uint64_t footer_partition; KLVPacket current_klv_data; int current_klv_index; int run_in; MXFPartition *current_partition; int parsing_backward; int64_t last_forward_tell; int last_forward_partition; int current_edit_unit; int nb_index_tables; MXFIndexTable *index_tables; int edit_units_per_packet; ///< how many edit units to read at a time (PCM, OPAtom) } MXFContext; enum MXFWrappingScheme { Frame, Clip, }; /* NOTE: klv_offset is not set (-1) for local keys */ typedef int MXFMetadataReadFunc(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset); typedef struct MXFMetadataReadTableEntry { const UID key; MXFMetadataReadFunc *read; int ctx_size; enum MXFMetadataSetType type; } MXFMetadataReadTableEntry; static int mxf_read_close(AVFormatContext *s); /* partial keys to match */ static const uint8_t mxf_header_partition_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02 }; static const uint8_t mxf_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0d,0x01,0x03,0x01 }; static const uint8_t mxf_avid_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x01,0x0e,0x04,0x03,0x01 }; static const uint8_t mxf_canopus_essence_element_key[] = { 0x06,0x0e,0x2b,0x34,0x01,0x02,0x01,0x0a,0x0e,0x0f,0x03,0x01 }; static const uint8_t mxf_system_item_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x03,0x01,0x04 }; static const uint8_t mxf_klv_key[] = { 0x06,0x0e,0x2b,0x34 }; /* complete keys to match */ static const uint8_t mxf_crypto_source_container_ul[] = { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0x09,0x06,0x01,0x01,0x02,0x02,0x00,0x00,0x00 }; static const uint8_t mxf_encrypted_triplet_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x04,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x7e,0x01,0x00 }; static const uint8_t mxf_encrypted_essence_container[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0b,0x01,0x00 }; static const uint8_t mxf_random_index_pack_key[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x11,0x01,0x00 }; static const uint8_t mxf_sony_mpeg4_extradata[] = { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0e,0x06,0x06,0x02,0x02,0x01,0x00,0x00 }; static const uint8_t mxf_avid_project_name[] = { 0xa5,0xfb,0x7b,0x25,0xf6,0x15,0x94,0xb9,0x62,0xfc,0x37,0x17,0x49,0x2d,0x42,0xbf }; static const uint8_t mxf_jp2k_rsiz[] = { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }; static const uint8_t mxf_indirect_value_utf16le[] = { 0x4c,0x00,0x02,0x10,0x01,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 }; static const uint8_t mxf_indirect_value_utf16be[] = { 0x42,0x01,0x10,0x02,0x00,0x00,0x00,0x00,0x00,0x06,0x0e,0x2b,0x34,0x01,0x04,0x01,0x01 }; #define IS_KLV_KEY(x, y) (!memcmp(x, y, sizeof(y))) static void mxf_free_metadataset(MXFMetadataSet **ctx, int freectx) { MXFIndexTableSegment *seg; switch ((*ctx)->type) { case Descriptor: av_freep(&((MXFDescriptor *)*ctx)->extradata); break; case MultipleDescriptor: av_freep(&((MXFDescriptor *)*ctx)->sub_descriptors_refs); break; case Sequence: av_freep(&((MXFSequence *)*ctx)->structural_components_refs); break; case EssenceGroup: av_freep(&((MXFEssenceGroup *)*ctx)->structural_components_refs); break; case SourcePackage: case MaterialPackage: av_freep(&((MXFPackage *)*ctx)->tracks_refs); av_freep(&((MXFPackage *)*ctx)->name); av_freep(&((MXFPackage *)*ctx)->comment_refs); break; case TaggedValue: av_freep(&((MXFTaggedValue *)*ctx)->name); av_freep(&((MXFTaggedValue *)*ctx)->value); break; case Track: av_freep(&((MXFTrack *)*ctx)->name); break; case IndexTableSegment: seg = (MXFIndexTableSegment *)*ctx; av_freep(&seg->temporal_offset_entries); av_freep(&seg->flag_entries); av_freep(&seg->stream_offset_entries); default: break; } if (freectx) av_freep(ctx); } static int64_t klv_decode_ber_length(AVIOContext *pb) { uint64_t size = avio_r8(pb); if (size & 0x80) { /* long form */ int bytes_num = size & 0x7f; /* SMPTE 379M 5.3.4 guarantee that bytes_num must not exceed 8 bytes */ if (bytes_num > 8) return AVERROR_INVALIDDATA; size = 0; while (bytes_num--) size = size << 8 | avio_r8(pb); } return size; } static int mxf_read_sync(AVIOContext *pb, const uint8_t *key, unsigned size) { int i, b; for (i = 0; i < size && !avio_feof(pb); i++) { b = avio_r8(pb); if (b == key[0]) i = 0; else if (b != key[i]) i = -1; } return i == size; } static int klv_read_packet(KLVPacket *klv, AVIOContext *pb) { if (!mxf_read_sync(pb, mxf_klv_key, 4)) return AVERROR_INVALIDDATA; klv->offset = avio_tell(pb) - 4; memcpy(klv->key, mxf_klv_key, 4); avio_read(pb, klv->key + 4, 12); klv->length = klv_decode_ber_length(pb); return klv->length == -1 ? -1 : 0; } static int mxf_get_stream_index(AVFormatContext *s, KLVPacket *klv) { int i; for (i = 0; i < s->nb_streams; i++) { MXFTrack *track = s->streams[i]->priv_data; /* SMPTE 379M 7.3 */ if (track && !memcmp(klv->key + sizeof(mxf_essence_element_key), track->track_number, sizeof(track->track_number))) return i; } /* return 0 if only one stream, for OP Atom files with 0 as track number */ return s->nb_streams == 1 ? 0 : -1; } /* XXX: use AVBitStreamFilter */ static int mxf_get_d10_aes3_packet(AVIOContext *pb, AVStream *st, AVPacket *pkt, int64_t length) { const uint8_t *buf_ptr, *end_ptr; uint8_t *data_ptr; int i; if (length > 61444) /* worst case PAL 1920 samples 8 channels */ return AVERROR_INVALIDDATA; length = av_get_packet(pb, pkt, length); if (length < 0) return length; data_ptr = pkt->data; end_ptr = pkt->data + length; buf_ptr = pkt->data + 4; /* skip SMPTE 331M header */ for (; end_ptr - buf_ptr >= st->codecpar->channels * 4; ) { for (i = 0; i < st->codecpar->channels; i++) { uint32_t sample = bytestream_get_le32(&buf_ptr); if (st->codecpar->bits_per_coded_sample == 24) bytestream_put_le24(&data_ptr, (sample >> 4) & 0xffffff); else bytestream_put_le16(&data_ptr, (sample >> 12) & 0xffff); } buf_ptr += 32 - st->codecpar->channels*4; // always 8 channels stored SMPTE 331M } av_shrink_packet(pkt, data_ptr - pkt->data); return 0; } static int mxf_decrypt_triplet(AVFormatContext *s, AVPacket *pkt, KLVPacket *klv) { static const uint8_t checkv[16] = {0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b, 0x43, 0x48, 0x55, 0x4b}; MXFContext *mxf = s->priv_data; AVIOContext *pb = s->pb; int64_t end = avio_tell(pb) + klv->length; int64_t size; uint64_t orig_size; uint64_t plaintext_size; uint8_t ivec[16]; uint8_t tmpbuf[16]; int index; if (!mxf->aesc && s->key && s->keylen == 16) { mxf->aesc = av_aes_alloc(); if (!mxf->aesc) return AVERROR(ENOMEM); av_aes_init(mxf->aesc, s->key, 128, 1); } // crypto context avio_skip(pb, klv_decode_ber_length(pb)); // plaintext offset klv_decode_ber_length(pb); plaintext_size = avio_rb64(pb); // source klv key klv_decode_ber_length(pb); avio_read(pb, klv->key, 16); if (!IS_KLV_KEY(klv, mxf_essence_element_key)) return AVERROR_INVALIDDATA; index = mxf_get_stream_index(s, klv); if (index < 0) return AVERROR_INVALIDDATA; // source size klv_decode_ber_length(pb); orig_size = avio_rb64(pb); if (orig_size < plaintext_size) return AVERROR_INVALIDDATA; // enc. code size = klv_decode_ber_length(pb); if (size < 32 || size - 32 < orig_size) return AVERROR_INVALIDDATA; avio_read(pb, ivec, 16); avio_read(pb, tmpbuf, 16); if (mxf->aesc) av_aes_crypt(mxf->aesc, tmpbuf, tmpbuf, 1, ivec, 1); if (memcmp(tmpbuf, checkv, 16)) av_log(s, AV_LOG_ERROR, "probably incorrect decryption key\n"); size -= 32; size = av_get_packet(pb, pkt, size); if (size < 0) return size; else if (size < plaintext_size) return AVERROR_INVALIDDATA; size -= plaintext_size; if (mxf->aesc) av_aes_crypt(mxf->aesc, &pkt->data[plaintext_size], &pkt->data[plaintext_size], size >> 4, ivec, 1); av_shrink_packet(pkt, orig_size); pkt->stream_index = index; avio_skip(pb, end - avio_tell(pb)); return 0; } static int mxf_read_primer_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; int item_num = avio_rb32(pb); int item_len = avio_rb32(pb); if (item_len != 18) { avpriv_request_sample(pb, "Primer pack item length %d", item_len); return AVERROR_PATCHWELCOME; } if (item_num > 65536) { av_log(mxf->fc, AV_LOG_ERROR, "item_num %d is too large\n", item_num); return AVERROR_INVALIDDATA; } if (mxf->local_tags) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple primer packs\n"); av_free(mxf->local_tags); mxf->local_tags_count = 0; mxf->local_tags = av_calloc(item_num, item_len); if (!mxf->local_tags) return AVERROR(ENOMEM); mxf->local_tags_count = item_num; avio_read(pb, mxf->local_tags, item_num*item_len); return 0; } static int mxf_read_partition_pack(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; MXFPartition *partition, *tmp_part; UID op; uint64_t footer_partition; uint32_t nb_essence_containers; tmp_part = av_realloc_array(mxf->partitions, mxf->partitions_count + 1, sizeof(*mxf->partitions)); if (!tmp_part) return AVERROR(ENOMEM); mxf->partitions = tmp_part; if (mxf->parsing_backward) { /* insert the new partition pack in the middle * this makes the entries in mxf->partitions sorted by offset */ memmove(&mxf->partitions[mxf->last_forward_partition+1], &mxf->partitions[mxf->last_forward_partition], (mxf->partitions_count - mxf->last_forward_partition)*sizeof(*mxf->partitions)); partition = mxf->current_partition = &mxf->partitions[mxf->last_forward_partition]; } else { mxf->last_forward_partition++; partition = mxf->current_partition = &mxf->partitions[mxf->partitions_count]; } memset(partition, 0, sizeof(*partition)); mxf->partitions_count++; partition->pack_length = avio_tell(pb) - klv_offset + size; partition->pack_ofs = klv_offset; switch(uid[13]) { case 2: partition->type = Header; break; case 3: partition->type = BodyPartition; break; case 4: partition->type = Footer; break; default: av_log(mxf->fc, AV_LOG_ERROR, "unknown partition type %i\n", uid[13]); return AVERROR_INVALIDDATA; } /* consider both footers to be closed (there is only Footer and CompleteFooter) */ partition->closed = partition->type == Footer || !(uid[14] & 1); partition->complete = uid[14] > 2; avio_skip(pb, 4); partition->kag_size = avio_rb32(pb); partition->this_partition = avio_rb64(pb); partition->previous_partition = avio_rb64(pb); footer_partition = avio_rb64(pb); partition->header_byte_count = avio_rb64(pb); partition->index_byte_count = avio_rb64(pb); partition->index_sid = avio_rb32(pb); avio_skip(pb, 8); partition->body_sid = avio_rb32(pb); if (avio_read(pb, op, sizeof(UID)) != sizeof(UID)) { av_log(mxf->fc, AV_LOG_ERROR, "Failed reading UID\n"); return AVERROR_INVALIDDATA; } nb_essence_containers = avio_rb32(pb); if (partition->this_partition && partition->previous_partition == partition->this_partition) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition equal to ThisPartition %"PRIx64"\n", partition->previous_partition); /* override with the actual previous partition offset */ if (!mxf->parsing_backward && mxf->last_forward_partition > 1) { MXFPartition *prev = mxf->partitions + mxf->last_forward_partition - 2; partition->previous_partition = prev->this_partition; } /* if no previous body partition are found point to the header * partition */ if (partition->previous_partition == partition->this_partition) partition->previous_partition = 0; av_log(mxf->fc, AV_LOG_ERROR, "Overriding PreviousPartition with %"PRIx64"\n", partition->previous_partition); } /* some files don't have FooterPartition set in every partition */ if (footer_partition) { if (mxf->footer_partition && mxf->footer_partition != footer_partition) { av_log(mxf->fc, AV_LOG_ERROR, "inconsistent FooterPartition value: %"PRIu64" != %"PRIu64"\n", mxf->footer_partition, footer_partition); } else { mxf->footer_partition = footer_partition; } } av_log(mxf->fc, AV_LOG_TRACE, "PartitionPack: ThisPartition = 0x%"PRIX64 ", PreviousPartition = 0x%"PRIX64", " "FooterPartition = 0x%"PRIX64", IndexSID = %i, BodySID = %i\n", partition->this_partition, partition->previous_partition, footer_partition, partition->index_sid, partition->body_sid); /* sanity check PreviousPartition if set */ //NOTE: this isn't actually enough, see mxf_seek_to_previous_partition() if (partition->previous_partition && mxf->run_in + partition->previous_partition >= klv_offset) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition points to this partition or forward\n"); return AVERROR_INVALIDDATA; } if (op[12] == 1 && op[13] == 1) mxf->op = OP1a; else if (op[12] == 1 && op[13] == 2) mxf->op = OP1b; else if (op[12] == 1 && op[13] == 3) mxf->op = OP1c; else if (op[12] == 2 && op[13] == 1) mxf->op = OP2a; else if (op[12] == 2 && op[13] == 2) mxf->op = OP2b; else if (op[12] == 2 && op[13] == 3) mxf->op = OP2c; else if (op[12] == 3 && op[13] == 1) mxf->op = OP3a; else if (op[12] == 3 && op[13] == 2) mxf->op = OP3b; else if (op[12] == 3 && op[13] == 3) mxf->op = OP3c; else if (op[12] == 64&& op[13] == 1) mxf->op = OPSONYOpt; else if (op[12] == 0x10) { /* SMPTE 390m: "There shall be exactly one essence container" * The following block deals with files that violate this, namely: * 2011_DCPTEST_24FPS.V.mxf - two ECs, OP1a * abcdefghiv016f56415e.mxf - zero ECs, OPAtom, output by Avid AirSpeed */ if (nb_essence_containers != 1) { MXFOP op = nb_essence_containers ? OP1a : OPAtom; /* only nag once */ if (!mxf->op) av_log(mxf->fc, AV_LOG_WARNING, "\"OPAtom\" with %"PRIu32" ECs - assuming %s\n", nb_essence_containers, op == OP1a ? "OP1a" : "OPAtom"); mxf->op = op; } else mxf->op = OPAtom; } else { av_log(mxf->fc, AV_LOG_ERROR, "unknown operational pattern: %02xh %02xh - guessing OP1a\n", op[12], op[13]); mxf->op = OP1a; } if (partition->kag_size <= 0 || partition->kag_size > (1 << 20)) { av_log(mxf->fc, AV_LOG_WARNING, "invalid KAGSize %"PRId32" - guessing ", partition->kag_size); if (mxf->op == OPSONYOpt) partition->kag_size = 512; else partition->kag_size = 1; av_log(mxf->fc, AV_LOG_WARNING, "%"PRId32"\n", partition->kag_size); } return 0; } static int mxf_add_metadata_set(MXFContext *mxf, void *metadata_set) { MXFMetadataSet **tmp; tmp = av_realloc_array(mxf->metadata_sets, mxf->metadata_sets_count + 1, sizeof(*mxf->metadata_sets)); if (!tmp) return AVERROR(ENOMEM); mxf->metadata_sets = tmp; mxf->metadata_sets[mxf->metadata_sets_count] = metadata_set; mxf->metadata_sets_count++; return 0; } static int mxf_read_cryptographic_context(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFCryptoContext *cryptocontext = arg; if (size != 16) return AVERROR_INVALIDDATA; if (IS_KLV_KEY(uid, mxf_crypto_source_container_ul)) avio_read(pb, cryptocontext->source_container_ul, 16); return 0; } static int mxf_read_strong_ref_array(AVIOContext *pb, UID **refs, int *count) { *count = avio_rb32(pb); *refs = av_calloc(*count, sizeof(UID)); if (!*refs) { *count = 0; return AVERROR(ENOMEM); } avio_skip(pb, 4); /* useless size of objects, always 16 according to specs */ avio_read(pb, (uint8_t *)*refs, *count * sizeof(UID)); return 0; } static inline int mxf_read_utf16_string(AVIOContext *pb, int size, char** str, int be) { int ret; size_t buf_size; if (size < 0 || size > INT_MAX/2) return AVERROR(EINVAL); buf_size = size + size / 2 + 1; *str = av_malloc(buf_size); if (!*str) return AVERROR(ENOMEM); if (be) ret = avio_get_str16be(pb, size, *str, buf_size); else ret = avio_get_str16le(pb, size, *str, buf_size); if (ret < 0) { av_freep(str); return ret; } return ret; } #define READ_STR16(type, big_endian) \ static int mxf_read_utf16 ## type ##_string(AVIOContext *pb, int size, char** str) \ { \ return mxf_read_utf16_string(pb, size, str, big_endian); \ } READ_STR16(be, 1) READ_STR16(le, 0) #undef READ_STR16 static int mxf_read_content_storage(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; switch (tag) { case 0x1901: if (mxf->packages_refs) av_log(mxf->fc, AV_LOG_VERBOSE, "Multiple packages_refs\n"); av_free(mxf->packages_refs); return mxf_read_strong_ref_array(pb, &mxf->packages_refs, &mxf->packages_count); } return 0; } static int mxf_read_source_clip(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFStructuralComponent *source_clip = arg; switch(tag) { case 0x0202: source_clip->duration = avio_rb64(pb); break; case 0x1201: source_clip->start_position = avio_rb64(pb); break; case 0x1101: /* UMID, only get last 16 bytes */ avio_read(pb, source_clip->source_package_ul, 16); avio_read(pb, source_clip->source_package_uid, 16); break; case 0x1102: source_clip->source_track_id = avio_rb32(pb); break; } return 0; } static int mxf_read_timecode_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFTimecodeComponent *mxf_timecode = arg; switch(tag) { case 0x1501: mxf_timecode->start_frame = avio_rb64(pb); break; case 0x1502: mxf_timecode->rate = (AVRational){avio_rb16(pb), 1}; break; case 0x1503: mxf_timecode->drop_frame = avio_r8(pb); break; } return 0; } static int mxf_read_pulldown_component(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFPulldownComponent *mxf_pulldown = arg; switch(tag) { case 0x0d01: avio_read(pb, mxf_pulldown->input_segment_ref, 16); break; } return 0; } static int mxf_read_track(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFTrack *track = arg; switch(tag) { case 0x4801: track->track_id = avio_rb32(pb); break; case 0x4804: avio_read(pb, track->track_number, 4); break; case 0x4802: mxf_read_utf16be_string(pb, size, &track->name); break; case 0x4b01: track->edit_rate.num = avio_rb32(pb); track->edit_rate.den = avio_rb32(pb); break; case 0x4803: avio_read(pb, track->sequence_ref, 16); break; } return 0; } static int mxf_read_sequence(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFSequence *sequence = arg; switch(tag) { case 0x0202: sequence->duration = avio_rb64(pb); break; case 0x0201: avio_read(pb, sequence->data_definition_ul, 16); break; case 0x4b02: sequence->origin = avio_r8(pb); break; case 0x1001: return mxf_read_strong_ref_array(pb, &sequence->structural_components_refs, &sequence->structural_components_count); } return 0; } static int mxf_read_essence_group(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFEssenceGroup *essence_group = arg; switch (tag) { case 0x0202: essence_group->duration = avio_rb64(pb); break; case 0x0501: return mxf_read_strong_ref_array(pb, &essence_group->structural_components_refs, &essence_group->structural_components_count); } return 0; } static int mxf_read_package(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFPackage *package = arg; switch(tag) { case 0x4403: return mxf_read_strong_ref_array(pb, &package->tracks_refs, &package->tracks_count); case 0x4401: /* UMID */ avio_read(pb, package->package_ul, 16); avio_read(pb, package->package_uid, 16); break; case 0x4701: avio_read(pb, package->descriptor_ref, 16); break; case 0x4402: return mxf_read_utf16be_string(pb, size, &package->name); case 0x4406: return mxf_read_strong_ref_array(pb, &package->comment_refs, &package->comment_count); } return 0; } static int mxf_read_index_entry_array(AVIOContext *pb, MXFIndexTableSegment *segment) { int i, length; segment->nb_index_entries = avio_rb32(pb); length = avio_rb32(pb); if(segment->nb_index_entries && length < 11) return AVERROR_INVALIDDATA; if (!(segment->temporal_offset_entries=av_calloc(segment->nb_index_entries, sizeof(*segment->temporal_offset_entries))) || !(segment->flag_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->flag_entries))) || !(segment->stream_offset_entries = av_calloc(segment->nb_index_entries, sizeof(*segment->stream_offset_entries)))) { av_freep(&segment->temporal_offset_entries); av_freep(&segment->flag_entries); return AVERROR(ENOMEM); } for (i = 0; i < segment->nb_index_entries; i++) { if(avio_feof(pb)) return AVERROR_INVALIDDATA; segment->temporal_offset_entries[i] = avio_r8(pb); avio_r8(pb); /* KeyFrameOffset */ segment->flag_entries[i] = avio_r8(pb); segment->stream_offset_entries[i] = avio_rb64(pb); avio_skip(pb, length - 11); } return 0; } static int mxf_read_index_table_segment(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFIndexTableSegment *segment = arg; switch(tag) { case 0x3F05: segment->edit_unit_byte_count = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "EditUnitByteCount %d\n", segment->edit_unit_byte_count); break; case 0x3F06: segment->index_sid = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "IndexSID %d\n", segment->index_sid); break; case 0x3F07: segment->body_sid = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "BodySID %d\n", segment->body_sid); break; case 0x3F0A: av_log(NULL, AV_LOG_TRACE, "IndexEntryArray found\n"); return mxf_read_index_entry_array(pb, segment); case 0x3F0B: segment->index_edit_rate.num = avio_rb32(pb); segment->index_edit_rate.den = avio_rb32(pb); av_log(NULL, AV_LOG_TRACE, "IndexEditRate %d/%d\n", segment->index_edit_rate.num, segment->index_edit_rate.den); break; case 0x3F0C: segment->index_start_position = avio_rb64(pb); av_log(NULL, AV_LOG_TRACE, "IndexStartPosition %"PRId64"\n", segment->index_start_position); break; case 0x3F0D: segment->index_duration = avio_rb64(pb); av_log(NULL, AV_LOG_TRACE, "IndexDuration %"PRId64"\n", segment->index_duration); break; } return 0; } static void mxf_read_pixel_layout(AVIOContext *pb, MXFDescriptor *descriptor) { int code, value, ofs = 0; char layout[16] = {0}; /* not for printing, may end up not terminated on purpose */ do { code = avio_r8(pb); value = avio_r8(pb); av_log(NULL, AV_LOG_TRACE, "pixel layout: code %#x\n", code); if (ofs <= 14) { layout[ofs++] = code; layout[ofs++] = value; } else break; /* don't read byte by byte on sneaky files filled with lots of non-zeroes */ } while (code != 0); /* SMPTE 377M E.2.46 */ ff_mxf_decode_pixel_layout(layout, &descriptor->pix_fmt); } static int mxf_read_generic_descriptor(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFDescriptor *descriptor = arg; int entry_count, entry_size; switch(tag) { case 0x3F01: return mxf_read_strong_ref_array(pb, &descriptor->sub_descriptors_refs, &descriptor->sub_descriptors_count); case 0x3002: /* ContainerDuration */ descriptor->duration = avio_rb64(pb); break; case 0x3004: avio_read(pb, descriptor->essence_container_ul, 16); break; case 0x3005: avio_read(pb, descriptor->codec_ul, 16); break; case 0x3006: descriptor->linked_track_id = avio_rb32(pb); break; case 0x3201: /* PictureEssenceCoding */ avio_read(pb, descriptor->essence_codec_ul, 16); break; case 0x3203: descriptor->width = avio_rb32(pb); break; case 0x3202: descriptor->height = avio_rb32(pb); break; case 0x320C: descriptor->frame_layout = avio_r8(pb); break; case 0x320D: entry_count = avio_rb32(pb); entry_size = avio_rb32(pb); if (entry_size == 4) { if (entry_count > 0) descriptor->video_line_map[0] = avio_rb32(pb); else descriptor->video_line_map[0] = 0; if (entry_count > 1) descriptor->video_line_map[1] = avio_rb32(pb); else descriptor->video_line_map[1] = 0; } else av_log(NULL, AV_LOG_WARNING, "VideoLineMap element size %d currently not supported\n", entry_size); break; case 0x320E: descriptor->aspect_ratio.num = avio_rb32(pb); descriptor->aspect_ratio.den = avio_rb32(pb); break; case 0x3212: descriptor->field_dominance = avio_r8(pb); break; case 0x3301: descriptor->component_depth = avio_rb32(pb); break; case 0x3302: descriptor->horiz_subsampling = avio_rb32(pb); break; case 0x3308: descriptor->vert_subsampling = avio_rb32(pb); break; case 0x3D03: descriptor->sample_rate.num = avio_rb32(pb); descriptor->sample_rate.den = avio_rb32(pb); break; case 0x3D06: /* SoundEssenceCompression */ avio_read(pb, descriptor->essence_codec_ul, 16); break; case 0x3D07: descriptor->channels = avio_rb32(pb); break; case 0x3D01: descriptor->bits_per_sample = avio_rb32(pb); break; case 0x3401: mxf_read_pixel_layout(pb, descriptor); break; default: /* Private uid used by SONY C0023S01.mxf */ if (IS_KLV_KEY(uid, mxf_sony_mpeg4_extradata)) { if (descriptor->extradata) av_log(NULL, AV_LOG_WARNING, "Duplicate sony_mpeg4_extradata\n"); av_free(descriptor->extradata); descriptor->extradata_size = 0; descriptor->extradata = av_malloc(size); if (!descriptor->extradata) return AVERROR(ENOMEM); descriptor->extradata_size = size; avio_read(pb, descriptor->extradata, size); } if (IS_KLV_KEY(uid, mxf_jp2k_rsiz)) { uint32_t rsiz = avio_rb16(pb); if (rsiz == FF_PROFILE_JPEG2000_DCINEMA_2K || rsiz == FF_PROFILE_JPEG2000_DCINEMA_4K) descriptor->pix_fmt = AV_PIX_FMT_XYZ12; } break; } return 0; } static int mxf_read_indirect_value(void *arg, AVIOContext *pb, int size) { MXFTaggedValue *tagged_value = arg; uint8_t key[17]; if (size <= 17) return 0; avio_read(pb, key, 17); /* TODO: handle other types of of indirect values */ if (memcmp(key, mxf_indirect_value_utf16le, 17) == 0) { return mxf_read_utf16le_string(pb, size - 17, &tagged_value->value); } else if (memcmp(key, mxf_indirect_value_utf16be, 17) == 0) { return mxf_read_utf16be_string(pb, size - 17, &tagged_value->value); } return 0; } static int mxf_read_tagged_value(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFTaggedValue *tagged_value = arg; switch (tag){ case 0x5001: return mxf_read_utf16be_string(pb, size, &tagged_value->name); case 0x5003: return mxf_read_indirect_value(tagged_value, pb, size); } return 0; } /* * Match an uid independently of the version byte and up to len common bytes * Returns: boolean */ static int mxf_match_uid(const UID key, const UID uid, int len) { int i; for (i = 0; i < len; i++) { if (i != 7 && key[i] != uid[i]) return 0; } return 1; } static const MXFCodecUL *mxf_get_codec_ul(const MXFCodecUL *uls, UID *uid) { while (uls->uid[0]) { if(mxf_match_uid(uls->uid, *uid, uls->matching_len)) break; uls++; } return uls; } static void *mxf_resolve_strong_ref(MXFContext *mxf, UID *strong_ref, enum MXFMetadataSetType type) { int i; if (!strong_ref) return NULL; for (i = 0; i < mxf->metadata_sets_count; i++) { if (!memcmp(*strong_ref, mxf->metadata_sets[i]->uid, 16) && (type == AnyType || mxf->metadata_sets[i]->type == type)) { return mxf->metadata_sets[i]; } } return NULL; } static const MXFCodecUL mxf_picture_essence_container_uls[] = { // video essence container uls { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x0d,0x01,0x03,0x01,0x02,0x0c,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x10,0x60,0x01 }, 14, AV_CODEC_ID_H264 }, /* H.264 frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x12,0x01,0x00 }, 14, AV_CODEC_ID_VC1 }, /* VC-1 frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x60,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MPEG-ES frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x04,0x01 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* Type D-10 mapping of 40Mbps 525/60-I */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x02,0x41,0x01 }, 14, AV_CODEC_ID_DVVIDEO }, /* DV 625 25mbps */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x05,0x00,0x00 }, 14, AV_CODEC_ID_RAWVIDEO }, /* uncompressed picture */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x01,0x01 }, 15, AV_CODEC_ID_HQ_HQA }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0a,0x0e,0x0f,0x03,0x01,0x02,0x20,0x02,0x01 }, 15, AV_CODEC_ID_HQX }, { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4f }, 14, AV_CODEC_ID_RAWVIDEO }, /* Legacy ?? Uncompressed Picture */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; /* EC ULs for intra-only formats */ static const MXFCodecUL mxf_intra_only_essence_container_uls[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x00,0x00 }, 14, AV_CODEC_ID_MPEG2VIDEO }, /* MXF-GC SMPTE D-10 mappings */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; /* intra-only PictureEssenceCoding ULs, where no corresponding EC UL exists */ static const MXFCodecUL mxf_intra_only_picture_essence_coding_uls[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x00,0x00 }, 14, AV_CODEC_ID_H264 }, /* H.264/MPEG-4 AVC Intra Profiles */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x07,0x04,0x01,0x02,0x02,0x03,0x01,0x01,0x00 }, 14, AV_CODEC_ID_JPEG2000 }, /* JPEG 2000 code stream */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; /* actual coded width for AVC-Intra to allow selecting correct SPS/PPS */ static const MXFCodecUL mxf_intra_only_picture_coded_width[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x01 }, 16, 1440 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x02 }, 16, 1440 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x03 }, 16, 1440 }, { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x0A,0x04,0x01,0x02,0x02,0x01,0x32,0x21,0x04 }, 16, 1440 }, { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, 0 }, }; static const MXFCodecUL mxf_sound_essence_container_uls[] = { // sound essence container uls { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x06,0x01,0x00 }, 14, AV_CODEC_ID_PCM_S16LE }, /* BWF Frame wrapped */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x02,0x0d,0x01,0x03,0x01,0x02,0x04,0x40,0x01 }, 14, AV_CODEC_ID_MP2 }, /* MPEG-ES Frame wrapped, 0x40 ??? stream id */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x01,0x0d,0x01,0x03,0x01,0x02,0x01,0x01,0x01 }, 14, AV_CODEC_ID_PCM_S16LE }, /* D-10 Mapping 50Mbps PAL Extended Template */ { { 0x06,0x0e,0x2b,0x34,0x01,0x01,0x01,0xff,0x4b,0x46,0x41,0x41,0x00,0x0d,0x4d,0x4F }, 14, AV_CODEC_ID_PCM_S16LE }, /* 0001GL00.MXF.A1.mxf_opatom.mxf */ { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x03,0x04,0x02,0x02,0x02,0x03,0x03,0x01,0x00 }, 14, AV_CODEC_ID_AAC }, /* MPEG-2 AAC ADTS (legacy) */ { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; static const MXFCodecUL mxf_data_essence_container_uls[] = { { { 0x06,0x0e,0x2b,0x34,0x04,0x01,0x01,0x09,0x0d,0x01,0x03,0x01,0x02,0x0e,0x00,0x00 }, 16, 0 }, { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, 0, AV_CODEC_ID_NONE }, }; static const char* const mxf_data_essence_descriptor[] = { "vbi_vanc_smpte_436M", }; static int mxf_get_sorted_table_segments(MXFContext *mxf, int *nb_sorted_segments, MXFIndexTableSegment ***sorted_segments) { int i, j, nb_segments = 0; MXFIndexTableSegment **unsorted_segments; int last_body_sid = -1, last_index_sid = -1, last_index_start = -1; /* count number of segments, allocate arrays and copy unsorted segments */ for (i = 0; i < mxf->metadata_sets_count; i++) if (mxf->metadata_sets[i]->type == IndexTableSegment) nb_segments++; if (!nb_segments) return AVERROR_INVALIDDATA; if (!(unsorted_segments = av_calloc(nb_segments, sizeof(*unsorted_segments))) || !(*sorted_segments = av_calloc(nb_segments, sizeof(**sorted_segments)))) { av_freep(sorted_segments); av_free(unsorted_segments); return AVERROR(ENOMEM); } for (i = j = 0; i < mxf->metadata_sets_count; i++) if (mxf->metadata_sets[i]->type == IndexTableSegment) unsorted_segments[j++] = (MXFIndexTableSegment*)mxf->metadata_sets[i]; *nb_sorted_segments = 0; /* sort segments by {BodySID, IndexSID, IndexStartPosition}, remove duplicates while we're at it */ for (i = 0; i < nb_segments; i++) { int best = -1, best_body_sid = -1, best_index_sid = -1, best_index_start = -1; uint64_t best_index_duration = 0; for (j = 0; j < nb_segments; j++) { MXFIndexTableSegment *s = unsorted_segments[j]; /* Require larger BosySID, IndexSID or IndexStartPosition then the previous entry. This removes duplicates. * We want the smallest values for the keys than what we currently have, unless this is the first such entry this time around. * If we come across an entry with the same IndexStartPosition but larger IndexDuration, then we'll prefer it over the one we currently have. */ if ((i == 0 || s->body_sid > last_body_sid || s->index_sid > last_index_sid || s->index_start_position > last_index_start) && (best == -1 || s->body_sid < best_body_sid || s->index_sid < best_index_sid || s->index_start_position < best_index_start || (s->index_start_position == best_index_start && s->index_duration > best_index_duration))) { best = j; best_body_sid = s->body_sid; best_index_sid = s->index_sid; best_index_start = s->index_start_position; best_index_duration = s->index_duration; } } /* no suitable entry found -> we're done */ if (best == -1) break; (*sorted_segments)[(*nb_sorted_segments)++] = unsorted_segments[best]; last_body_sid = best_body_sid; last_index_sid = best_index_sid; last_index_start = best_index_start; } av_free(unsorted_segments); return 0; } /** * Computes the absolute file offset of the given essence container offset */ static int mxf_absolute_bodysid_offset(MXFContext *mxf, int body_sid, int64_t offset, int64_t *offset_out) { int x; int64_t offset_in = offset; /* for logging */ for (x = 0; x < mxf->partitions_count; x++) { MXFPartition *p = &mxf->partitions[x]; if (p->body_sid != body_sid) continue; if (offset < p->essence_length || !p->essence_length) { *offset_out = p->essence_offset + offset; return 0; } offset -= p->essence_length; } av_log(mxf->fc, AV_LOG_ERROR, "failed to find absolute offset of %"PRIX64" in BodySID %i - partial file?\n", offset_in, body_sid); return AVERROR_INVALIDDATA; } /** * Returns the end position of the essence container with given BodySID, or zero if unknown */ static int64_t mxf_essence_container_end(MXFContext *mxf, int body_sid) { int x; int64_t ret = 0; for (x = 0; x < mxf->partitions_count; x++) { MXFPartition *p = &mxf->partitions[x]; if (p->body_sid != body_sid) continue; if (!p->essence_length) return 0; ret = p->essence_offset + p->essence_length; } return ret; } /* EditUnit -> absolute offset */ static int mxf_edit_unit_absolute_offset(MXFContext *mxf, MXFIndexTable *index_table, int64_t edit_unit, int64_t *edit_unit_out, int64_t *offset_out, int nag) { int i; int64_t offset_temp = 0; for (i = 0; i < index_table->nb_segments; i++) { MXFIndexTableSegment *s = index_table->segments[i]; edit_unit = FFMAX(edit_unit, s->index_start_position); /* clamp if trying to seek before start */ if (edit_unit < s->index_start_position + s->index_duration) { int64_t index = edit_unit - s->index_start_position; if (s->edit_unit_byte_count) offset_temp += s->edit_unit_byte_count * index; else if (s->nb_index_entries) { if (s->nb_index_entries == 2 * s->index_duration + 1) index *= 2; /* Avid index */ if (index < 0 || index >= s->nb_index_entries) { av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" IndexEntryArray too small\n", index_table->index_sid, s->index_start_position); return AVERROR_INVALIDDATA; } offset_temp = s->stream_offset_entries[index]; } else { av_log(mxf->fc, AV_LOG_ERROR, "IndexSID %i segment at %"PRId64" missing EditUnitByteCount and IndexEntryArray\n", index_table->index_sid, s->index_start_position); return AVERROR_INVALIDDATA; } if (edit_unit_out) *edit_unit_out = edit_unit; return mxf_absolute_bodysid_offset(mxf, index_table->body_sid, offset_temp, offset_out); } else { /* EditUnitByteCount == 0 for VBR indexes, which is fine since they use explicit StreamOffsets */ offset_temp += s->edit_unit_byte_count * s->index_duration; } } if (nag) av_log(mxf->fc, AV_LOG_ERROR, "failed to map EditUnit %"PRId64" in IndexSID %i to an offset\n", edit_unit, index_table->index_sid); return AVERROR_INVALIDDATA; } static int mxf_compute_ptses_fake_index(MXFContext *mxf, MXFIndexTable *index_table) { int i, j, x; int8_t max_temporal_offset = -128; uint8_t *flags; /* first compute how many entries we have */ for (i = 0; i < index_table->nb_segments; i++) { MXFIndexTableSegment *s = index_table->segments[i]; if (!s->nb_index_entries) { index_table->nb_ptses = 0; return 0; /* no TemporalOffsets */ } index_table->nb_ptses += s->index_duration; } /* paranoid check */ if (index_table->nb_ptses <= 0) return 0; if (!(index_table->ptses = av_calloc(index_table->nb_ptses, sizeof(int64_t))) || !(index_table->fake_index = av_calloc(index_table->nb_ptses, sizeof(AVIndexEntry))) || !(index_table->offsets = av_calloc(index_table->nb_ptses, sizeof(int8_t))) || !(flags = av_calloc(index_table->nb_ptses, sizeof(uint8_t)))) { av_freep(&index_table->ptses); av_freep(&index_table->fake_index); av_freep(&index_table->offsets); return AVERROR(ENOMEM); } /* we may have a few bad TemporalOffsets * make sure the corresponding PTSes don't have the bogus value 0 */ for (x = 0; x < index_table->nb_ptses; x++) index_table->ptses[x] = AV_NOPTS_VALUE; /** * We have this: * * x TemporalOffset * 0: 0 * 1: 1 * 2: 1 * 3: -2 * 4: 1 * 5: 1 * 6: -2 * * We want to transform it into this: * * x DTS PTS * 0: -1 0 * 1: 0 3 * 2: 1 1 * 3: 2 2 * 4: 3 6 * 5: 4 4 * 6: 5 5 * * We do this by bucket sorting x by x+TemporalOffset[x] into mxf->ptses, * then settings mxf->first_dts = -max(TemporalOffset[x]). * The latter makes DTS <= PTS. */ for (i = x = 0; i < index_table->nb_segments; i++) { MXFIndexTableSegment *s = index_table->segments[i]; int index_delta = 1; int n = s->nb_index_entries; if (s->nb_index_entries == 2 * s->index_duration + 1) { index_delta = 2; /* Avid index */ /* ignore the last entry - it's the size of the essence container */ n--; } for (j = 0; j < n; j += index_delta, x++) { int offset = s->temporal_offset_entries[j] / index_delta; int index = x + offset; if (x >= index_table->nb_ptses) { av_log(mxf->fc, AV_LOG_ERROR, "x >= nb_ptses - IndexEntryCount %i < IndexDuration %"PRId64"?\n", s->nb_index_entries, s->index_duration); break; } flags[x] = !(s->flag_entries[j] & 0x30) ? AVINDEX_KEYFRAME : 0; if (index < 0 || index >= index_table->nb_ptses) { av_log(mxf->fc, AV_LOG_ERROR, "index entry %i + TemporalOffset %i = %i, which is out of bounds\n", x, offset, index); continue; } index_table->offsets[x] = offset; index_table->ptses[index] = x; max_temporal_offset = FFMAX(max_temporal_offset, offset); } } /* calculate the fake index table in display order */ for (x = 0; x < index_table->nb_ptses; x++) { index_table->fake_index[x].timestamp = x; if (index_table->ptses[x] != AV_NOPTS_VALUE) index_table->fake_index[index_table->ptses[x]].flags = flags[x]; } av_freep(&flags); index_table->first_dts = -max_temporal_offset; return 0; } /** * Sorts and collects index table segments into index tables. * Also computes PTSes if possible. */ static int mxf_compute_index_tables(MXFContext *mxf) { int i, j, k, ret, nb_sorted_segments; MXFIndexTableSegment **sorted_segments = NULL; AVStream *st = NULL; for (i = 0; i < mxf->fc->nb_streams; i++) { if (mxf->fc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA) continue; st = mxf->fc->streams[i]; break; } if ((ret = mxf_get_sorted_table_segments(mxf, &nb_sorted_segments, &sorted_segments)) || nb_sorted_segments <= 0) { av_log(mxf->fc, AV_LOG_WARNING, "broken or empty index\n"); return 0; } /* sanity check and count unique BodySIDs/IndexSIDs */ for (i = 0; i < nb_sorted_segments; i++) { if (i == 0 || sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) mxf->nb_index_tables++; else if (sorted_segments[i-1]->body_sid != sorted_segments[i]->body_sid) { av_log(mxf->fc, AV_LOG_ERROR, "found inconsistent BodySID\n"); ret = AVERROR_INVALIDDATA; goto finish_decoding_index; } } mxf->index_tables = av_mallocz_array(mxf->nb_index_tables, sizeof(*mxf->index_tables)); if (!mxf->index_tables) { av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate index tables\n"); ret = AVERROR(ENOMEM); goto finish_decoding_index; } /* distribute sorted segments to index tables */ for (i = j = 0; i < nb_sorted_segments; i++) { if (i != 0 && sorted_segments[i-1]->index_sid != sorted_segments[i]->index_sid) { /* next IndexSID */ j++; } mxf->index_tables[j].nb_segments++; } for (i = j = 0; j < mxf->nb_index_tables; i += mxf->index_tables[j++].nb_segments) { MXFIndexTable *t = &mxf->index_tables[j]; t->segments = av_mallocz_array(t->nb_segments, sizeof(*t->segments)); if (!t->segments) { av_log(mxf->fc, AV_LOG_ERROR, "failed to allocate IndexTableSegment" " pointer array\n"); ret = AVERROR(ENOMEM); goto finish_decoding_index; } if (sorted_segments[i]->index_start_position) av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i starts at EditUnit %"PRId64" - seeking may not work as expected\n", sorted_segments[i]->index_sid, sorted_segments[i]->index_start_position); memcpy(t->segments, &sorted_segments[i], t->nb_segments * sizeof(MXFIndexTableSegment*)); t->index_sid = sorted_segments[i]->index_sid; t->body_sid = sorted_segments[i]->body_sid; if ((ret = mxf_compute_ptses_fake_index(mxf, t)) < 0) goto finish_decoding_index; /* fix zero IndexDurations */ for (k = 0; k < t->nb_segments; k++) { if (t->segments[k]->index_duration) continue; if (t->nb_segments > 1) av_log(mxf->fc, AV_LOG_WARNING, "IndexSID %i segment %i has zero IndexDuration and there's more than one segment\n", t->index_sid, k); if (!st) { av_log(mxf->fc, AV_LOG_WARNING, "no streams?\n"); break; } /* assume the first stream's duration is reasonable * leave index_duration = 0 on further segments in case we have any (unlikely) */ t->segments[k]->index_duration = st->duration; break; } } ret = 0; finish_decoding_index: av_free(sorted_segments); return ret; } static int mxf_is_intra_only(MXFDescriptor *descriptor) { return mxf_get_codec_ul(mxf_intra_only_essence_container_uls, &descriptor->essence_container_ul)->id != AV_CODEC_ID_NONE || mxf_get_codec_ul(mxf_intra_only_picture_essence_coding_uls, &descriptor->essence_codec_ul)->id != AV_CODEC_ID_NONE; } static int mxf_uid_to_str(UID uid, char **str) { int i; char *p; p = *str = av_mallocz(sizeof(UID) * 2 + 4 + 1); if (!p) return AVERROR(ENOMEM); for (i = 0; i < sizeof(UID); i++) { snprintf(p, 2 + 1, "%.2x", uid[i]); p += 2; if (i == 3 || i == 5 || i == 7 || i == 9) { snprintf(p, 1 + 1, "-"); p++; } } return 0; } static int mxf_umid_to_str(UID ul, UID uid, char **str) { int i; char *p; p = *str = av_mallocz(sizeof(UID) * 4 + 2 + 1); if (!p) return AVERROR(ENOMEM); snprintf(p, 2 + 1, "0x"); p += 2; for (i = 0; i < sizeof(UID); i++) { snprintf(p, 2 + 1, "%.2X", ul[i]); p += 2; } for (i = 0; i < sizeof(UID); i++) { snprintf(p, 2 + 1, "%.2X", uid[i]); p += 2; } return 0; } static int mxf_add_umid_metadata(AVDictionary **pm, const char *key, MXFPackage* package) { char *str; int ret; if (!package) return 0; if ((ret = mxf_umid_to_str(package->package_ul, package->package_uid, &str)) < 0) return ret; av_dict_set(pm, key, str, AV_DICT_DONT_STRDUP_VAL); return 0; } static int mxf_add_timecode_metadata(AVDictionary **pm, const char *key, AVTimecode *tc) { char buf[AV_TIMECODE_STR_SIZE]; av_dict_set(pm, key, av_timecode_make_string(tc, buf, 0), 0); return 0; } static MXFTimecodeComponent* mxf_resolve_timecode_component(MXFContext *mxf, UID *strong_ref) { MXFStructuralComponent *component = NULL; MXFPulldownComponent *pulldown = NULL; component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType); if (!component) return NULL; switch (component->type) { case TimecodeComponent: return (MXFTimecodeComponent*)component; case PulldownComponent: /* timcode component may be located on a pulldown component */ pulldown = (MXFPulldownComponent*)component; return mxf_resolve_strong_ref(mxf, &pulldown->input_segment_ref, TimecodeComponent); default: break; } return NULL; } static MXFPackage* mxf_resolve_source_package(MXFContext *mxf, UID package_uid) { MXFPackage *package = NULL; int i; for (i = 0; i < mxf->packages_count; i++) { package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], SourcePackage); if (!package) continue; if (!memcmp(package->package_uid, package_uid, 16)) return package; } return NULL; } static MXFDescriptor* mxf_resolve_multidescriptor(MXFContext *mxf, MXFDescriptor *descriptor, int track_id) { MXFDescriptor *sub_descriptor = NULL; int i; if (!descriptor) return NULL; if (descriptor->type == MultipleDescriptor) { for (i = 0; i < descriptor->sub_descriptors_count; i++) { sub_descriptor = mxf_resolve_strong_ref(mxf, &descriptor->sub_descriptors_refs[i], Descriptor); if (!sub_descriptor) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve sub descriptor strong ref\n"); continue; } if (sub_descriptor->linked_track_id == track_id) { return sub_descriptor; } } } else if (descriptor->type == Descriptor) return descriptor; return NULL; } static MXFStructuralComponent* mxf_resolve_essence_group_choice(MXFContext *mxf, MXFEssenceGroup *essence_group) { MXFStructuralComponent *component = NULL; MXFPackage *package = NULL; MXFDescriptor *descriptor = NULL; int i; if (!essence_group || !essence_group->structural_components_count) return NULL; /* essence groups contains multiple representations of the same media, this return the first components with a valid Descriptor typically index 0 */ for (i =0; i < essence_group->structural_components_count; i++){ component = mxf_resolve_strong_ref(mxf, &essence_group->structural_components_refs[i], SourceClip); if (!component) continue; if (!(package = mxf_resolve_source_package(mxf, component->source_package_uid))) continue; descriptor = mxf_resolve_strong_ref(mxf, &package->descriptor_ref, Descriptor); if (descriptor) return component; } return NULL; } static MXFStructuralComponent* mxf_resolve_sourceclip(MXFContext *mxf, UID *strong_ref) { MXFStructuralComponent *component = NULL; component = mxf_resolve_strong_ref(mxf, strong_ref, AnyType); if (!component) return NULL; switch (component->type) { case SourceClip: return component; case EssenceGroup: return mxf_resolve_essence_group_choice(mxf, (MXFEssenceGroup*) component); default: break; } return NULL; } static int mxf_parse_package_comments(MXFContext *mxf, AVDictionary **pm, MXFPackage *package) { MXFTaggedValue *tag; int size, i; char *key = NULL; for (i = 0; i < package->comment_count; i++) { tag = mxf_resolve_strong_ref(mxf, &package->comment_refs[i], TaggedValue); if (!tag || !tag->name || !tag->value) continue; size = strlen(tag->name) + 8 + 1; key = av_mallocz(size); if (!key) return AVERROR(ENOMEM); snprintf(key, size, "comment_%s", tag->name); av_dict_set(pm, key, tag->value, AV_DICT_DONT_STRDUP_KEY); } return 0; } static int mxf_parse_physical_source_package(MXFContext *mxf, MXFTrack *source_track, AVStream *st) { MXFPackage *physical_package = NULL; MXFTrack *physical_track = NULL; MXFStructuralComponent *sourceclip = NULL; MXFTimecodeComponent *mxf_tc = NULL; int i, j, k; AVTimecode tc; int flags; int64_t start_position; for (i = 0; i < source_track->sequence->structural_components_count; i++) { sourceclip = mxf_resolve_strong_ref(mxf, &source_track->sequence->structural_components_refs[i], SourceClip); if (!sourceclip) continue; if (!(physical_package = mxf_resolve_source_package(mxf, sourceclip->source_package_uid))) break; mxf_add_umid_metadata(&st->metadata, "reel_umid", physical_package); /* the name of physical source package is name of the reel or tape */ if (physical_package->name && physical_package->name[0]) av_dict_set(&st->metadata, "reel_name", physical_package->name, 0); /* the source timecode is calculated by adding the start_position of the sourceclip from the file source package track * to the start_frame of the timecode component located on one of the tracks of the physical source package. */ for (j = 0; j < physical_package->tracks_count; j++) { if (!(physical_track = mxf_resolve_strong_ref(mxf, &physical_package->tracks_refs[j], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n"); continue; } if (!(physical_track->sequence = mxf_resolve_strong_ref(mxf, &physical_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n"); continue; } if (physical_track->edit_rate.num <= 0 || physical_track->edit_rate.den <= 0) { av_log(mxf->fc, AV_LOG_WARNING, "Invalid edit rate (%d/%d) found on structural" " component #%d, defaulting to 25/1\n", physical_track->edit_rate.num, physical_track->edit_rate.den, i); physical_track->edit_rate = (AVRational){25, 1}; } for (k = 0; k < physical_track->sequence->structural_components_count; k++) { if (!(mxf_tc = mxf_resolve_timecode_component(mxf, &physical_track->sequence->structural_components_refs[k]))) continue; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; /* scale sourceclip start_position to match physical track edit rate */ start_position = av_rescale_q(sourceclip->start_position, physical_track->edit_rate, source_track->edit_rate); if (av_timecode_init(&tc, mxf_tc->rate, flags, start_position + mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&st->metadata, "timecode", &tc); return 0; } } } } return 0; } static int mxf_add_metadata_stream(MXFContext *mxf, MXFTrack *track) { MXFStructuralComponent *component = NULL; const MXFCodecUL *codec_ul = NULL; MXFPackage tmp_package; AVStream *st; int j; for (j = 0; j < track->sequence->structural_components_count; j++) { component = mxf_resolve_sourceclip(mxf, &track->sequence->structural_components_refs[j]); if (!component) continue; break; } if (!component) return 0; st = avformat_new_stream(mxf->fc, NULL); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, "could not allocate metadata stream\n"); return AVERROR(ENOMEM); } st->codecpar->codec_type = AVMEDIA_TYPE_DATA; st->codecpar->codec_id = AV_CODEC_ID_NONE; st->id = track->track_id; memcpy(&tmp_package.package_ul, component->source_package_ul, 16); memcpy(&tmp_package.package_uid, component->source_package_uid, 16); mxf_add_umid_metadata(&st->metadata, "file_package_umid", &tmp_package); if (track->name && track->name[0]) av_dict_set(&st->metadata, "track_name", track->name, 0); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &track->sequence->data_definition_ul); av_dict_set(&st->metadata, "data_type", av_get_media_type_string(codec_ul->id), 0); return 0; } static int mxf_parse_structural_metadata(MXFContext *mxf) { MXFPackage *material_package = NULL; int i, j, k, ret; av_log(mxf->fc, AV_LOG_TRACE, "metadata sets count %d\n", mxf->metadata_sets_count); /* TODO: handle multiple material packages (OP3x) */ for (i = 0; i < mxf->packages_count; i++) { material_package = mxf_resolve_strong_ref(mxf, &mxf->packages_refs[i], MaterialPackage); if (material_package) break; } if (!material_package) { av_log(mxf->fc, AV_LOG_ERROR, "no material package found\n"); return AVERROR_INVALIDDATA; } mxf_add_umid_metadata(&mxf->fc->metadata, "material_package_umid", material_package); if (material_package->name && material_package->name[0]) av_dict_set(&mxf->fc->metadata, "material_package_name", material_package->name, 0); mxf_parse_package_comments(mxf, &mxf->fc->metadata, material_package); for (i = 0; i < material_package->tracks_count; i++) { MXFPackage *source_package = NULL; MXFTrack *material_track = NULL; MXFTrack *source_track = NULL; MXFTrack *temp_track = NULL; MXFDescriptor *descriptor = NULL; MXFStructuralComponent *component = NULL; MXFTimecodeComponent *mxf_tc = NULL; UID *essence_container_ul = NULL; const MXFCodecUL *codec_ul = NULL; const MXFCodecUL *container_ul = NULL; const MXFCodecUL *pix_fmt_ul = NULL; AVStream *st; AVTimecode tc; int flags; if (!(material_track = mxf_resolve_strong_ref(mxf, &material_package->tracks_refs[i], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track strong ref\n"); continue; } if ((component = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, TimecodeComponent))) { mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc); } } if (!(material_track->sequence = mxf_resolve_strong_ref(mxf, &material_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve material track sequence strong ref\n"); continue; } for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_strong_ref(mxf, &material_track->sequence->structural_components_refs[j], TimecodeComponent); if (!component) continue; mxf_tc = (MXFTimecodeComponent*)component; flags = mxf_tc->drop_frame == 1 ? AV_TIMECODE_FLAG_DROPFRAME : 0; if (av_timecode_init(&tc, mxf_tc->rate, flags, mxf_tc->start_frame, mxf->fc) == 0) { mxf_add_timecode_metadata(&mxf->fc->metadata, "timecode", &tc); break; } } /* TODO: handle multiple source clips, only finds first valid source clip */ if(material_track->sequence->structural_components_count > 1) av_log(mxf->fc, AV_LOG_WARNING, "material track %d: has %d components\n", material_track->track_id, material_track->sequence->structural_components_count); for (j = 0; j < material_track->sequence->structural_components_count; j++) { component = mxf_resolve_sourceclip(mxf, &material_track->sequence->structural_components_refs[j]); if (!component) continue; source_package = mxf_resolve_source_package(mxf, component->source_package_uid); if (!source_package) { av_log(mxf->fc, AV_LOG_TRACE, "material track %d: no corresponding source package found\n", material_track->track_id); break; } for (k = 0; k < source_package->tracks_count; k++) { if (!(temp_track = mxf_resolve_strong_ref(mxf, &source_package->tracks_refs[k], Track))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track strong ref\n"); ret = AVERROR_INVALIDDATA; goto fail_and_free; } if (temp_track->track_id == component->source_track_id) { source_track = temp_track; break; } } if (!source_track) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: no corresponding source track found\n", material_track->track_id); break; } if(source_track && component) break; } if (!source_track || !component || !source_package) { if((ret = mxf_add_metadata_stream(mxf, material_track))) goto fail_and_free; continue; } if (!(source_track->sequence = mxf_resolve_strong_ref(mxf, &source_track->sequence_ref, Sequence))) { av_log(mxf->fc, AV_LOG_ERROR, "could not resolve source track sequence strong ref\n"); ret = AVERROR_INVALIDDATA; goto fail_and_free; } /* 0001GL00.MXF.A1.mxf_opatom.mxf has the same SourcePackageID as 0001GL.MXF.V1.mxf_opatom.mxf * This would result in both files appearing to have two streams. Work around this by sanity checking DataDefinition */ if (memcmp(material_track->sequence->data_definition_ul, source_track->sequence->data_definition_ul, 16)) { av_log(mxf->fc, AV_LOG_ERROR, "material track %d: DataDefinition mismatch\n", material_track->track_id); continue; } st = avformat_new_stream(mxf->fc, NULL); if (!st) { av_log(mxf->fc, AV_LOG_ERROR, "could not allocate stream\n"); ret = AVERROR(ENOMEM); goto fail_and_free; } st->id = material_track->track_id; st->priv_data = source_track; source_package->descriptor = mxf_resolve_strong_ref(mxf, &source_package->descriptor_ref, AnyType); descriptor = mxf_resolve_multidescriptor(mxf, source_package->descriptor, source_track->track_id); /* A SourceClip from a EssenceGroup may only be a single frame of essence data. The clips duration is then how many * frames its suppose to repeat for. Descriptor->duration, if present, contains the real duration of the essence data */ if (descriptor && descriptor->duration != AV_NOPTS_VALUE) source_track->original_duration = st->duration = FFMIN(descriptor->duration, component->duration); else source_track->original_duration = st->duration = component->duration; if (st->duration == -1) st->duration = AV_NOPTS_VALUE; st->start_time = component->start_position; if (material_track->edit_rate.num <= 0 || material_track->edit_rate.den <= 0) { av_log(mxf->fc, AV_LOG_WARNING, "Invalid edit rate (%d/%d) found on stream #%d, " "defaulting to 25/1\n", material_track->edit_rate.num, material_track->edit_rate.den, st->index); material_track->edit_rate = (AVRational){25, 1}; } avpriv_set_pts_info(st, 64, material_track->edit_rate.den, material_track->edit_rate.num); /* ensure SourceTrack EditRate == MaterialTrack EditRate since only * the former is accessible via st->priv_data */ source_track->edit_rate = material_track->edit_rate; PRINT_KEY(mxf->fc, "data definition ul", source_track->sequence->data_definition_ul); codec_ul = mxf_get_codec_ul(ff_mxf_data_definition_uls, &source_track->sequence->data_definition_ul); st->codecpar->codec_type = codec_ul->id; if (!descriptor) { av_log(mxf->fc, AV_LOG_INFO, "source track %d: stream %d, no descriptor found\n", source_track->track_id, st->index); continue; } PRINT_KEY(mxf->fc, "essence codec ul", descriptor->essence_codec_ul); PRINT_KEY(mxf->fc, "essence container ul", descriptor->essence_container_ul); essence_container_ul = &descriptor->essence_container_ul; /* HACK: replacing the original key with mxf_encrypted_essence_container * is not allowed according to s429-6, try to find correct information anyway */ if (IS_KLV_KEY(essence_container_ul, mxf_encrypted_essence_container)) { av_log(mxf->fc, AV_LOG_INFO, "broken encrypted mxf file\n"); for (k = 0; k < mxf->metadata_sets_count; k++) { MXFMetadataSet *metadata = mxf->metadata_sets[k]; if (metadata->type == CryptoContext) { essence_container_ul = &((MXFCryptoContext *)metadata)->source_container_ul; break; } } } /* TODO: drop PictureEssenceCoding and SoundEssenceCompression, only check EssenceContainer */ codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->essence_codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; if (st->codecpar->codec_id == AV_CODEC_ID_NONE) { codec_ul = mxf_get_codec_ul(ff_mxf_codec_uls, &descriptor->codec_ul); st->codecpar->codec_id = (enum AVCodecID)codec_ul->id; } av_log(mxf->fc, AV_LOG_VERBOSE, "%s: Universal Label: ", avcodec_get_name(st->codecpar->codec_id)); for (k = 0; k < 16; k++) { av_log(mxf->fc, AV_LOG_VERBOSE, "%.2x", descriptor->essence_codec_ul[k]); if (!(k+1 & 19) || k == 5) av_log(mxf->fc, AV_LOG_VERBOSE, "."); } av_log(mxf->fc, AV_LOG_VERBOSE, "\n"); mxf_add_umid_metadata(&st->metadata, "file_package_umid", source_package); if (source_package->name && source_package->name[0]) av_dict_set(&st->metadata, "file_package_name", source_package->name, 0); if (material_track->name && material_track->name[0]) av_dict_set(&st->metadata, "track_name", material_track->name, 0); mxf_parse_physical_source_package(mxf, source_track, st); if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) { source_track->intra_only = mxf_is_intra_only(descriptor); container_ul = mxf_get_codec_ul(mxf_picture_essence_container_uls, essence_container_ul); if (st->codecpar->codec_id == AV_CODEC_ID_NONE) st->codecpar->codec_id = container_ul->id; st->codecpar->width = descriptor->width; st->codecpar->height = descriptor->height; /* Field height, not frame height */ switch (descriptor->frame_layout) { case FullFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; break; case OneField: /* Every other line is stored and needs to be duplicated. */ av_log(mxf->fc, AV_LOG_INFO, "OneField frame layout isn't currently supported\n"); break; /* The correct thing to do here is fall through, but by breaking we might be able to decode some streams at half the vertical resolution, rather than not al all. It's also for compatibility with the old behavior. */ case MixedFields: break; case SegmentedFrame: st->codecpar->field_order = AV_FIELD_PROGRESSIVE; case SeparateFields: av_log(mxf->fc, AV_LOG_DEBUG, "video_line_map: (%d, %d), field_dominance: %d\n", descriptor->video_line_map[0], descriptor->video_line_map[1], descriptor->field_dominance); if ((descriptor->video_line_map[0] > 0) && (descriptor->video_line_map[1] > 0)) { /* Detect coded field order from VideoLineMap: * (even, even) => bottom field coded first * (even, odd) => top field coded first * (odd, even) => top field coded first * (odd, odd) => bottom field coded first */ if ((descriptor->video_line_map[0] + descriptor->video_line_map[1]) % 2) { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_TT; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_TB; break; default: avpriv_request_sample(mxf->fc, "Field dominance %d support", descriptor->field_dominance); } } else { switch (descriptor->field_dominance) { case MXF_FIELD_DOMINANCE_DEFAULT: case MXF_FIELD_DOMINANCE_FF: st->codecpar->field_order = AV_FIELD_BB; break; case MXF_FIELD_DOMINANCE_FL: st->codecpar->field_order = AV_FIELD_BT; break; default: avpriv_request_sample(mxf->fc, "Field dominance %d support", descriptor->field_dominance); } } } /* Turn field height into frame height. */ st->codecpar->height *= 2; break; default: av_log(mxf->fc, AV_LOG_INFO, "Unknown frame layout type: %d\n", descriptor->frame_layout); } if (st->codecpar->codec_id == AV_CODEC_ID_RAWVIDEO) { st->codecpar->format = descriptor->pix_fmt; if (st->codecpar->format == AV_PIX_FMT_NONE) { pix_fmt_ul = mxf_get_codec_ul(ff_mxf_pixel_format_uls, &descriptor->essence_codec_ul); st->codecpar->format = (enum AVPixelFormat)pix_fmt_ul->id; if (st->codecpar->format== AV_PIX_FMT_NONE) { st->codecpar->codec_tag = mxf_get_codec_ul(ff_mxf_codec_tag_uls, &descriptor->essence_codec_ul)->id; if (!st->codecpar->codec_tag) { /* support files created before RP224v10 by defaulting to UYVY422 if subsampling is 4:2:2 and component depth is 8-bit */ if (descriptor->horiz_subsampling == 2 && descriptor->vert_subsampling == 1 && descriptor->component_depth == 8) { st->codecpar->format = AV_PIX_FMT_UYVY422; } } } } } st->need_parsing = AVSTREAM_PARSE_HEADERS; if (material_track->sequence->origin) { av_dict_set_int(&st->metadata, "material_track_origin", material_track->sequence->origin, 0); } if (source_track->sequence->origin) { av_dict_set_int(&st->metadata, "source_track_origin", source_track->sequence->origin, 0); } if (descriptor->aspect_ratio.num && descriptor->aspect_ratio.den) st->display_aspect_ratio = descriptor->aspect_ratio; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { container_ul = mxf_get_codec_ul(mxf_sound_essence_container_uls, essence_container_ul); /* Only overwrite existing codec ID if it is unset or A-law, which is the default according to SMPTE RP 224. */ if (st->codecpar->codec_id == AV_CODEC_ID_NONE || (st->codecpar->codec_id == AV_CODEC_ID_PCM_ALAW && (enum AVCodecID)container_ul->id != AV_CODEC_ID_NONE)) st->codecpar->codec_id = (enum AVCodecID)container_ul->id; st->codecpar->channels = descriptor->channels; st->codecpar->bits_per_coded_sample = descriptor->bits_per_sample; if (descriptor->sample_rate.den > 0) { st->codecpar->sample_rate = descriptor->sample_rate.num / descriptor->sample_rate.den; avpriv_set_pts_info(st, 64, descriptor->sample_rate.den, descriptor->sample_rate.num); } else { av_log(mxf->fc, AV_LOG_WARNING, "invalid sample rate (%d/%d) " "found for stream #%d, time base forced to 1/48000\n", descriptor->sample_rate.num, descriptor->sample_rate.den, st->index); avpriv_set_pts_info(st, 64, 1, 48000); } /* if duration is set, rescale it from EditRate to SampleRate */ if (st->duration != AV_NOPTS_VALUE) st->duration = av_rescale_q(st->duration, av_inv_q(material_track->edit_rate), st->time_base); /* TODO: implement AV_CODEC_ID_RAWAUDIO */ if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16LE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24LE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32LE; } else if (st->codecpar->codec_id == AV_CODEC_ID_PCM_S16BE) { if (descriptor->bits_per_sample > 16 && descriptor->bits_per_sample <= 24) st->codecpar->codec_id = AV_CODEC_ID_PCM_S24BE; else if (descriptor->bits_per_sample == 32) st->codecpar->codec_id = AV_CODEC_ID_PCM_S32BE; } else if (st->codecpar->codec_id == AV_CODEC_ID_MP2) { st->need_parsing = AVSTREAM_PARSE_FULL; } } else if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA) { int codec_id = mxf_get_codec_ul(mxf_data_essence_container_uls, essence_container_ul)->id; if (codec_id >= 0 && codec_id < FF_ARRAY_ELEMS(mxf_data_essence_descriptor)) { av_dict_set(&st->metadata, "data_type", mxf_data_essence_descriptor[codec_id], 0); } } if (descriptor->extradata) { if (!ff_alloc_extradata(st->codecpar, descriptor->extradata_size)) { memcpy(st->codecpar->extradata, descriptor->extradata, descriptor->extradata_size); } } else if (st->codecpar->codec_id == AV_CODEC_ID_H264) { int coded_width = mxf_get_codec_ul(mxf_intra_only_picture_coded_width, &descriptor->essence_codec_ul)->id; if (coded_width) st->codecpar->width = coded_width; ret = ff_generate_avci_extradata(st); if (ret < 0) return ret; } if (st->codecpar->codec_type != AVMEDIA_TYPE_DATA && (*essence_container_ul)[15] > 0x01) { /* TODO: decode timestamps */ st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS; } } ret = 0; fail_and_free: return ret; } static int64_t mxf_timestamp_to_int64(uint64_t timestamp) { struct tm time = { 0 }; time.tm_year = (timestamp >> 48) - 1900; time.tm_mon = (timestamp >> 40 & 0xFF) - 1; time.tm_mday = (timestamp >> 32 & 0xFF); time.tm_hour = (timestamp >> 24 & 0xFF); time.tm_min = (timestamp >> 16 & 0xFF); time.tm_sec = (timestamp >> 8 & 0xFF); /* msvcrt versions of strftime calls the invalid parameter handler * (aborting the process if one isn't set) if the parameters are out * of range. */ time.tm_mon = av_clip(time.tm_mon, 0, 11); time.tm_mday = av_clip(time.tm_mday, 1, 31); time.tm_hour = av_clip(time.tm_hour, 0, 23); time.tm_min = av_clip(time.tm_min, 0, 59); time.tm_sec = av_clip(time.tm_sec, 0, 59); return (int64_t)av_timegm(&time) * 1000000; } #define SET_STR_METADATA(pb, name, str) do { \ if ((ret = mxf_read_utf16be_string(pb, size, &str)) < 0) \ return ret; \ av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \ } while (0) #define SET_UID_METADATA(pb, name, var, str) do { \ avio_read(pb, var, 16); \ if ((ret = mxf_uid_to_str(var, &str)) < 0) \ return ret; \ av_dict_set(&s->metadata, name, str, AV_DICT_DONT_STRDUP_VAL); \ } while (0) #define SET_TS_METADATA(pb, name, var, str) do { \ var = avio_rb64(pb); \ if ((ret = avpriv_dict_set_timestamp(&s->metadata, name, mxf_timestamp_to_int64(var)) < 0)) \ return ret; \ } while (0) static int mxf_read_identification_metadata(void *arg, AVIOContext *pb, int tag, int size, UID _uid, int64_t klv_offset) { MXFContext *mxf = arg; AVFormatContext *s = mxf->fc; int ret; UID uid = { 0 }; char *str = NULL; uint64_t ts; switch (tag) { case 0x3C01: SET_STR_METADATA(pb, "company_name", str); break; case 0x3C02: SET_STR_METADATA(pb, "product_name", str); break; case 0x3C04: SET_STR_METADATA(pb, "product_version", str); break; case 0x3C05: SET_UID_METADATA(pb, "product_uid", uid, str); break; case 0x3C06: SET_TS_METADATA(pb, "modification_date", ts, str); break; case 0x3C08: SET_STR_METADATA(pb, "application_platform", str); break; case 0x3C09: SET_UID_METADATA(pb, "generation_uid", uid, str); break; case 0x3C0A: SET_UID_METADATA(pb, "uid", uid, str); break; } return 0; } static int mxf_read_preface_metadata(void *arg, AVIOContext *pb, int tag, int size, UID uid, int64_t klv_offset) { MXFContext *mxf = arg; AVFormatContext *s = mxf->fc; int ret; char *str = NULL; if (tag >= 0x8000 && (IS_KLV_KEY(uid, mxf_avid_project_name))) { SET_STR_METADATA(pb, "project_name", str); } return 0; } static const MXFMetadataReadTableEntry mxf_metadata_read_table[] = { { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x05,0x01,0x00 }, mxf_read_primer_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x01,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x02,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x03,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x02,0x04,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x01,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x02,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x03,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x03,0x04,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x02,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x05,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x04,0x04,0x00 }, mxf_read_partition_pack }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x2f,0x00 }, mxf_read_preface_metadata }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x30,0x00 }, mxf_read_identification_metadata }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x18,0x00 }, mxf_read_content_storage, 0, AnyType }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x37,0x00 }, mxf_read_package, sizeof(MXFPackage), SourcePackage }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x36,0x00 }, mxf_read_package, sizeof(MXFPackage), MaterialPackage }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0f,0x00 }, mxf_read_sequence, sizeof(MXFSequence), Sequence }, { { 0x06,0x0E,0x2B,0x34,0x02,0x53,0x01,0x01,0x0D,0x01,0x01,0x01,0x01,0x01,0x05,0x00 }, mxf_read_essence_group, sizeof(MXFEssenceGroup), EssenceGroup}, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x11,0x00 }, mxf_read_source_clip, sizeof(MXFStructuralComponent), SourceClip }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3f,0x00 }, mxf_read_tagged_value, sizeof(MXFTaggedValue), TaggedValue }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x44,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), MultipleDescriptor }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x42,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Generic Sound */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x28,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* CDCI */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x29,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* RGBA */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x48,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* Wave */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x47,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* AES3 */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x51,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2VideoDescriptor */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5c,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* VANC/VBI - SMPTE 436M */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x5e,0x00 }, mxf_read_generic_descriptor, sizeof(MXFDescriptor), Descriptor }, /* MPEG2AudioDescriptor */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3A,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Static Track */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x3B,0x00 }, mxf_read_track, sizeof(MXFTrack), Track }, /* Generic Track */ { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x14,0x00 }, mxf_read_timecode_component, sizeof(MXFTimecodeComponent), TimecodeComponent }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x01,0x01,0x01,0x01,0x0c,0x00 }, mxf_read_pulldown_component, sizeof(MXFPulldownComponent), PulldownComponent }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x04,0x01,0x02,0x02,0x00,0x00 }, mxf_read_cryptographic_context, sizeof(MXFCryptoContext), CryptoContext }, { { 0x06,0x0e,0x2b,0x34,0x02,0x53,0x01,0x01,0x0d,0x01,0x02,0x01,0x01,0x10,0x01,0x00 }, mxf_read_index_table_segment, sizeof(MXFIndexTableSegment), IndexTableSegment }, { { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00 }, NULL, 0, AnyType }, }; static int mxf_metadataset_init(MXFMetadataSet *ctx, enum MXFMetadataSetType type) { switch (type){ case MultipleDescriptor: case Descriptor: ((MXFDescriptor*)ctx)->pix_fmt = AV_PIX_FMT_NONE; ((MXFDescriptor*)ctx)->duration = AV_NOPTS_VALUE; break; default: break; } return 0; } static int mxf_read_local_tags(MXFContext *mxf, KLVPacket *klv, MXFMetadataReadFunc *read_child, int ctx_size, enum MXFMetadataSetType type) { AVIOContext *pb = mxf->fc->pb; MXFMetadataSet *ctx = ctx_size ? av_mallocz(ctx_size) : mxf; uint64_t klv_end = avio_tell(pb) + klv->length; if (!ctx) return AVERROR(ENOMEM); mxf_metadataset_init(ctx, type); while (avio_tell(pb) + 4 < klv_end && !avio_feof(pb)) { int ret; int tag = avio_rb16(pb); int size = avio_rb16(pb); /* KLV specified by 0x53 */ uint64_t next = avio_tell(pb) + size; UID uid = {0}; av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x size %d\n", tag, size); if (!size) { /* ignore empty tag, needed for some files with empty UMID tag */ av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x with 0 size\n", tag); continue; } if (tag > 0x7FFF) { /* dynamic tag */ int i; for (i = 0; i < mxf->local_tags_count; i++) { int local_tag = AV_RB16(mxf->local_tags+i*18); if (local_tag == tag) { memcpy(uid, mxf->local_tags+i*18+2, 16); av_log(mxf->fc, AV_LOG_TRACE, "local tag %#04x\n", local_tag); PRINT_KEY(mxf->fc, "uid", uid); } } } if (ctx_size && tag == 0x3C0A) { avio_read(pb, ctx->uid, 16); } else if ((ret = read_child(ctx, pb, tag, size, uid, -1)) < 0) { mxf_free_metadataset(&ctx, !!ctx_size); return ret; } /* Accept the 64k local set limit being exceeded (Avid). Don't accept * it extending past the end of the KLV though (zzuf5.mxf). */ if (avio_tell(pb) > klv_end) { if (ctx_size) { ctx->type = type; mxf_free_metadataset(&ctx, !!ctx_size); } av_log(mxf->fc, AV_LOG_ERROR, "local tag %#04x extends past end of local set @ %#"PRIx64"\n", tag, klv->offset); return AVERROR_INVALIDDATA; } else if (avio_tell(pb) <= next) /* only seek forward, else this can loop for a long time */ avio_seek(pb, next, SEEK_SET); } if (ctx_size) ctx->type = type; return ctx_size ? mxf_add_metadata_set(mxf, ctx) : 0; } /** * Matches any partition pack key, in other words: * - HeaderPartition * - BodyPartition * - FooterPartition * @return non-zero if the key is a partition pack key, zero otherwise */ static int mxf_is_partition_pack_key(UID key) { //NOTE: this is a little lax since it doesn't constraint key[14] return !memcmp(key, mxf_header_partition_pack_key, 13) && key[13] >= 2 && key[13] <= 4; } /** * Parses a metadata KLV * @return <0 on error, 0 otherwise */ static int mxf_parse_klv(MXFContext *mxf, KLVPacket klv, MXFMetadataReadFunc *read, int ctx_size, enum MXFMetadataSetType type) { AVFormatContext *s = mxf->fc; int res; if (klv.key[5] == 0x53) { res = mxf_read_local_tags(mxf, &klv, read, ctx_size, type); } else { uint64_t next = avio_tell(s->pb) + klv.length; res = read(mxf, s->pb, 0, klv.length, klv.key, klv.offset); /* only seek forward, else this can loop for a long time */ if (avio_tell(s->pb) > next) { av_log(s, AV_LOG_ERROR, "read past end of KLV @ %#"PRIx64"\n", klv.offset); return AVERROR_INVALIDDATA; } avio_seek(s->pb, next, SEEK_SET); } if (res < 0) { av_log(s, AV_LOG_ERROR, "error reading header metadata\n"); return res; } return 0; } /** * Seeks to the previous partition and parses it, if possible * @return <= 0 if we should stop parsing, > 0 if we should keep going */ static int mxf_seek_to_previous_partition(MXFContext *mxf) { AVIOContext *pb = mxf->fc->pb; KLVPacket klv; int64_t current_partition_ofs; int ret; if (!mxf->current_partition || mxf->run_in + mxf->current_partition->previous_partition <= mxf->last_forward_tell) return 0; /* we've parsed all partitions */ /* seek to previous partition */ current_partition_ofs = mxf->current_partition->pack_ofs; //includes run-in avio_seek(pb, mxf->run_in + mxf->current_partition->previous_partition, SEEK_SET); mxf->current_partition = NULL; av_log(mxf->fc, AV_LOG_TRACE, "seeking to previous partition\n"); /* Make sure this is actually a PartitionPack, and if so parse it. * See deadlock2.mxf */ if ((ret = klv_read_packet(&klv, pb)) < 0) { av_log(mxf->fc, AV_LOG_ERROR, "failed to read PartitionPack KLV\n"); return ret; } if (!mxf_is_partition_pack_key(klv.key)) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition @ %" PRIx64 " isn't a PartitionPack\n", klv.offset); return AVERROR_INVALIDDATA; } /* We can't just check ofs >= current_partition_ofs because PreviousPartition * can point to just before the current partition, causing klv_read_packet() * to sync back up to it. See deadlock3.mxf */ if (klv.offset >= current_partition_ofs) { av_log(mxf->fc, AV_LOG_ERROR, "PreviousPartition for PartitionPack @ %" PRIx64 " indirectly points to itself\n", current_partition_ofs); return AVERROR_INVALIDDATA; } if ((ret = mxf_parse_klv(mxf, klv, mxf_read_partition_pack, 0, 0)) < 0) return ret; return 1; } /** * Called when essence is encountered * @return <= 0 if we should stop parsing, > 0 if we should keep going */ static int mxf_parse_handle_essence(MXFContext *mxf) { AVIOContext *pb = mxf->fc->pb; int64_t ret; if (mxf->parsing_backward) { return mxf_seek_to_previous_partition(mxf); } else { if (!mxf->footer_partition) { av_log(mxf->fc, AV_LOG_TRACE, "no FooterPartition\n"); return 0; } av_log(mxf->fc, AV_LOG_TRACE, "seeking to FooterPartition\n"); /* remember where we were so we don't end up seeking further back than this */ mxf->last_forward_tell = avio_tell(pb); if (!(pb->seekable & AVIO_SEEKABLE_NORMAL)) { av_log(mxf->fc, AV_LOG_INFO, "file is not seekable - not parsing FooterPartition\n"); return -1; } /* seek to FooterPartition and parse backward */ if ((ret = avio_seek(pb, mxf->run_in + mxf->footer_partition, SEEK_SET)) < 0) { av_log(mxf->fc, AV_LOG_ERROR, "failed to seek to FooterPartition @ 0x%" PRIx64 " (%"PRId64") - partial file?\n", mxf->run_in + mxf->footer_partition, ret); return ret; } mxf->current_partition = NULL; mxf->parsing_backward = 1; } return 1; } /** * Called when the next partition or EOF is encountered * @return <= 0 if we should stop parsing, > 0 if we should keep going */ static int mxf_parse_handle_partition_or_eof(MXFContext *mxf) { return mxf->parsing_backward ? mxf_seek_to_previous_partition(mxf) : 1; } /** * Figures out the proper offset and length of the essence container in each partition */ static void mxf_compute_essence_containers(MXFContext *mxf) { int x; /* everything is already correct */ if (mxf->op == OPAtom) return; for (x = 0; x < mxf->partitions_count; x++) { MXFPartition *p = &mxf->partitions[x]; if (!p->body_sid) continue; /* BodySID == 0 -> no essence */ if (x >= mxf->partitions_count - 1) break; /* FooterPartition - can't compute length (and we don't need to) */ /* essence container spans to the next partition */ p->essence_length = mxf->partitions[x+1].this_partition - p->essence_offset; if (p->essence_length < 0) { /* next ThisPartition < essence_offset */ p->essence_length = 0; av_log(mxf->fc, AV_LOG_ERROR, "partition %i: bad ThisPartition = %"PRIX64"\n", x+1, mxf->partitions[x+1].this_partition); } } } static int64_t round_to_kag(int64_t position, int kag_size) { /* TODO: account for run-in? the spec isn't clear whether KAG should account for it */ /* NOTE: kag_size may be any integer between 1 - 2^10 */ int64_t ret = (position / kag_size) * kag_size; return ret == position ? ret : ret + kag_size; } static int is_pcm(enum AVCodecID codec_id) { /* we only care about "normal" PCM codecs until we get samples */ return codec_id >= AV_CODEC_ID_PCM_S16LE && codec_id < AV_CODEC_ID_PCM_S24DAUD; } static AVStream* mxf_get_opatom_stream(MXFContext *mxf) { int i; if (mxf->op != OPAtom) return NULL; for (i = 0; i < mxf->fc->nb_streams; i++) { if (mxf->fc->streams[i]->codecpar->codec_type == AVMEDIA_TYPE_DATA) continue; return mxf->fc->streams[i]; } return NULL; } /** * Deal with the case where for some audio atoms EditUnitByteCount is * very small (2, 4..). In those cases we should read more than one * sample per call to mxf_read_packet(). */ static void mxf_handle_small_eubc(AVFormatContext *s) { MXFContext *mxf = s->priv_data; /* assuming non-OPAtom == frame wrapped * no sane writer would wrap 2 byte PCM packets with 20 byte headers.. */ AVStream *st = mxf_get_opatom_stream(mxf); if (!st) return; /* expect PCM with exactly one index table segment and a small (< 32) EUBC */ if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || !is_pcm(st->codecpar->codec_id) || mxf->nb_index_tables != 1 || mxf->index_tables[0].nb_segments != 1 || mxf->index_tables[0].segments[0]->edit_unit_byte_count >= 32) return; /* arbitrarily default to 48 kHz PAL audio frame size */ /* TODO: We could compute this from the ratio between the audio * and video edit rates for 48 kHz NTSC we could use the * 1802-1802-1802-1802-1801 pattern. */ mxf->edit_units_per_packet = 1920; } /** * Deal with the case where OPAtom files does not have any IndexTableSegments. */ static int mxf_handle_missing_index_segment(MXFContext *mxf) { AVFormatContext *s = mxf->fc; AVStream *st = NULL; MXFIndexTableSegment *segment = NULL; MXFPartition *p = NULL; int essence_partition_count = 0; int i, ret; st = mxf_get_opatom_stream(mxf); if (!st) return 0; /* TODO: support raw video without an index if they exist */ if (st->codecpar->codec_type != AVMEDIA_TYPE_AUDIO || !is_pcm(st->codecpar->codec_id)) return 0; /* check if file already has a IndexTableSegment */ for (i = 0; i < mxf->metadata_sets_count; i++) { if (mxf->metadata_sets[i]->type == IndexTableSegment) return 0; } /* find the essence partition */ for (i = 0; i < mxf->partitions_count; i++) { /* BodySID == 0 -> no essence */ if (!mxf->partitions[i].body_sid) continue; p = &mxf->partitions[i]; essence_partition_count++; } /* only handle files with a single essence partition */ if (essence_partition_count != 1) return 0; if (!(segment = av_mallocz(sizeof(*segment)))) return AVERROR(ENOMEM); if ((ret = mxf_add_metadata_set(mxf, segment))) { mxf_free_metadataset((MXFMetadataSet**)&segment, 1); return ret; } segment->type = IndexTableSegment; /* stream will be treated as small EditUnitByteCount */ segment->edit_unit_byte_count = (av_get_bits_per_sample(st->codecpar->codec_id) * st->codecpar->channels) >> 3; segment->index_start_position = 0; segment->index_duration = s->streams[0]->duration; segment->index_sid = p->index_sid; segment->body_sid = p->body_sid; return 0; } static void mxf_read_random_index_pack(AVFormatContext *s) { MXFContext *mxf = s->priv_data; uint32_t length; int64_t file_size, max_rip_length, min_rip_length; KLVPacket klv; if (!(s->pb->seekable & AVIO_SEEKABLE_NORMAL)) return; file_size = avio_size(s->pb); /* S377m says to check the RIP length for "silly" values, without defining "silly". * The limit below assumes a file with nothing but partition packs and a RIP. * Before changing this, consider that a muxer may place each sample in its own partition. * * 105 is the size of the smallest possible PartitionPack * 12 is the size of each RIP entry * 28 is the size of the RIP header and footer, assuming an 8-byte BER */ max_rip_length = ((file_size - mxf->run_in) / 105) * 12 + 28; max_rip_length = FFMIN(max_rip_length, INT_MAX); //2 GiB and up is also silly /* We're only interested in RIPs with at least two entries.. */ min_rip_length = 16+1+24+4; /* See S377m section 11 */ avio_seek(s->pb, file_size - 4, SEEK_SET); length = avio_rb32(s->pb); if (length < min_rip_length || length > max_rip_length) goto end; avio_seek(s->pb, file_size - length, SEEK_SET); if (klv_read_packet(&klv, s->pb) < 0 || !IS_KLV_KEY(klv.key, mxf_random_index_pack_key) || klv.length != length - 20) goto end; avio_skip(s->pb, klv.length - 12); mxf->footer_partition = avio_rb64(s->pb); /* sanity check */ if (mxf->run_in + mxf->footer_partition >= file_size) { av_log(s, AV_LOG_WARNING, "bad FooterPartition in RIP - ignoring\n"); mxf->footer_partition = 0; } end: avio_seek(s->pb, mxf->run_in, SEEK_SET); } static int mxf_read_header(AVFormatContext *s) { MXFContext *mxf = s->priv_data; KLVPacket klv; int64_t essence_offset = 0; int ret; mxf->last_forward_tell = INT64_MAX; mxf->edit_units_per_packet = 1; if (!mxf_read_sync(s->pb, mxf_header_partition_pack_key, 14)) { av_log(s, AV_LOG_ERROR, "could not find header partition pack key\n"); return AVERROR_INVALIDDATA; } avio_seek(s->pb, -14, SEEK_CUR); mxf->fc = s; mxf->run_in = avio_tell(s->pb); mxf_read_random_index_pack(s); while (!avio_feof(s->pb)) { const MXFMetadataReadTableEntry *metadata; if (klv_read_packet(&klv, s->pb) < 0) { /* EOF - seek to previous partition or stop */ if(mxf_parse_handle_partition_or_eof(mxf) <= 0) break; else continue; } PRINT_KEY(s, "read header", klv.key); av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset); if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key) || IS_KLV_KEY(klv.key, mxf_essence_element_key) || IS_KLV_KEY(klv.key, mxf_avid_essence_element_key) || IS_KLV_KEY(klv.key, mxf_system_item_key)) { if (!mxf->current_partition) { av_log(mxf->fc, AV_LOG_ERROR, "found essence prior to first PartitionPack\n"); return AVERROR_INVALIDDATA; } if (!mxf->current_partition->essence_offset) { /* for OP1a we compute essence_offset * for OPAtom we point essence_offset after the KL (usually op1a_essence_offset + 20 or 25) * TODO: for OP1a we could eliminate this entire if statement, always stopping parsing at op1a_essence_offset * for OPAtom we still need the actual essence_offset though (the KL's length can vary) */ int64_t op1a_essence_offset = round_to_kag(mxf->current_partition->this_partition + mxf->current_partition->pack_length, mxf->current_partition->kag_size) + round_to_kag(mxf->current_partition->header_byte_count, mxf->current_partition->kag_size) + round_to_kag(mxf->current_partition->index_byte_count, mxf->current_partition->kag_size); if (mxf->op == OPAtom) { /* point essence_offset to the actual data * OPAtom has all the essence in one big KLV */ mxf->current_partition->essence_offset = avio_tell(s->pb); mxf->current_partition->essence_length = klv.length; } else { /* NOTE: op1a_essence_offset may be less than to klv.offset (C0023S01.mxf) */ mxf->current_partition->essence_offset = op1a_essence_offset; } } if (!essence_offset) essence_offset = klv.offset; /* seek to footer, previous partition or stop */ if (mxf_parse_handle_essence(mxf) <= 0) break; continue; } else if (mxf_is_partition_pack_key(klv.key) && mxf->current_partition) { /* next partition pack - keep going, seek to previous partition or stop */ if(mxf_parse_handle_partition_or_eof(mxf) <= 0) break; else if (mxf->parsing_backward) continue; /* we're still parsing forward. proceed to parsing this partition pack */ } for (metadata = mxf_metadata_read_table; metadata->read; metadata++) { if (IS_KLV_KEY(klv.key, metadata->key)) { if ((ret = mxf_parse_klv(mxf, klv, metadata->read, metadata->ctx_size, metadata->type)) < 0) goto fail; break; } } if (!metadata->read) { av_log(s, AV_LOG_VERBOSE, "Dark key " PRIxUID "\n", UID_ARG(klv.key)); avio_skip(s->pb, klv.length); } } /* FIXME avoid seek */ if (!essence_offset) { av_log(s, AV_LOG_ERROR, "no essence\n"); ret = AVERROR_INVALIDDATA; goto fail; } avio_seek(s->pb, essence_offset, SEEK_SET); mxf_compute_essence_containers(mxf); /* we need to do this before computing the index tables * to be able to fill in zero IndexDurations with st->duration */ if ((ret = mxf_parse_structural_metadata(mxf)) < 0) goto fail; mxf_handle_missing_index_segment(mxf); if ((ret = mxf_compute_index_tables(mxf)) < 0) goto fail; if (mxf->nb_index_tables > 1) { /* TODO: look up which IndexSID to use via EssenceContainerData */ av_log(mxf->fc, AV_LOG_INFO, "got %i index tables - only the first one (IndexSID %i) will be used\n", mxf->nb_index_tables, mxf->index_tables[0].index_sid); } else if (mxf->nb_index_tables == 0 && mxf->op == OPAtom) { av_log(mxf->fc, AV_LOG_ERROR, "cannot demux OPAtom without an index\n"); ret = AVERROR_INVALIDDATA; goto fail; } mxf_handle_small_eubc(s); return 0; fail: mxf_read_close(s); return ret; } /** * Sets mxf->current_edit_unit based on what offset we're currently at. * @return next_ofs if OK, <0 on error */ static int64_t mxf_set_current_edit_unit(MXFContext *mxf, int64_t current_offset) { int64_t last_ofs = -1, next_ofs = -1; MXFIndexTable *t = &mxf->index_tables[0]; /* this is called from the OP1a demuxing logic, which means there * may be no index tables */ if (mxf->nb_index_tables <= 0) return -1; /* find mxf->current_edit_unit so that the next edit unit starts ahead of current_offset */ while (mxf->current_edit_unit >= 0) { if (mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + 1, NULL, &next_ofs, 0) < 0) return -1; if (next_ofs <= last_ofs) { /* large next_ofs didn't change or current_edit_unit wrapped * around this fixes the infinite loop on zzuf3.mxf */ av_log(mxf->fc, AV_LOG_ERROR, "next_ofs didn't change. not deriving packet timestamps\n"); return -1; } if (next_ofs > current_offset) break; last_ofs = next_ofs; mxf->current_edit_unit++; } /* not checking mxf->current_edit_unit >= t->nb_ptses here since CBR files may lack IndexEntryArrays */ if (mxf->current_edit_unit < 0) return -1; return next_ofs; } static int mxf_compute_sample_count(MXFContext *mxf, int stream_index, uint64_t *sample_count) { int i, total = 0, size = 0; AVStream *st = mxf->fc->streams[stream_index]; MXFTrack *track = st->priv_data; AVRational time_base = av_inv_q(track->edit_rate); AVRational sample_rate = av_inv_q(st->time_base); const MXFSamplesPerFrame *spf = NULL; if ((sample_rate.num / sample_rate.den) == 48000) spf = ff_mxf_get_samples_per_frame(mxf->fc, time_base); if (!spf) { int remainder = (sample_rate.num * time_base.num) % (time_base.den * sample_rate.den); *sample_count = av_q2d(av_mul_q((AVRational){mxf->current_edit_unit, 1}, av_mul_q(sample_rate, time_base))); if (remainder) av_log(mxf->fc, AV_LOG_WARNING, "seeking detected on stream #%d with time base (%d/%d) and " "sample rate (%d/%d), audio pts won't be accurate.\n", stream_index, time_base.num, time_base.den, sample_rate.num, sample_rate.den); return 0; } while (spf->samples_per_frame[size]) { total += spf->samples_per_frame[size]; size++; } av_assert2(size); *sample_count = (mxf->current_edit_unit / size) * (uint64_t)total; for (i = 0; i < mxf->current_edit_unit % size; i++) { *sample_count += spf->samples_per_frame[i]; } return 0; } static int mxf_set_audio_pts(MXFContext *mxf, AVCodecParameters *par, AVPacket *pkt) { MXFTrack *track = mxf->fc->streams[pkt->stream_index]->priv_data; int64_t bits_per_sample = par->bits_per_coded_sample; if (!bits_per_sample) bits_per_sample = av_get_bits_per_sample(par->codec_id); pkt->pts = track->sample_count; if ( par->channels <= 0 || bits_per_sample <= 0 || par->channels * (int64_t)bits_per_sample < 8) return AVERROR(EINVAL); track->sample_count += pkt->size / (par->channels * (int64_t)bits_per_sample / 8); return 0; } static int mxf_read_packet_old(AVFormatContext *s, AVPacket *pkt) { KLVPacket klv; MXFContext *mxf = s->priv_data; int ret; while ((ret = klv_read_packet(&klv, s->pb)) == 0) { PRINT_KEY(s, "read packet", klv.key); av_log(s, AV_LOG_TRACE, "size %"PRIu64" offset %#"PRIx64"\n", klv.length, klv.offset); if (IS_KLV_KEY(klv.key, mxf_encrypted_triplet_key)) { ret = mxf_decrypt_triplet(s, pkt, &klv); if (ret < 0) { av_log(s, AV_LOG_ERROR, "invalid encoded triplet\n"); return ret; } return 0; } if (IS_KLV_KEY(klv.key, mxf_essence_element_key) || IS_KLV_KEY(klv.key, mxf_canopus_essence_element_key) || IS_KLV_KEY(klv.key, mxf_avid_essence_element_key)) { int index = mxf_get_stream_index(s, &klv); int64_t next_ofs, next_klv; AVStream *st; MXFTrack *track; AVCodecParameters *par; if (index < 0) { av_log(s, AV_LOG_ERROR, "error getting stream index %"PRIu32"\n", AV_RB32(klv.key + 12)); goto skip; } st = s->streams[index]; track = st->priv_data; if (s->streams[index]->discard == AVDISCARD_ALL) goto skip; next_klv = avio_tell(s->pb) + klv.length; next_ofs = mxf_set_current_edit_unit(mxf, klv.offset); if (next_ofs >= 0 && next_klv > next_ofs) { /* if this check is hit then it's possible OPAtom was treated as OP1a * truncate the packet since it's probably very large (>2 GiB is common) */ avpriv_request_sample(s, "OPAtom misinterpreted as OP1a? " "KLV for edit unit %i extending into " "next edit unit", mxf->current_edit_unit); klv.length = next_ofs - avio_tell(s->pb); } /* check for 8 channels AES3 element */ if (klv.key[12] == 0x06 && klv.key[13] == 0x01 && klv.key[14] == 0x10) { ret = mxf_get_d10_aes3_packet(s->pb, s->streams[index], pkt, klv.length); if (ret < 0) { av_log(s, AV_LOG_ERROR, "error reading D-10 aes3 frame\n"); return ret; } } else { ret = av_get_packet(s->pb, pkt, klv.length); if (ret < 0) return ret; } pkt->stream_index = index; pkt->pos = klv.offset; par = st->codecpar; if (par->codec_type == AVMEDIA_TYPE_VIDEO && next_ofs >= 0) { /* mxf->current_edit_unit good - see if we have an * index table to derive timestamps from */ MXFIndexTable *t = &mxf->index_tables[0]; if (mxf->nb_index_tables >= 1 && mxf->current_edit_unit < t->nb_ptses) { pkt->dts = mxf->current_edit_unit + t->first_dts; pkt->pts = t->ptses[mxf->current_edit_unit]; } else if (track && track->intra_only) { /* intra-only -> PTS = EditUnit. * let utils.c figure out DTS since it can be < PTS if low_delay = 0 (Sony IMX30) */ pkt->pts = mxf->current_edit_unit; } } else if (par->codec_type == AVMEDIA_TYPE_AUDIO) { ret = mxf_set_audio_pts(mxf, par, pkt); if (ret < 0) return ret; } /* seek for truncated packets */ avio_seek(s->pb, next_klv, SEEK_SET); return 0; } else skip: avio_skip(s->pb, klv.length); } return avio_feof(s->pb) ? AVERROR_EOF : ret; } static int mxf_read_packet(AVFormatContext *s, AVPacket *pkt) { MXFContext *mxf = s->priv_data; int ret, size; int64_t ret64, pos, next_pos; AVStream *st; MXFIndexTable *t; int edit_units; if (mxf->op != OPAtom) return mxf_read_packet_old(s, pkt); // If we have no streams then we basically are at EOF st = mxf_get_opatom_stream(mxf); if (!st) return AVERROR_EOF; /* OPAtom - clip wrapped demuxing */ /* NOTE: mxf_read_header() makes sure nb_index_tables > 0 for OPAtom */ t = &mxf->index_tables[0]; if (mxf->current_edit_unit >= st->duration) return AVERROR_EOF; edit_units = FFMIN(mxf->edit_units_per_packet, st->duration - mxf->current_edit_unit); if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit, NULL, &pos, 1)) < 0) return ret; /* compute size by finding the next edit unit or the end of the essence container * not pretty, but it works */ if ((ret = mxf_edit_unit_absolute_offset(mxf, t, mxf->current_edit_unit + edit_units, NULL, &next_pos, 0)) < 0 && (next_pos = mxf_essence_container_end(mxf, t->body_sid)) <= 0) { av_log(s, AV_LOG_ERROR, "unable to compute the size of the last packet\n"); return AVERROR_INVALIDDATA; } if ((size = next_pos - pos) <= 0) { av_log(s, AV_LOG_ERROR, "bad size: %i\n", size); return AVERROR_INVALIDDATA; } if ((ret64 = avio_seek(s->pb, pos, SEEK_SET)) < 0) return ret64; if ((size = av_get_packet(s->pb, pkt, size)) < 0) return size; pkt->stream_index = st->index; if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO && t->ptses && mxf->current_edit_unit >= 0 && mxf->current_edit_unit < t->nb_ptses) { pkt->dts = mxf->current_edit_unit + t->first_dts; pkt->pts = t->ptses[mxf->current_edit_unit]; } else if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { int ret = mxf_set_audio_pts(mxf, st->codecpar, pkt); if (ret < 0) return ret; } mxf->current_edit_unit += edit_units; return 0; } static int mxf_read_close(AVFormatContext *s) { MXFContext *mxf = s->priv_data; int i; av_freep(&mxf->packages_refs); for (i = 0; i < s->nb_streams; i++) s->streams[i]->priv_data = NULL; for (i = 0; i < mxf->metadata_sets_count; i++) { mxf_free_metadataset(mxf->metadata_sets + i, 1); } av_freep(&mxf->partitions); av_freep(&mxf->metadata_sets); av_freep(&mxf->aesc); av_freep(&mxf->local_tags); if (mxf->index_tables) { for (i = 0; i < mxf->nb_index_tables; i++) { av_freep(&mxf->index_tables[i].segments); av_freep(&mxf->index_tables[i].ptses); av_freep(&mxf->index_tables[i].fake_index); av_freep(&mxf->index_tables[i].offsets); } } av_freep(&mxf->index_tables); return 0; } static int mxf_probe(AVProbeData *p) { const uint8_t *bufp = p->buf; const uint8_t *end = p->buf + p->buf_size; if (p->buf_size < sizeof(mxf_header_partition_pack_key)) return 0; /* Must skip Run-In Sequence and search for MXF header partition pack key SMPTE 377M 5.5 */ end -= sizeof(mxf_header_partition_pack_key); for (; bufp < end;) { if (!((bufp[13] - 1) & 0xF2)){ if (AV_RN32(bufp ) == AV_RN32(mxf_header_partition_pack_key ) && AV_RN32(bufp+ 4) == AV_RN32(mxf_header_partition_pack_key+ 4) && AV_RN32(bufp+ 8) == AV_RN32(mxf_header_partition_pack_key+ 8) && AV_RN16(bufp+12) == AV_RN16(mxf_header_partition_pack_key+12)) return AVPROBE_SCORE_MAX; bufp ++; } else bufp += 10; } return 0; } /* rudimentary byte seek */ /* XXX: use MXF Index */ static int mxf_read_seek(AVFormatContext *s, int stream_index, int64_t sample_time, int flags) { AVStream *st = s->streams[stream_index]; int64_t seconds; MXFContext* mxf = s->priv_data; int64_t seekpos; int i, ret; MXFIndexTable *t; MXFTrack *source_track = st->priv_data; if(st->codecpar->codec_type == AVMEDIA_TYPE_DATA) return 0; /* if audio then truncate sample_time to EditRate */ if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) sample_time = av_rescale_q(sample_time, st->time_base, av_inv_q(source_track->edit_rate)); if (mxf->nb_index_tables <= 0) { if (!s->bit_rate) return AVERROR_INVALIDDATA; if (sample_time < 0) sample_time = 0; seconds = av_rescale(sample_time, st->time_base.num, st->time_base.den); seekpos = avio_seek(s->pb, (s->bit_rate * seconds) >> 3, SEEK_SET); if (seekpos < 0) return seekpos; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; } else { t = &mxf->index_tables[0]; /* clamp above zero, else ff_index_search_timestamp() returns negative * this also means we allow seeking before the start */ sample_time = FFMAX(sample_time, 0); if (t->fake_index) { /* The first frames may not be keyframes in presentation order, so * we have to advance the target to be able to find the first * keyframe backwards... */ if (!(flags & AVSEEK_FLAG_ANY) && (flags & AVSEEK_FLAG_BACKWARD) && t->ptses[0] != AV_NOPTS_VALUE && sample_time < t->ptses[0] && (t->fake_index[t->ptses[0]].flags & AVINDEX_KEYFRAME)) sample_time = t->ptses[0]; /* behave as if we have a proper index */ if ((sample_time = ff_index_search_timestamp(t->fake_index, t->nb_ptses, sample_time, flags)) < 0) return sample_time; /* get the stored order index from the display order index */ sample_time += t->offsets[sample_time]; } else { /* no IndexEntryArray (one or more CBR segments) * make sure we don't seek past the end */ sample_time = FFMIN(sample_time, source_track->original_duration - 1); } if ((ret = mxf_edit_unit_absolute_offset(mxf, t, sample_time, &sample_time, &seekpos, 1)) < 0) return ret; ff_update_cur_dts(s, st, sample_time); mxf->current_edit_unit = sample_time; avio_seek(s->pb, seekpos, SEEK_SET); } // Update all tracks sample count for (i = 0; i < s->nb_streams; i++) { AVStream *cur_st = s->streams[i]; MXFTrack *cur_track = cur_st->priv_data; uint64_t current_sample_count = 0; if (cur_st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { ret = mxf_compute_sample_count(mxf, i, &current_sample_count); if (ret < 0) return ret; cur_track->sample_count = current_sample_count; } } return 0; } AVInputFormat ff_mxf_demuxer = { .name = "mxf", .long_name = NULL_IF_CONFIG_SMALL("MXF (Material eXchange Format)"), .flags = AVFMT_SEEK_TO_PTS, .priv_data_size = sizeof(MXFContext), .read_probe = mxf_probe, .read_header = mxf_read_header, .read_packet = mxf_read_packet, .read_close = mxf_read_close, .read_seek = mxf_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2779_0
crossvul-cpp_data_good_2781_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP SSSSS % % P P SS % % PPPP SSS % % P SS % % P SSSSS % % % % % % Read/Write Postscript Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/delegate.h" #include "magick/delegate-private.h" #include "magick/draw.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/nt-base-private.h" #include "magick/option.h" #include "magick/profile.h" #include "magick/pixel-accessor.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/module.h" #include "magick/token.h" #include "magick/transform.h" #include "magick/utility.h" /* Forward declarations. */ static MagickBooleanType WritePSImage(const ImageInfo *,Image *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v o k e P o s t s r i p t D e l e g a t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InvokePostscriptDelegate() executes the Postscript interpreter with the % specified command. % % The format of the InvokePostscriptDelegate method is: % % MagickBooleanType InvokePostscriptDelegate( % const MagickBooleanType verbose,const char *command, % ExceptionInfo *exception) % % A description of each parameter follows: % % o verbose: A value other than zero displays the command prior to % executing it. % % o command: the address of a character string containing the command to % execute. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) static int MagickDLLCall PostscriptDelegateMessage(void *handle, const char *message,int length) { char **messages; ssize_t offset; offset=0; messages=(char **) handle; if (*messages == (char *) NULL) *messages=(char *) AcquireQuantumMemory(length+1,sizeof(char *)); else { offset=strlen(*messages); *messages=(char *) ResizeQuantumMemory(*messages,offset+length+1, sizeof(char *)); } (void) memcpy(*messages+offset,message,length); (*messages)[length+offset] ='\0'; return(length); } #endif static MagickBooleanType InvokePostscriptDelegate( const MagickBooleanType verbose,const char *command,char *message, ExceptionInfo *exception) { int status; #if defined(MAGICKCORE_GS_DELEGATE) || defined(MAGICKCORE_WINDOWS_SUPPORT) #define SetArgsStart(command,args_start) \ if (args_start == (const char *) NULL) \ { \ if (*command != '"') \ args_start=strchr(command,' '); \ else \ { \ args_start=strchr(command+1,'"'); \ if (args_start != (const char *) NULL) \ args_start++; \ } \ } #define ExecuteGhostscriptCommand(command,status) \ { \ status=ExternalDelegateCommand(MagickFalse,verbose,command,message, \ exception); \ if (status == 0) \ return(MagickTrue); \ if (status < 0) \ return(MagickFalse); \ (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, \ "FailedToExecuteCommand","`%s' (%d)",command,status); \ return(MagickFalse); \ } char **argv, *errors; const char *args_start = (const char *) NULL; const GhostInfo *ghost_info; gs_main_instance *interpreter; gsapi_revision_t revision; int argc, code; register ssize_t i; #if defined(MAGICKCORE_WINDOWS_SUPPORT) ghost_info=NTGhostscriptDLLVectors(); #else GhostInfo ghost_info_struct; ghost_info=(&ghost_info_struct); (void) ResetMagickMemory(&ghost_info_struct,0,sizeof(ghost_info_struct)); ghost_info_struct.delete_instance=(void (*)(gs_main_instance *)) gsapi_delete_instance; ghost_info_struct.exit=(int (*)(gs_main_instance *)) gsapi_exit; ghost_info_struct.new_instance=(int (*)(gs_main_instance **,void *)) gsapi_new_instance; ghost_info_struct.init_with_args=(int (*)(gs_main_instance *,int,char **)) gsapi_init_with_args; ghost_info_struct.run_string=(int (*)(gs_main_instance *,const char *,int, int *)) gsapi_run_string; ghost_info_struct.set_stdio=(int (*)(gs_main_instance *,int(*)(void *,char *, int),int(*)(void *,const char *,int),int(*)(void *, const char *, int))) gsapi_set_stdio; ghost_info_struct.revision=(int (*)(gsapi_revision_t *,int)) gsapi_revision; #endif if (ghost_info == (GhostInfo *) NULL) ExecuteGhostscriptCommand(command,status); if ((ghost_info->revision)(&revision,sizeof(revision)) != 0) revision.revision=0; if (verbose != MagickFalse) { (void) fprintf(stdout,"[ghostscript library %.2f]",(double) revision.revision/100.0); SetArgsStart(command,args_start); (void) fputs(args_start,stdout); } errors=(char *) NULL; status=(ghost_info->new_instance)(&interpreter,(void *) &errors); if (status < 0) ExecuteGhostscriptCommand(command,status); code=0; argv=StringToArgv(command,&argc); if (argv == (char **) NULL) { (ghost_info->delete_instance)(interpreter); return(MagickFalse); } (void) (ghost_info->set_stdio)(interpreter,(int(MagickDLLCall *)(void *, char *,int)) NULL,PostscriptDelegateMessage,PostscriptDelegateMessage); status=(ghost_info->init_with_args)(interpreter,argc-1,argv+1); if (status == 0) status=(ghost_info->run_string)(interpreter,"systemdict /start get exec\n", 0,&code); (ghost_info->exit)(interpreter); (ghost_info->delete_instance)(interpreter); for (i=0; i < (ssize_t) argc; i++) argv[i]=DestroyString(argv[i]); argv=(char **) RelinquishMagickMemory(argv); if (status != 0) { SetArgsStart(command,args_start); if (status == -101) /* quit */ (void) FormatLocaleString(message,MaxTextExtent, "[ghostscript library %.2f]%s: %s",(double)revision.revision / 100, args_start,errors); else { (void) ThrowMagickException(exception,GetMagickModule(), DelegateError,"PostscriptDelegateFailed", "`[ghostscript library %.2f]%s': %s", (double)revision.revision / 100,args_start,errors); if (errors != (char *) NULL) errors=DestroyString(errors); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Ghostscript returns status %d, exit code %d",status,code); return(MagickFalse); } } if (errors != (char *) NULL) errors=DestroyString(errors); return(MagickTrue); #else status=ExternalDelegateCommand(MagickFalse,verbose,command,(char *) NULL, exception); return(status == 0 ? MagickTrue : MagickFalse); #endif } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P S % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPS() returns MagickTrue if the image format type, identified by the % magick string, is PS. % % The format of the IsPS method is: % % MagickBooleanType IsPS(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsPS(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (memcmp(magick,"%!",2) == 0) return(MagickTrue); if (memcmp(magick,"\004%!",3) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPSImage() reads a Postscript image file and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer % to the new image. % % The format of the ReadPSImage method is: % % Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType IsPostscriptRendered(const char *path) { MagickBooleanType status; struct stat attributes; if ((path == (const char *) NULL) || (*path == '\0')) return(MagickFalse); status=GetPathAttributes(path,&attributes); if ((status != MagickFalse) && S_ISREG(attributes.st_mode) && (attributes.st_size > 0)) return(MagickTrue); return(MagickFalse); } static inline int ProfileInteger(Image *image,short int *hex_digits) { int c, l, value; register ssize_t i; l=0; value=0; for (i=0; i < 2; ) { c=ReadBlobByte(image); if ((c == EOF) || ((c == '%') && (l == '%'))) { value=(-1); break; } l=c; c&=0xff; if (isxdigit(c) == MagickFalse) continue; value=(int) ((size_t) value << 4)+hex_digits[c]; i++; } return(value); } static Image *ReadPSImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BoundingBox "BoundingBox:" #define BeginDocument "BeginDocument:" #define BeginXMPPacket "<?xpacket begin=" #define EndXMPPacket "<?xpacket end=" #define ICCProfile "BeginICCProfile:" #define CMYKCustomColor "CMYKCustomColor:" #define CMYKProcessColor "CMYKProcessColor:" #define DocumentMedia "DocumentMedia:" #define DocumentCustomColors "DocumentCustomColors:" #define DocumentProcessColors "DocumentProcessColors:" #define EndDocument "EndDocument:" #define HiResBoundingBox "HiResBoundingBox:" #define ImageData "ImageData:" #define PageBoundingBox "PageBoundingBox:" #define LanguageLevel "LanguageLevel:" #define PageMedia "PageMedia:" #define Pages "Pages:" #define PhotoshopProfile "BeginPhotoshop:" #define PostscriptLevel "!PS-" #define RenderPostscriptText " Rendering Postscript... " #define SpotColor "+ " char command[MaxTextExtent], *density, filename[MaxTextExtent], geometry[MaxTextExtent], input_filename[MaxTextExtent], message[MaxTextExtent], *options, postscript_filename[MaxTextExtent]; const char *option; const DelegateInfo *delegate_info; GeometryInfo geometry_info; Image *image, *next, *postscript_image; ImageInfo *read_info; int c, file; MagickBooleanType cmyk, fitPage, skip, status; MagickStatusType flags; PointInfo delta, resolution; RectangleInfo page; register char *p; register ssize_t i; SegmentInfo bounds, hires_bounds; short int hex_digits[256]; size_t length, priority; ssize_t count; StringInfo *profile; unsigned long columns, extent, language_level, pages, rows, scene, spotcolor; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } status=AcquireUniqueSymbolicLink(image_info->filename,input_filename); if (status == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToCreateTemporaryFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } /* Initialize hex values. */ (void) ResetMagickMemory(hex_digits,0,sizeof(hex_digits)); hex_digits[(int) '0']=0; hex_digits[(int) '1']=1; hex_digits[(int) '2']=2; hex_digits[(int) '3']=3; hex_digits[(int) '4']=4; hex_digits[(int) '5']=5; hex_digits[(int) '6']=6; hex_digits[(int) '7']=7; hex_digits[(int) '8']=8; hex_digits[(int) '9']=9; hex_digits[(int) 'a']=10; hex_digits[(int) 'b']=11; hex_digits[(int) 'c']=12; hex_digits[(int) 'd']=13; hex_digits[(int) 'e']=14; hex_digits[(int) 'f']=15; hex_digits[(int) 'A']=10; hex_digits[(int) 'B']=11; hex_digits[(int) 'C']=12; hex_digits[(int) 'D']=13; hex_digits[(int) 'E']=14; hex_digits[(int) 'F']=15; /* Set the page density. */ delta.x=DefaultResolution; delta.y=DefaultResolution; if ((image->x_resolution == 0.0) || (image->y_resolution == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); image->x_resolution=geometry_info.rho; image->y_resolution=geometry_info.sigma; if ((flags & SigmaValue) == 0) image->y_resolution=image->x_resolution; } (void) ParseAbsoluteGeometry(PSPageGeometry,&page); if (image_info->page != (char *) NULL) (void) ParseAbsoluteGeometry(image_info->page,&page); resolution.x=image->x_resolution; resolution.y=image->y_resolution; page.width=(size_t) ceil((double) (page.width*resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) (page.height*resolution.y/delta.y)-0.5); /* Determine page geometry from the Postscript bounding box. */ (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); (void) ResetMagickMemory(command,0,sizeof(command)); cmyk=image_info->colorspace == CMYKColorspace ? MagickTrue : MagickFalse; (void) ResetMagickMemory(&hires_bounds,0,sizeof(hires_bounds)); priority=0; columns=0; rows=0; extent=0; spotcolor=0; language_level=1; skip=MagickFalse; pages=(~0UL); p=command; for (c=ReadBlobByte(image); c != EOF; c=ReadBlobByte(image)) { /* Note document structuring comments. */ *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; /* Skip %%BeginDocument thru %%EndDocument. */ if (LocaleNCompare(BeginDocument,command,strlen(BeginDocument)) == 0) skip=MagickTrue; if (LocaleNCompare(EndDocument,command,strlen(EndDocument)) == 0) skip=MagickFalse; if (skip != MagickFalse) continue; if (LocaleNCompare(PostscriptLevel,command,strlen(PostscriptLevel)) == 0) { (void) SetImageProperty(image,"ps:Level",command+4); if (GlobExpression(command,"*EPSF-*",MagickTrue) != MagickFalse) pages=1; } if (LocaleNCompare(LanguageLevel,command,strlen(LanguageLevel)) == 0) (void) sscanf(command,LanguageLevel " %lu",&language_level); if (LocaleNCompare(Pages,command,strlen(Pages)) == 0) (void) sscanf(command,Pages " %lu",&pages); if (LocaleNCompare(ImageData,command,strlen(ImageData)) == 0) (void) sscanf(command,ImageData " %lu %lu",&columns,&rows); if (LocaleNCompare(ICCProfile,command,strlen(ICCProfile)) == 0) { unsigned char *datum; /* Read ICC profile. */ profile=AcquireStringInfo(MaxTextExtent); datum=GetStringInfoDatum(profile); for (i=0; (c=ProfileInteger(image,hex_digits)) != EOF; i++) { if (i >= (ssize_t) GetStringInfoLength(profile)) { SetStringInfoLength(profile,(size_t) i << 1); datum=GetStringInfoDatum(profile); } datum[i]=(unsigned char) c; } SetStringInfoLength(profile,(size_t) i+1); (void) SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); continue; } if (LocaleNCompare(PhotoshopProfile,command,strlen(PhotoshopProfile)) == 0) { unsigned char *p; /* Read Photoshop profile. */ count=(ssize_t) sscanf(command,PhotoshopProfile " %lu",&extent); if (count != 1) continue; length=extent; if (length > GetBlobSize(image)) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); profile=BlobToStringInfo((const void *) NULL,length); if (profile != (StringInfo *) NULL) { p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) length; i++) *p++=(unsigned char) ProfileInteger(image,hex_digits); (void) SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); } continue; } if (LocaleNCompare(BeginXMPPacket,command,strlen(BeginXMPPacket)) == 0) { register size_t i; /* Read XMP profile. */ p=command; profile=StringToStringInfo(command); for (i=GetStringInfoLength(profile)-1; c != EOF; i++) { SetStringInfoLength(profile,i+1); c=ReadBlobByte(image); GetStringInfoDatum(profile)[i]=(unsigned char) c; *p++=(char) c; if ((strchr("\n\r%",c) == (char *) NULL) && ((size_t) (p-command) < (MaxTextExtent-1))) continue; *p='\0'; p=command; if (LocaleNCompare(EndXMPPacket,command,strlen(EndXMPPacket)) == 0) break; } SetStringInfoLength(profile,i); (void) SetImageProfile(image,"xmp",profile); profile=DestroyStringInfo(profile); continue; } /* Is this a CMYK document? */ length=strlen(DocumentProcessColors); if (LocaleNCompare(DocumentProcessColors,command,length) == 0) { if ((GlobExpression(command,"*Cyan*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Magenta*",MagickTrue) != MagickFalse) || (GlobExpression(command,"*Yellow*",MagickTrue) != MagickFalse)) cmyk=MagickTrue; } if (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) cmyk=MagickTrue; if (LocaleNCompare(CMYKProcessColor,command,strlen(CMYKProcessColor)) == 0) cmyk=MagickTrue; length=strlen(DocumentCustomColors); if ((LocaleNCompare(DocumentCustomColors,command,length) == 0) || (LocaleNCompare(CMYKCustomColor,command,strlen(CMYKCustomColor)) == 0) || (LocaleNCompare(SpotColor,command,strlen(SpotColor)) == 0)) { char property[MaxTextExtent], *value; register char *p; /* Note spot names. */ (void) FormatLocaleString(property,MaxTextExtent,"ps:SpotColor-%.20g", (double) (spotcolor++)); for (p=command; *p != '\0'; p++) if (isspace((int) (unsigned char) *p) != 0) break; value=AcquireString(p); (void) SubstituteString(&value,"(",""); (void) SubstituteString(&value,")",""); (void) StripString(value); (void) SetImageProperty(image,property,value); value=DestroyString(value); continue; } if (image_info->page != (char *) NULL) continue; /* Note region defined by bounding box. */ count=0; i=0; if (LocaleNCompare(BoundingBox,command,strlen(BoundingBox)) == 0) { count=(ssize_t) sscanf(command,BoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=2; } if (LocaleNCompare(DocumentMedia,command,strlen(DocumentMedia)) == 0) { count=(ssize_t) sscanf(command,DocumentMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(HiResBoundingBox,command,strlen(HiResBoundingBox)) == 0) { count=(ssize_t) sscanf(command,HiResBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=3; } if (LocaleNCompare(PageBoundingBox,command,strlen(PageBoundingBox)) == 0) { count=(ssize_t) sscanf(command,PageBoundingBox " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if (LocaleNCompare(PageMedia,command,strlen(PageMedia)) == 0) { count=(ssize_t) sscanf(command,PageMedia " %lf %lf %lf %lf", &bounds.x1,&bounds.y1,&bounds.x2,&bounds.y2); i=1; } if ((count != 4) || (i < (ssize_t) priority)) continue; if ((fabs(bounds.x2-bounds.x1) <= fabs(hires_bounds.x2-hires_bounds.x1)) || (fabs(bounds.y2-bounds.y1) <= fabs(hires_bounds.y2-hires_bounds.y1))) if (i == (ssize_t) priority) continue; hires_bounds=bounds; priority=i; } if ((fabs(hires_bounds.x2-hires_bounds.x1) >= MagickEpsilon) && (fabs(hires_bounds.y2-hires_bounds.y1) >= MagickEpsilon)) { /* Set Postscript render geometry. */ (void) FormatLocaleString(geometry,MaxTextExtent,"%gx%g%+.15g%+.15g", hires_bounds.x2-hires_bounds.x1,hires_bounds.y2-hires_bounds.y1, hires_bounds.x1,hires_bounds.y1); (void) SetImageProperty(image,"ps:HiResBoundingBox",geometry); page.width=(size_t) ceil((double) ((hires_bounds.x2-hires_bounds.x1)* resolution.x/delta.x)-0.5); page.height=(size_t) ceil((double) ((hires_bounds.y2-hires_bounds.y1)* resolution.y/delta.y)-0.5); } fitPage=MagickFalse; option=GetImageOption(image_info,"eps:fit-page"); if (option != (char *) NULL) { char *geometry; MagickStatusType flags; geometry=GetPageGeometry(option); flags=ParseMetaGeometry(geometry,&page.x,&page.y,&page.width,&page.height); if (flags == NoValue) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",option); image=DestroyImage(image); return((Image *) NULL); } page.width=(size_t) ceil((double) (page.width*image->x_resolution/delta.x) -0.5); page.height=(size_t) ceil((double) (page.height*image->y_resolution/ delta.y) -0.5); geometry=DestroyString(geometry); fitPage=MagickTrue; } (void) CloseBlob(image); if (IssRGBCompatibleColorspace(image_info->colorspace) != MagickFalse) cmyk=MagickFalse; /* Create Ghostscript control file. */ file=AcquireUniqueFileResource(postscript_filename); if (file == -1) { ThrowFileException(&image->exception,FileOpenError,"UnableToOpenFile", image_info->filename); image=DestroyImageList(image); return((Image *) NULL); } (void) CopyMagickString(command,"/setpagedevice {pop} bind 1 index where {" "dup wcheck {3 1 roll put} {pop def} ifelse} {def} ifelse\n" "<</UseCIEColor true>>setpagedevice\n",MaxTextExtent); count=write(file,command,(unsigned int) strlen(command)); if (image_info->page == (char *) NULL) { char translate_geometry[MaxTextExtent]; (void) FormatLocaleString(translate_geometry,MaxTextExtent, "%g %g translate\n",-hires_bounds.x1,-hires_bounds.y1); count=write(file,translate_geometry,(unsigned int) strlen(translate_geometry)); } file=close(file)-1; /* Render Postscript with the Ghostscript delegate. */ if (image_info->monochrome != MagickFalse) delegate_info=GetDelegateInfo("ps:mono",(char *) NULL,exception); else if (cmyk != MagickFalse) delegate_info=GetDelegateInfo("ps:cmyk",(char *) NULL,exception); else delegate_info=GetDelegateInfo("ps:alpha",(char *) NULL,exception); if (delegate_info == (const DelegateInfo *) NULL) { (void) RelinquishUniqueFileResource(postscript_filename); image=DestroyImageList(image); return((Image *) NULL); } density=AcquireString(""); options=AcquireString(""); (void) FormatLocaleString(density,MaxTextExtent,"%gx%g",resolution.x, resolution.y); (void) FormatLocaleString(options,MaxTextExtent,"-g%.20gx%.20g ",(double) page.width,(double) page.height); read_info=CloneImageInfo(image_info); *read_info->magick='\0'; if (read_info->number_scenes != 0) { char pages[MaxTextExtent]; (void) FormatLocaleString(pages,MaxTextExtent,"-dFirstPage=%.20g " "-dLastPage=%.20g ",(double) read_info->scene+1,(double) (read_info->scene+read_info->number_scenes)); (void) ConcatenateMagickString(options,pages,MaxTextExtent); read_info->number_scenes=0; if (read_info->scenes != (char *) NULL) *read_info->scenes='\0'; } if (*image_info->magick == 'E') { option=GetImageOption(image_info,"eps:use-cropbox"); if ((option == (const char *) NULL) || (IsStringTrue(option) != MagickFalse)) (void) ConcatenateMagickString(options,"-dEPSCrop ",MaxTextExtent); if (fitPage != MagickFalse) (void) ConcatenateMagickString(options,"-dEPSFitPage ",MaxTextExtent); } (void) CopyMagickString(filename,read_info->filename,MaxTextExtent); (void) AcquireUniqueFilename(filename); (void) RelinquishUniqueFileResource(filename); (void) ConcatenateMagickString(filename,"%d",MaxTextExtent); (void) FormatLocaleString(command,MaxTextExtent, GetDelegateCommands(delegate_info), read_info->antialias != MagickFalse ? 4 : 1, read_info->antialias != MagickFalse ? 4 : 1,density,options,filename, postscript_filename,input_filename); options=DestroyString(options); density=DestroyString(density); *message='\0'; status=InvokePostscriptDelegate(read_info->verbose,command,message,exception); (void) InterpretImageFilename(image_info,image,filename,1, read_info->filename); if ((status == MagickFalse) || (IsPostscriptRendered(read_info->filename) == MagickFalse)) { (void) ConcatenateMagickString(command," -c showpage",MaxTextExtent); status=InvokePostscriptDelegate(read_info->verbose,command,message, exception); } (void) RelinquishUniqueFileResource(postscript_filename); (void) RelinquishUniqueFileResource(input_filename); postscript_image=(Image *) NULL; if (status == MagickFalse) for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; (void) RelinquishUniqueFileResource(read_info->filename); } else for (i=1; ; i++) { (void) InterpretImageFilename(image_info,image,filename,(int) i, read_info->filename); if (IsPostscriptRendered(read_info->filename) == MagickFalse) break; read_info->blob=NULL; read_info->length=0; next=ReadImage(read_info,exception); (void) RelinquishUniqueFileResource(read_info->filename); if (next == (Image *) NULL) break; AppendImageToList(&postscript_image,next); } (void) RelinquishUniqueFileResource(read_info->filename); read_info=DestroyImageInfo(read_info); if (postscript_image == (Image *) NULL) { if (*message != '\0') (void) ThrowMagickException(exception,GetMagickModule(),DelegateError, "PostscriptDelegateFailed","`%s'",message); image=DestroyImageList(image); return((Image *) NULL); } if (LocaleCompare(postscript_image->magick,"BMP") == 0) { Image *cmyk_image; cmyk_image=ConsolidateCMYKImages(postscript_image,exception); if (cmyk_image != (Image *) NULL) { postscript_image=DestroyImageList(postscript_image); postscript_image=cmyk_image; } } if (image_info->number_scenes != 0) { Image *clone_image; register ssize_t i; /* Add place holder images to meet the subimage specification requirement. */ for (i=0; i < (ssize_t) image_info->scene; i++) { clone_image=CloneImage(postscript_image,1,1,MagickTrue,exception); if (clone_image != (Image *) NULL) PrependImageToList(&postscript_image,clone_image); } } do { (void) CopyMagickString(postscript_image->filename,filename,MaxTextExtent); (void) CopyMagickString(postscript_image->magick,image->magick, MaxTextExtent); if (columns != 0) postscript_image->magick_columns=columns; if (rows != 0) postscript_image->magick_rows=rows; postscript_image->page=page; (void) CloneImageProfiles(postscript_image,image); (void) CloneImageProperties(postscript_image,image); next=SyncNextImageInList(postscript_image); if (next != (Image *) NULL) postscript_image=next; } while (next != (Image *) NULL); image=DestroyImageList(image); scene=0; for (next=GetFirstImageInList(postscript_image); next != (Image *) NULL; ) { next->scene=scene++; next=GetNextImageInList(next); } return(GetFirstImageInList(postscript_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterPSImage() adds properties for the PS image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterPSImage method is: % % size_t RegisterPSImage(void) % */ ModuleExport size_t RegisterPSImage(void) { MagickInfo *entry; entry=SetMagickInfo("EPI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->magick=(IsImageFormatHandler *) IsPS; entry->seekable_stream=MagickTrue; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSF"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("Encapsulated PostScript"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("EPSI"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->adjoin=MagickFalse; entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString( "Encapsulated PostScript Interchange format"); entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PS"); entry->decoder=(DecodeImageHandler *) ReadPSImage; entry->encoder=(EncodeImageHandler *) WritePSImage; entry->seekable_stream=MagickTrue; entry->magick=(IsImageFormatHandler *) IsPS; entry->mime_type=ConstantString("application/postscript"); entry->module=ConstantString("PS"); entry->blob_support=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString("PostScript"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterPSImage() removes format registrations made by the % PS module from the list of supported formats. % % The format of the UnregisterPSImage method is: % % UnregisterPSImage(void) % */ ModuleExport void UnregisterPSImage(void) { (void) UnregisterMagickInfo("EPI"); (void) UnregisterMagickInfo("EPS"); (void) UnregisterMagickInfo("EPSF"); (void) UnregisterMagickInfo("EPSI"); (void) UnregisterMagickInfo("PS"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e P S I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePSImage translates an image to encapsulated Postscript % Level I for printing. If the supplied geometry is null, the image is % centered on the Postscript page. Otherwise, the image is positioned as % specified by the geometry. % % The format of the WritePSImage method is: % % MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the image. % */ static inline unsigned char *PopHexPixel(const char *const *hex_digits, const size_t pixel,unsigned char *pixels) { register const char *hex; hex=hex_digits[pixel]; *pixels++=(unsigned char) (*hex++); *pixels++=(unsigned char) (*hex); return(pixels); } static MagickBooleanType WritePSImage(const ImageInfo *image_info,Image *image) { #define WriteRunlengthPacket(image,pixel,length,p) \ { \ if ((image->matte != MagickFalse) && (length != 0) &&\ (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) \ { \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ q=PopHexPixel(hex_digits,0xff,q); \ } \ else \ { \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.red),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.green),q); \ q=PopHexPixel(hex_digits,ScaleQuantumToChar(pixel.blue),q); \ } \ q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); \ } static const char *const hex_digits[] = { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B", "1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C", "3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D", "5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E", "7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F", "A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA", "AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0", "C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB", "CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1", "E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC", "ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF", (const char *) NULL }, *const PostscriptProlog[]= { "%%BeginProlog", "%", "% Display a color image. The image is displayed in color on", "% Postscript viewers or printers that support color, otherwise", "% it is displayed as grayscale.", "%", "/DirectClassPacket", "{", " %", " % Get a DirectClass packet.", " %", " % Parameters:", " % red.", " % green.", " % blue.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/DirectClassImage", "{", " %", " % Display a DirectClass image.", " %", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { DirectClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayDirectClassPacket } image", " } ifelse", "} bind def", "", "/GrayDirectClassPacket", "{", " %", " % Get a DirectClass packet; convert to grayscale.", " %", " % Parameters:", " % red", " % green", " % blue", " % length: number of pixels minus one of this color (optional).", " %", " currentfile color_packet readhexstring pop pop", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/GrayPseudoClassPacket", "{", " %", " % Get a PseudoClass packet; convert to grayscale.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " color_packet 0 get 0.299 mul", " color_packet 1 get 0.587 mul add", " color_packet 2 get 0.114 mul add", " cvi", " /gray_packet exch def", " compression 0 eq", " {", " /number_pixels 1 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add def", " } ifelse", " 0 1 number_pixels 1 sub", " {", " pixels exch gray_packet put", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassPacket", "{", " %", " % Get a PseudoClass packet.", " %", " % Parameters:", " % index: index into the colormap.", " % length: number of pixels minus one of this color (optional).", " %", " currentfile byte readhexstring pop 0 get", " /offset exch 3 mul def", " /color_packet colormap offset 3 getinterval def", " compression 0 eq", " {", " /number_pixels 3 def", " }", " {", " currentfile byte readhexstring pop 0 get", " /number_pixels exch 1 add 3 mul def", " } ifelse", " 0 3 number_pixels 1 sub", " {", " pixels exch color_packet putinterval", " } for", " pixels 0 number_pixels getinterval", "} bind def", "", "/PseudoClassImage", "{", " %", " % Display a PseudoClass image.", " %", " % Parameters:", " % class: 0-PseudoClass or 1-Grayscale.", " %", " currentfile buffer readline pop", " token pop /class exch def pop", " class 0 gt", " {", " currentfile buffer readline pop", " token pop /depth exch def pop", " /grays columns 8 add depth sub depth mul 8 idiv string def", " columns rows depth", " [", " columns 0 0", " rows neg 0 rows", " ]", " { currentfile grays readhexstring pop } image", " }", " {", " %", " % Parameters:", " % colors: number of colors in the colormap.", " % colormap: red, green, blue color packets.", " %", " currentfile buffer readline pop", " token pop /colors exch def pop", " /colors colors 3 mul def", " /colormap colors string def", " currentfile colormap readhexstring pop pop", " systemdict /colorimage known", " {", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { PseudoClassPacket } false 3 colorimage", " }", " {", " %", " % No colorimage operator; convert to grayscale.", " %", " columns rows 8", " [", " columns 0 0", " rows neg 0 rows", " ]", " { GrayPseudoClassPacket } image", " } ifelse", " } ifelse", "} bind def", "", "/DisplayImage", "{", " %", " % Display a DirectClass or PseudoClass image.", " %", " % Parameters:", " % x & y translation.", " % x & y scale.", " % label pointsize.", " % image label.", " % image columns & rows.", " % class: 0-DirectClass or 1-PseudoClass.", " % compression: 0-none or 1-RunlengthEncoded.", " % hex color packets.", " %", " gsave", " /buffer 512 string def", " /byte 1 string def", " /color_packet 3 string def", " /pixels 768 string def", "", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " x y translate", " currentfile buffer readline pop", " token pop /x exch def", " token pop /y exch def pop", " currentfile buffer readline pop", " token pop /pointsize exch def pop", (const char *) NULL }, *const PostscriptEpilog[]= { " x y scale", " currentfile buffer readline pop", " token pop /columns exch def", " token pop /rows exch def pop", " currentfile buffer readline pop", " token pop /class exch def pop", " currentfile buffer readline pop", " token pop /compression exch def pop", " class 0 gt { PseudoClassImage } { DirectClassImage } ifelse", " grestore", (const char *) NULL }; char buffer[MaxTextExtent], date[MaxTextExtent], **labels, page_geometry[MaxTextExtent]; CompressionType compression; const char *const *s, *value; const StringInfo *profile; double pointsize; GeometryInfo geometry_info; IndexPacket index; MagickBooleanType status; MagickOffsetType scene; MagickStatusType flags; PixelPacket pixel; PointInfo delta, resolution, scale; RectangleInfo geometry, media_info, page_info; register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t i, x; register unsigned char *q; SegmentInfo bounds; size_t bit, byte, length, page, text_size; ssize_t j, y; time_t timer; unsigned char pixels[2048]; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=OpenBlob(image_info,image,WriteBinaryBlobMode,&image->exception); if (status == MagickFalse) return(status); (void) ResetMagickMemory(&bounds,0,sizeof(bounds)); compression=image->compression; if (image_info->compression != UndefinedCompression) compression=image_info->compression; page=1; scene=0; do { /* Scale relative to dots-per-inch. */ if (image->colorspace != CMYKColorspace) (void) TransformImageColorspace(image,sRGBColorspace); delta.x=DefaultResolution; delta.y=DefaultResolution; resolution.x=image->x_resolution; resolution.y=image->y_resolution; if ((resolution.x == 0.0) || (resolution.y == 0.0)) { flags=ParseGeometry(PSDensityGeometry,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image_info->density != (char *) NULL) { flags=ParseGeometry(image_info->density,&geometry_info); resolution.x=geometry_info.rho; resolution.y=geometry_info.sigma; if ((flags & SigmaValue) == 0) resolution.y=resolution.x; } if (image->units == PixelsPerCentimeterResolution) { resolution.x=(double) ((size_t) (100.0*2.54*resolution.x+0.5)/100.0); resolution.y=(double) ((size_t) (100.0*2.54*resolution.y+0.5)/100.0); } SetGeometry(image,&geometry); (void) FormatLocaleString(page_geometry,MaxTextExtent,"%.20gx%.20g", (double) image->columns,(double) image->rows); if (image_info->page != (char *) NULL) (void) CopyMagickString(page_geometry,image_info->page,MaxTextExtent); else if ((image->page.width != 0) && (image->page.height != 0)) (void) FormatLocaleString(page_geometry,MaxTextExtent, "%.20gx%.20g%+.20g%+.20g",(double) image->page.width,(double) image->page.height,(double) image->page.x,(double) image->page.y); else if ((image->gravity != UndefinedGravity) && (LocaleCompare(image_info->magick,"PS") == 0)) (void) CopyMagickString(page_geometry,PSPageGeometry,MaxTextExtent); (void) ConcatenateMagickString(page_geometry,">",MaxTextExtent); (void) ParseMetaGeometry(page_geometry,&geometry.x,&geometry.y, &geometry.width,&geometry.height); scale.x=(double) (geometry.width*delta.x)/resolution.x; geometry.width=(size_t) floor(scale.x+0.5); scale.y=(double) (geometry.height*delta.y)/resolution.y; geometry.height=(size_t) floor(scale.y+0.5); (void) ParseAbsoluteGeometry(page_geometry,&media_info); (void) ParseGravityGeometry(image,page_geometry,&page_info, &image->exception); if (image->gravity != UndefinedGravity) { geometry.x=(-page_info.x); geometry.y=(ssize_t) (media_info.height+page_info.y-image->rows); } pointsize=12.0; if (image_info->pointsize != 0.0) pointsize=image_info->pointsize; text_size=0; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) text_size=(size_t) (MultilineCensus(value)*pointsize+12); if (page == 1) { /* Output Postscript header. */ if (LocaleCompare(image_info->magick,"PS") == 0) (void) CopyMagickString(buffer,"%!PS-Adobe-3.0\n",MaxTextExtent); else (void) CopyMagickString(buffer,"%!PS-Adobe-3.0 EPSF-3.0\n", MaxTextExtent); (void) WriteBlobString(image,buffer); (void) WriteBlobString(image,"%%Creator: (ImageMagick)\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Title: (%s)\n", image->filename); (void) WriteBlobString(image,buffer); timer=time((time_t *) NULL); (void) FormatMagickTime(timer,MaxTextExtent,date); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%CreationDate: (%s)\n",date); (void) WriteBlobString(image,buffer); bounds.x1=(double) geometry.x; bounds.y1=(double) geometry.y; bounds.x2=(double) geometry.x+scale.x; bounds.y2=(double) geometry.y+(geometry.height+text_size); if ((image_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) (void) CopyMagickString(buffer,"%%%%BoundingBox: (atend)\n", MaxTextExtent); else { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); } (void) WriteBlobString(image,buffer); profile=GetImageProfile(image,"8bim"); if (profile != (StringInfo *) NULL) { /* Embed Photoshop profile. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%%BeginPhotoshop: %.20g",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) { if ((i % 32) == 0) (void) WriteBlobString(image,"\n% "); (void) FormatLocaleString(buffer,MaxTextExtent,"%02X", (unsigned int) (GetStringInfoDatum(profile)[i] & 0xff)); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"\n%EndPhotoshop\n"); } profile=GetImageProfile(image,"xmp"); DisableMSCWarning(4127) if (0 && (profile != (StringInfo *) NULL)) RestoreMSCWarning { /* Embed XML profile. */ (void) WriteBlobString(image,"\n%begin_xml_code\n"); (void) FormatLocaleString(buffer,MaxTextExtent, "\n%%begin_xml_packet: %.20g\n",(double) GetStringInfoLength(profile)); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) (void) WriteBlobByte(image,GetStringInfoDatum(profile)[i]); (void) WriteBlobString(image,"\n%end_xml_packet\n%end_xml_code\n"); } value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image, "%%DocumentNeededResources: font Times-Roman\n"); (void) WriteBlobString(image,"%%DocumentData: Clean7Bit\n"); (void) WriteBlobString(image,"%%LanguageLevel: 1\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"%%Pages: 1\n"); else { /* Compute the number of pages. */ (void) WriteBlobString(image,"%%Orientation: Portrait\n"); (void) WriteBlobString(image,"%%PageOrder: Ascend\n"); (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Pages: %.20g\n", image_info->adjoin != MagickFalse ? (double) GetImageListLength(image) : 1.0); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EndComments\n"); (void) WriteBlobString(image,"\n%%BeginDefaults\n"); (void) WriteBlobString(image,"%%EndDefaults\n\n"); if ((LocaleCompare(image_info->magick,"EPI") == 0) || (LocaleCompare(image_info->magick,"EPSI") == 0) || (LocaleCompare(image_info->magick,"EPT") == 0)) { Image *preview_image; Quantum pixel; register ssize_t x; ssize_t y; /* Create preview image. */ preview_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (preview_image == (Image *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BeginPreview: %.20g %.20g %.20g %.20g\n%% ",(double) preview_image->columns,(double) preview_image->rows,1.0, (double) ((((preview_image->columns+7) >> 3)*preview_image->rows+ 35)/36)); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(preview_image,0,y,preview_image->columns,1, &preview_image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(preview_image); bit=0; byte=0; for (x=0; x < (ssize_t) preview_image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; bit=0; byte=0; } } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; (void) WriteBlobString(image,"% "); }; }; } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } (void) WriteBlobString(image,"\n%%EndPreview\n"); preview_image=DestroyImage(preview_image); } /* Output Postscript commands. */ for (s=PostscriptProlog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } value=GetImageProperty(image,"label"); if (value != (const char *) NULL) { (void) WriteBlobString(image, " /Times-Roman findfont pointsize scalefont setfont\n"); for (j=(ssize_t) MultilineCensus(value)-1; j >= 0; j--) { (void) WriteBlobString(image," /label 512 string def\n"); (void) WriteBlobString(image, " currentfile label readline pop\n"); (void) FormatLocaleString(buffer,MaxTextExtent, " 0 y %g add moveto label show pop\n",j*pointsize+12); (void) WriteBlobString(image,buffer); } } for (s=PostscriptEpilog; *s != (char *) NULL; s++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s\n",*s); (void) WriteBlobString(image,buffer); } if (LocaleCompare(image_info->magick,"PS") == 0) (void) WriteBlobString(image," showpage\n"); (void) WriteBlobString(image,"} bind def\n"); (void) WriteBlobString(image,"%%EndProlog\n"); } (void) FormatLocaleString(buffer,MaxTextExtent,"%%%%Page: 1 %.20g\n", (double) (page++)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%PageBoundingBox: %.20g %.20g %.20g %.20g\n",(double) geometry.x, (double) geometry.y,geometry.x+(double) geometry.width,geometry.y+(double) (geometry.height+text_size)); (void) WriteBlobString(image,buffer); if ((double) geometry.x < bounds.x1) bounds.x1=(double) geometry.x; if ((double) geometry.y < bounds.y1) bounds.y1=(double) geometry.y; if ((double) (geometry.x+geometry.width-1) > bounds.x2) bounds.x2=(double) geometry.x+geometry.width-1; if ((double) (geometry.y+(geometry.height+text_size)-1) > bounds.y2) bounds.y2=(double) geometry.y+(geometry.height+text_size)-1; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) (void) WriteBlobString(image,"%%%%PageResources: font Times-Roman\n"); if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"userdict begin\n"); (void) WriteBlobString(image,"DisplayImage\n"); /* Output image data. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n%g %g\n%g\n", (double) geometry.x,(double) geometry.y,scale.x,scale.y,pointsize); (void) WriteBlobString(image,buffer); labels=(char **) NULL; value=GetImageProperty(image,"label"); if (value != (const char *) NULL) labels=StringToList(value); if (labels != (char **) NULL) { for (i=0; labels[i] != (char *) NULL; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%s \n", labels[i]); (void) WriteBlobString(image,buffer); labels[i]=DestroyString(labels[i]); } labels=(char **) RelinquishMagickMemory(labels); } (void) ResetMagickMemory(&pixel,0,sizeof(pixel)); pixel.opacity=(Quantum) TransparentOpacity; index=(IndexPacket) 0; x=0; if ((image_info->type != TrueColorType) && (SetImageGray(image,&image->exception) != MagickFalse)) { if (SetImageMonochrome(image,&image->exception) == MagickFalse) { Quantum pixel; /* Dump image as grayscale. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n1\n1\n1\n8\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { pixel=ScaleQuantumToChar(ClampToQuantum(GetPixelLuma(image,p))); q=PopHexPixel(hex_digits,(size_t) pixel,q); if ((q-pixels+8) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } else { ssize_t y; Quantum pixel; /* Dump image as bitmap. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n1\n1\n1\n1\n",(double) image->columns,(double) image->rows); (void) WriteBlobString(image,buffer); q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); bit=0; byte=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; pixel=ClampToQuantum(GetPixelLuma(image,p)); if (pixel >= (Quantum) (QuantumRange/2)) byte|=0x01; bit++; if (bit == 8) { q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; }; bit=0; byte=0; } p++; } if (bit != 0) { byte<<=(8-bit); q=PopHexPixel(hex_digits,byte,q); if ((q-pixels+2) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } }; if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } } } else if ((image->storage_class == DirectClass) || (image->colors > 256) || (image->matte != MagickFalse)) { /* Dump DirectClass image. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g %.20g\n0\n%d\n", (double) image->columns,(double) image->rows, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); switch (compression) { case RLECompression: { /* Dump runlength-encoded DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; pixel=(*p); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((GetPixelRed(p) == pixel.red) && (GetPixelGreen(p) == pixel.green) && (GetPixelBlue(p) == pixel.blue) && (GetPixelOpacity(p) == pixel.opacity) && (length < 255) && (x < (ssize_t) (image->columns-1))) length++; else { if (x > 0) { WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } pixel=(*p); p++; } WriteRunlengthPacket(image,pixel,length,p); if ((q-pixels+10) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed DirectColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { if ((image->matte != MagickFalse) && (GetPixelOpacity(p) == (Quantum) TransparentOpacity)) { q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); q=PopHexPixel(hex_digits,0xff,q); } else { q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelRed(p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelGreen(p)),q); q=PopHexPixel(hex_digits,ScaleQuantumToChar( GetPixelBlue(p)),q); } if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } else { /* Dump PseudoClass image. */ (void) FormatLocaleString(buffer,MaxTextExtent, "%.20g %.20g\n%d\n%d\n0\n",(double) image->columns,(double) image->rows,image->storage_class == PseudoClass ? 1 : 0, compression == RLECompression ? 1 : 0); (void) WriteBlobString(image,buffer); /* Dump number of colors and colormap. */ (void) FormatLocaleString(buffer,MaxTextExtent,"%.20g\n",(double) image->colors); (void) WriteBlobString(image,buffer); for (i=0; i < (ssize_t) image->colors; i++) { (void) FormatLocaleString(buffer,MaxTextExtent,"%02X%02X%02X\n", ScaleQuantumToChar(image->colormap[i].red), ScaleQuantumToChar(image->colormap[i].green), ScaleQuantumToChar(image->colormap[i].blue)); (void) WriteBlobString(image,buffer); } switch (compression) { case RLECompression: { /* Dump runlength-encoded PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); index=GetPixelIndex(indexes); length=255; for (x=0; x < (ssize_t) image->columns; x++) { if ((index == GetPixelIndex(indexes+x)) && (length < 255) && (x < ((ssize_t) image->columns-1))) length++; else { if (x > 0) { q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); i++; if ((q-pixels+6) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } } length=0; } index=GetPixelIndex(indexes+x); pixel.red=GetPixelRed(p); pixel.green=GetPixelGreen(p); pixel.blue=GetPixelBlue(p); pixel.opacity=GetPixelOpacity(p); p++; } q=PopHexPixel(hex_digits,(size_t) index,q); q=PopHexPixel(hex_digits,(size_t) MagickMin(length,0xff),q); if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } case NoCompression: default: { /* Dump uncompressed PseudoColor packets. */ q=pixels; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1, &image->exception); if (p == (const PixelPacket *) NULL) break; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { q=PopHexPixel(hex_digits,(size_t) GetPixelIndex( indexes+x),q); if ((q-pixels+4) >= 80) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); q=pixels; } p++; } if (image->previous == (Image *) NULL) { status=SetImageProgress(image,SaveImageTag, (MagickOffsetType) y,image->rows); if (status == MagickFalse) break; } } if (q != pixels) { *q++='\n'; (void) WriteBlob(image,q-pixels,pixels); } break; } } (void) WriteBlobByte(image,'\n'); } if (LocaleCompare(image_info->magick,"PS") != 0) (void) WriteBlobString(image,"end\n"); (void) WriteBlobString(image,"%%PageTrailer\n"); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); status=SetImageProgress(image,SaveImagesTag,scene++, GetImageListLength(image)); if (status == MagickFalse) break; } while (image_info->adjoin != MagickFalse); (void) WriteBlobString(image,"%%Trailer\n"); if (page > 2) { (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%BoundingBox: %.20g %.20g %.20g %.20g\n",ceil(bounds.x1-0.5), ceil(bounds.y1-0.5),floor(bounds.x2+0.5),floor(bounds.y2+0.5)); (void) WriteBlobString(image,buffer); (void) FormatLocaleString(buffer,MaxTextExtent, "%%%%HiResBoundingBox: %g %g %g %g\n",bounds.x1,bounds.y1, bounds.x2,bounds.y2); (void) WriteBlobString(image,buffer); } (void) WriteBlobString(image,"%%EOF\n"); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-834/c/good_2781_0
crossvul-cpp_data_good_2766_0
/* * Phantom Cine demuxer * Copyright (c) 2010-2011 Peter Ross <pross@xvid.org> * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /** * @file * Phantom Cine demuxer * @author Peter Ross <pross@xvid.org> */ #include "libavutil/intreadwrite.h" #include "libavcodec/bmp.h" #include "libavutil/intfloat.h" #include "avformat.h" #include "internal.h" typedef struct { uint64_t pts; } CineDemuxContext; /** Compression */ enum { CC_RGB = 0, /**< Gray */ CC_LEAD = 1, /**< LEAD (M)JPEG */ CC_UNINT = 2 /**< Uninterpolated color image (CFA field indicates color ordering) */ }; /** Color Filter Array */ enum { CFA_NONE = 0, /**< GRAY */ CFA_VRI = 1, /**< GBRG/RGGB */ CFA_VRIV6 = 2, /**< BGGR/GRBG */ CFA_BAYER = 3, /**< GB/RG */ CFA_BAYERFLIP = 4, /**< RG/GB */ }; #define CFA_TLGRAY 0x80000000U #define CFA_TRGRAY 0x40000000U #define CFA_BLGRAY 0x20000000U #define CFA_BRGRAY 0x10000000U static int cine_read_probe(AVProbeData *p) { int HeaderSize; if (p->buf[0] == 'C' && p->buf[1] == 'I' && // Type (HeaderSize = AV_RL16(p->buf + 2)) >= 0x2C && // HeaderSize AV_RL16(p->buf + 4) <= CC_UNINT && // Compression AV_RL16(p->buf + 6) <= 1 && // Version AV_RL32(p->buf + 20) && // ImageCount AV_RL32(p->buf + 24) >= HeaderSize && // OffImageHeader AV_RL32(p->buf + 28) >= HeaderSize && // OffSetup AV_RL32(p->buf + 32) >= HeaderSize) // OffImageOffsets return AVPROBE_SCORE_MAX; return 0; } static int set_metadata_int(AVDictionary **dict, const char *key, int value, int allow_zero) { if (value || allow_zero) { return av_dict_set_int(dict, key, value, 0); } return 0; } static int set_metadata_float(AVDictionary **dict, const char *key, float value, int allow_zero) { if (value != 0 || allow_zero) { char tmp[64]; snprintf(tmp, sizeof(tmp), "%f", value); return av_dict_set(dict, key, tmp, 0); } return 0; } static int cine_read_header(AVFormatContext *avctx) { AVIOContext *pb = avctx->pb; AVStream *st; unsigned int version, compression, offImageHeader, offSetup, offImageOffsets, biBitCount, length, CFA; int vflip; char *description; uint64_t i; st = avformat_new_stream(avctx, NULL); if (!st) return AVERROR(ENOMEM); st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_RAWVIDEO; st->codecpar->codec_tag = 0; /* CINEFILEHEADER structure */ avio_skip(pb, 4); // Type, Headersize compression = avio_rl16(pb); version = avio_rl16(pb); if (version != 1) { avpriv_request_sample(avctx, "unknown version %i", version); return AVERROR_INVALIDDATA; } avio_skip(pb, 12); // FirstMovieImage, TotalImageCount, FirstImageNumber st->duration = avio_rl32(pb); offImageHeader = avio_rl32(pb); offSetup = avio_rl32(pb); offImageOffsets = avio_rl32(pb); avio_skip(pb, 8); // TriggerTime /* BITMAPINFOHEADER structure */ avio_seek(pb, offImageHeader, SEEK_SET); avio_skip(pb, 4); //biSize st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); if (avio_rl16(pb) != 1) // biPlanes return AVERROR_INVALIDDATA; biBitCount = avio_rl16(pb); if (biBitCount != 8 && biBitCount != 16 && biBitCount != 24 && biBitCount != 48) { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } switch (avio_rl32(pb)) { case BMP_RGB: vflip = 0; break; case 0x100: /* BI_PACKED */ st->codecpar->codec_tag = MKTAG('B', 'I', 'T', 0); vflip = 1; break; default: avpriv_request_sample(avctx, "unknown bitmap compression"); return AVERROR_INVALIDDATA; } avio_skip(pb, 4); // biSizeImage /* parse SETUP structure */ avio_seek(pb, offSetup, SEEK_SET); avio_skip(pb, 140); // FrameRatae16 .. descriptionOld if (avio_rl16(pb) != 0x5453) return AVERROR_INVALIDDATA; length = avio_rl16(pb); if (length < 0x163C) { avpriv_request_sample(avctx, "short SETUP header"); return AVERROR_INVALIDDATA; } avio_skip(pb, 616); // Binning .. bFlipH if (!avio_rl32(pb) ^ vflip) { st->codecpar->extradata = av_strdup("BottomUp"); st->codecpar->extradata_size = 9; } avio_skip(pb, 4); // Grid avpriv_set_pts_info(st, 64, 1, avio_rl32(pb)); avio_skip(pb, 20); // Shutter .. bEnableColor set_metadata_int(&st->metadata, "camera_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "firmware_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "software_version", avio_rl32(pb), 0); set_metadata_int(&st->metadata, "recording_timezone", avio_rl32(pb), 0); CFA = avio_rl32(pb); set_metadata_int(&st->metadata, "brightness", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "contrast", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "gamma", avio_rl32(pb), 1); avio_skip(pb, 12 + 16); // Reserved1 .. AutoExpRect set_metadata_float(&st->metadata, "wbgain[0].r", av_int2float(avio_rl32(pb)), 1); set_metadata_float(&st->metadata, "wbgain[0].b", av_int2float(avio_rl32(pb)), 1); avio_skip(pb, 36); // WBGain[1].. WBView st->codecpar->bits_per_coded_sample = avio_rl32(pb); if (compression == CC_RGB) { if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_GRAY8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_GRAY16LE; } else if (biBitCount == 24) { st->codecpar->format = AV_PIX_FMT_BGR24; } else if (biBitCount == 48) { st->codecpar->format = AV_PIX_FMT_BGR48LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } } else if (compression == CC_UNINT) { switch (CFA & 0xFFFFFF) { case CFA_BAYER: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_GBRG16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; case CFA_BAYERFLIP: if (biBitCount == 8) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB8; } else if (biBitCount == 16) { st->codecpar->format = AV_PIX_FMT_BAYER_RGGB16LE; } else { avpriv_request_sample(avctx, "unsupported biBitCount %i", biBitCount); return AVERROR_INVALIDDATA; } break; default: avpriv_request_sample(avctx, "unsupported Color Field Array (CFA) %i", CFA & 0xFFFFFF); return AVERROR_INVALIDDATA; } } else { //CC_LEAD avpriv_request_sample(avctx, "unsupported compression %i", compression); return AVERROR_INVALIDDATA; } avio_skip(pb, 668); // Conv8Min ... Sensor set_metadata_int(&st->metadata, "shutter_ns", avio_rl32(pb), 0); avio_skip(pb, 24); // EDRShutterNs ... ImHeightAcq #define DESCRIPTION_SIZE 4096 description = av_malloc(DESCRIPTION_SIZE + 1); if (!description) return AVERROR(ENOMEM); i = avio_get_str(pb, DESCRIPTION_SIZE, description, DESCRIPTION_SIZE + 1); if (i < DESCRIPTION_SIZE) avio_skip(pb, DESCRIPTION_SIZE - i); if (description[0]) av_dict_set(&st->metadata, "description", description, AV_DICT_DONT_STRDUP_VAL); else av_free(description); avio_skip(pb, 1176); // RisingEdge ... cmUser set_metadata_int(&st->metadata, "enable_crop", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_left", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_top", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_right", avio_rl32(pb), 1); set_metadata_int(&st->metadata, "crop_bottom", avio_rl32(pb), 1); /* parse image offsets */ avio_seek(pb, offImageOffsets, SEEK_SET); for (i = 0; i < st->duration; i++) { if (avio_feof(pb)) return AVERROR_INVALIDDATA; av_add_index_entry(st, avio_rl64(pb), i, 0, 0, AVINDEX_KEYFRAME); } return 0; } static int cine_read_packet(AVFormatContext *avctx, AVPacket *pkt) { CineDemuxContext *cine = avctx->priv_data; AVStream *st = avctx->streams[0]; AVIOContext *pb = avctx->pb; int n, size, ret; if (cine->pts >= st->duration) return AVERROR_EOF; avio_seek(pb, st->index_entries[cine->pts].pos, SEEK_SET); n = avio_rl32(pb); if (n < 8) return AVERROR_INVALIDDATA; avio_skip(pb, n - 8); size = avio_rl32(pb); ret = av_get_packet(pb, pkt, size); if (ret < 0) return ret; pkt->pts = cine->pts++; pkt->stream_index = 0; pkt->flags |= AV_PKT_FLAG_KEY; return 0; } static int cine_read_seek(AVFormatContext *avctx, int stream_index, int64_t timestamp, int flags) { CineDemuxContext *cine = avctx->priv_data; if ((flags & AVSEEK_FLAG_FRAME) || (flags & AVSEEK_FLAG_BYTE)) return AVERROR(ENOSYS); if (!(avctx->pb->seekable & AVIO_SEEKABLE_NORMAL)) return AVERROR(EIO); cine->pts = timestamp; return 0; } AVInputFormat ff_cine_demuxer = { .name = "cine", .long_name = NULL_IF_CONFIG_SMALL("Phantom Cine"), .priv_data_size = sizeof(CineDemuxContext), .read_probe = cine_read_probe, .read_header = cine_read_header, .read_packet = cine_read_packet, .read_seek = cine_read_seek, };
./CrossVul/dataset_final_sorted/CWE-834/c/good_2766_0
crossvul-cpp_data_bad_2764_0
/* * ASF compatible demuxer * Copyright (c) 2000, 2001 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <inttypes.h> #include "libavutil/attributes.h" #include "libavutil/avassert.h" #include "libavutil/avstring.h" #include "libavutil/bswap.h" #include "libavutil/common.h" #include "libavutil/dict.h" #include "libavutil/internal.h" #include "libavutil/mathematics.h" #include "libavutil/opt.h" #include "avformat.h" #include "avio_internal.h" #include "avlanguage.h" #include "id3v2.h" #include "internal.h" #include "riff.h" #include "asf.h" #include "asfcrypt.h" typedef struct ASFPayload { uint8_t type; uint16_t size; } ASFPayload; typedef struct ASFStream { int num; unsigned char seq; /* use for reading */ AVPacket pkt; int frag_offset; int packet_obj_size; int timestamp; int64_t duration; int skip_to_key; int pkt_clean; int ds_span; /* descrambling */ int ds_packet_size; int ds_chunk_size; int64_t packet_pos; uint16_t stream_language_index; int palette_changed; uint32_t palette[256]; int payload_ext_ct; ASFPayload payload[8]; } ASFStream; typedef struct ASFContext { const AVClass *class; int asfid2avid[128]; ///< conversion table from asf ID 2 AVStream ID ASFStream streams[128]; ///< it's max number and it's not that big uint32_t stream_bitrates[128]; ///< max number of streams, bitrate for each (for streaming) AVRational dar[128]; char stream_languages[128][6]; ///< max number of streams, language for each (RFC1766, e.g. en-US) /* non streamed additonnal info */ /* packet filling */ int packet_size_left; /* only for reading */ uint64_t data_offset; ///< beginning of the first data packet uint64_t data_object_offset; ///< data object offset (excl. GUID & size) uint64_t data_object_size; ///< size of the data object int index_read; ASFMainHeader hdr; int packet_flags; int packet_property; int packet_timestamp; int packet_segsizetype; int packet_segments; int packet_seq; int packet_replic_size; int packet_key_frame; int packet_padsize; unsigned int packet_frag_offset; unsigned int packet_frag_size; int64_t packet_frag_timestamp; int ts_is_pts; int packet_multi_size; int packet_time_delta; int packet_time_start; int64_t packet_pos; int stream_index; ASFStream *asf_st; ///< currently decoded stream int no_resync_search; int export_xmp; int uses_std_ecc; } ASFContext; static const AVOption options[] = { { "no_resync_search", "Don't try to resynchronize by looking for a certain optional start code", offsetof(ASFContext, no_resync_search), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM }, { "export_xmp", "Export full XMP metadata", offsetof(ASFContext, export_xmp), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM }, { NULL }, }; static const AVClass asf_class = { .class_name = "asf demuxer", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; #undef NDEBUG #include <assert.h> #define ASF_MAX_STREAMS 127 #define FRAME_HEADER_SIZE 6 // Fix Me! FRAME_HEADER_SIZE may be different. // (7 is known to be too large for GipsyGuitar.wmv) #ifdef DEBUG static const ff_asf_guid stream_bitrate_guid = { /* (http://get.to/sdp) */ 0xce, 0x75, 0xf8, 0x7b, 0x8d, 0x46, 0xd1, 0x11, 0x8d, 0x82, 0x00, 0x60, 0x97, 0xc9, 0xa2, 0xb2 }; #define PRINT_IF_GUID(g, cmp) \ if (!ff_guidcmp(g, &cmp)) \ av_log(NULL, AV_LOG_TRACE, "(GUID: %s) ", # cmp) static void print_guid(ff_asf_guid *g) { int i; PRINT_IF_GUID(g, ff_asf_header); else PRINT_IF_GUID(g, ff_asf_file_header); else PRINT_IF_GUID(g, ff_asf_stream_header); else PRINT_IF_GUID(g, ff_asf_audio_stream); else PRINT_IF_GUID(g, ff_asf_audio_conceal_none); else PRINT_IF_GUID(g, ff_asf_video_stream); else PRINT_IF_GUID(g, ff_asf_video_conceal_none); else PRINT_IF_GUID(g, ff_asf_command_stream); else PRINT_IF_GUID(g, ff_asf_comment_header); else PRINT_IF_GUID(g, ff_asf_codec_comment_header); else PRINT_IF_GUID(g, ff_asf_codec_comment1_header); else PRINT_IF_GUID(g, ff_asf_data_header); else PRINT_IF_GUID(g, ff_asf_simple_index_header); else PRINT_IF_GUID(g, ff_asf_head1_guid); else PRINT_IF_GUID(g, ff_asf_head2_guid); else PRINT_IF_GUID(g, ff_asf_my_guid); else PRINT_IF_GUID(g, ff_asf_ext_stream_header); else PRINT_IF_GUID(g, ff_asf_extended_content_header); else PRINT_IF_GUID(g, ff_asf_ext_stream_embed_stream_header); else PRINT_IF_GUID(g, ff_asf_ext_stream_audio_stream); else PRINT_IF_GUID(g, ff_asf_metadata_header); else PRINT_IF_GUID(g, ff_asf_metadata_library_header); else PRINT_IF_GUID(g, ff_asf_marker_header); else PRINT_IF_GUID(g, stream_bitrate_guid); else PRINT_IF_GUID(g, ff_asf_language_guid); else av_log(NULL, AV_LOG_TRACE, "(GUID: unknown) "); for (i = 0; i < 16; i++) av_log(NULL, AV_LOG_TRACE, " 0x%02x,", (*g)[i]); av_log(NULL, AV_LOG_TRACE, "}\n"); } #undef PRINT_IF_GUID #else #define print_guid(g) while(0) #endif static int asf_probe(AVProbeData *pd) { /* check file header */ if (!ff_guidcmp(pd->buf, &ff_asf_header)) return AVPROBE_SCORE_MAX; else return 0; } /* size of type 2 (BOOL) is 32bit for "Extended Content Description Object" * but 16 bit for "Metadata Object" and "Metadata Library Object" */ static int get_value(AVIOContext *pb, int type, int type2_size) { switch (type) { case 2: return (type2_size == 32) ? avio_rl32(pb) : avio_rl16(pb); case 3: return avio_rl32(pb); case 4: return avio_rl64(pb); case 5: return avio_rl16(pb); default: return INT_MIN; } } /* MSDN claims that this should be "compatible with the ID3 frame, APIC", * but in reality this is only loosely similar */ static int asf_read_picture(AVFormatContext *s, int len) { AVPacket pkt = { 0 }; const CodecMime *mime = ff_id3v2_mime_tags; enum AVCodecID id = AV_CODEC_ID_NONE; char mimetype[64]; uint8_t *desc = NULL; AVStream *st = NULL; int ret, type, picsize, desc_len; /* type + picsize + mime + desc */ if (len < 1 + 4 + 2 + 2) { av_log(s, AV_LOG_ERROR, "Invalid attached picture size: %d.\n", len); return AVERROR_INVALIDDATA; } /* picture type */ type = avio_r8(s->pb); len--; if (type >= FF_ARRAY_ELEMS(ff_id3v2_picture_types) || type < 0) { av_log(s, AV_LOG_WARNING, "Unknown attached picture type: %d.\n", type); type = 0; } /* picture data size */ picsize = avio_rl32(s->pb); len -= 4; /* picture MIME type */ len -= avio_get_str16le(s->pb, len, mimetype, sizeof(mimetype)); while (mime->id != AV_CODEC_ID_NONE) { if (!strncmp(mime->str, mimetype, sizeof(mimetype))) { id = mime->id; break; } mime++; } if (id == AV_CODEC_ID_NONE) { av_log(s, AV_LOG_ERROR, "Unknown attached picture mimetype: %s.\n", mimetype); return 0; } if (picsize >= len) { av_log(s, AV_LOG_ERROR, "Invalid attached picture data size: %d >= %d.\n", picsize, len); return AVERROR_INVALIDDATA; } /* picture description */ desc_len = (len - picsize) * 2 + 1; desc = av_malloc(desc_len); if (!desc) return AVERROR(ENOMEM); len -= avio_get_str16le(s->pb, len - picsize, desc, desc_len); ret = av_get_packet(s->pb, &pkt, picsize); if (ret < 0) goto fail; st = avformat_new_stream(s, NULL); if (!st) { ret = AVERROR(ENOMEM); goto fail; } st->disposition |= AV_DISPOSITION_ATTACHED_PIC; st->codecpar->codec_type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = id; st->attached_pic = pkt; st->attached_pic.stream_index = st->index; st->attached_pic.flags |= AV_PKT_FLAG_KEY; if (*desc) av_dict_set(&st->metadata, "title", desc, AV_DICT_DONT_STRDUP_VAL); else av_freep(&desc); av_dict_set(&st->metadata, "comment", ff_id3v2_picture_types[type], 0); return 0; fail: av_freep(&desc); av_packet_unref(&pkt); return ret; } static void get_id3_tag(AVFormatContext *s, int len) { ID3v2ExtraMeta *id3v2_extra_meta = NULL; ff_id3v2_read(s, ID3v2_DEFAULT_MAGIC, &id3v2_extra_meta, len); if (id3v2_extra_meta) ff_id3v2_parse_apic(s, &id3v2_extra_meta); ff_id3v2_free_extra_meta(&id3v2_extra_meta); } static void get_tag(AVFormatContext *s, const char *key, int type, int len, int type2_size) { ASFContext *asf = s->priv_data; char *value = NULL; int64_t off = avio_tell(s->pb); #define LEN 22 if ((unsigned)len >= (UINT_MAX - LEN) / 2) return; if (!asf->export_xmp && !strncmp(key, "xmp", 3)) goto finish; value = av_malloc(2 * len + LEN); if (!value) goto finish; switch (type) { case ASF_UNICODE: avio_get_str16le(s->pb, len, value, 2 * len + 1); break; case -1: // ASCI avio_read(s->pb, value, len); value[len]=0; break; case ASF_BYTE_ARRAY: if (!strcmp(key, "WM/Picture")) { // handle cover art asf_read_picture(s, len); } else if (!strcmp(key, "ID3")) { // handle ID3 tag get_id3_tag(s, len); } else { av_log(s, AV_LOG_VERBOSE, "Unsupported byte array in tag %s.\n", key); } goto finish; case ASF_BOOL: case ASF_DWORD: case ASF_QWORD: case ASF_WORD: { uint64_t num = get_value(s->pb, type, type2_size); snprintf(value, LEN, "%"PRIu64, num); break; } case ASF_GUID: av_log(s, AV_LOG_DEBUG, "Unsupported GUID value in tag %s.\n", key); goto finish; default: av_log(s, AV_LOG_DEBUG, "Unsupported value type %d in tag %s.\n", type, key); goto finish; } if (*value) av_dict_set(&s->metadata, key, value, 0); finish: av_freep(&value); avio_seek(s->pb, off + len, SEEK_SET); } static int asf_read_file_properties(AVFormatContext *s, int64_t size) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; ff_get_guid(pb, &asf->hdr.guid); asf->hdr.file_size = avio_rl64(pb); asf->hdr.create_time = avio_rl64(pb); avio_rl64(pb); /* number of packets */ asf->hdr.play_time = avio_rl64(pb); asf->hdr.send_time = avio_rl64(pb); asf->hdr.preroll = avio_rl32(pb); asf->hdr.ignore = avio_rl32(pb); asf->hdr.flags = avio_rl32(pb); asf->hdr.min_pktsize = avio_rl32(pb); asf->hdr.max_pktsize = avio_rl32(pb); if (asf->hdr.min_pktsize >= (1U << 29)) return AVERROR_INVALIDDATA; asf->hdr.max_bitrate = avio_rl32(pb); s->packet_size = asf->hdr.max_pktsize; return 0; } static int asf_read_stream_properties(AVFormatContext *s, int64_t size) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; AVStream *st; ASFStream *asf_st; ff_asf_guid g; enum AVMediaType type; int type_specific_size, sizeX; unsigned int tag1; int64_t pos1, pos2, start_time; int test_for_ext_stream_audio, is_dvr_ms_audio = 0; if (s->nb_streams == ASF_MAX_STREAMS) { av_log(s, AV_LOG_ERROR, "too many streams\n"); return AVERROR(EINVAL); } pos1 = avio_tell(pb); st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */ start_time = asf->hdr.preroll; if (!(asf->hdr.flags & 0x01)) { // if we aren't streaming... int64_t fsize = avio_size(pb); if (fsize <= 0 || (int64_t)asf->hdr.file_size <= 0 || 20*FFABS(fsize - (int64_t)asf->hdr.file_size) < FFMIN(fsize, asf->hdr.file_size)) st->duration = asf->hdr.play_time / (10000000 / 1000) - start_time; } ff_get_guid(pb, &g); test_for_ext_stream_audio = 0; if (!ff_guidcmp(&g, &ff_asf_audio_stream)) { type = AVMEDIA_TYPE_AUDIO; } else if (!ff_guidcmp(&g, &ff_asf_video_stream)) { type = AVMEDIA_TYPE_VIDEO; } else if (!ff_guidcmp(&g, &ff_asf_jfif_media)) { type = AVMEDIA_TYPE_VIDEO; st->codecpar->codec_id = AV_CODEC_ID_MJPEG; } else if (!ff_guidcmp(&g, &ff_asf_command_stream)) { type = AVMEDIA_TYPE_DATA; } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_embed_stream_header)) { test_for_ext_stream_audio = 1; type = AVMEDIA_TYPE_UNKNOWN; } else { return -1; } ff_get_guid(pb, &g); avio_skip(pb, 8); /* total_size */ type_specific_size = avio_rl32(pb); avio_rl32(pb); st->id = avio_rl16(pb) & 0x7f; /* stream id */ // mapping of asf ID to AV stream ID; asf->asfid2avid[st->id] = s->nb_streams - 1; asf_st = &asf->streams[st->id]; avio_rl32(pb); if (test_for_ext_stream_audio) { ff_get_guid(pb, &g); if (!ff_guidcmp(&g, &ff_asf_ext_stream_audio_stream)) { type = AVMEDIA_TYPE_AUDIO; is_dvr_ms_audio = 1; ff_get_guid(pb, &g); avio_rl32(pb); avio_rl32(pb); avio_rl32(pb); ff_get_guid(pb, &g); avio_rl32(pb); } } st->codecpar->codec_type = type; if (type == AVMEDIA_TYPE_AUDIO) { int ret = ff_get_wav_header(s, pb, st->codecpar, type_specific_size, 0); if (ret < 0) return ret; if (is_dvr_ms_audio) { // codec_id and codec_tag are unreliable in dvr_ms // files. Set them later by probing stream. st->request_probe = 1; st->codecpar->codec_tag = 0; } if (st->codecpar->codec_id == AV_CODEC_ID_AAC) st->need_parsing = AVSTREAM_PARSE_NONE; else st->need_parsing = AVSTREAM_PARSE_FULL; /* We have to init the frame size at some point .... */ pos2 = avio_tell(pb); if (size >= (pos2 + 8 - pos1 + 24)) { asf_st->ds_span = avio_r8(pb); asf_st->ds_packet_size = avio_rl16(pb); asf_st->ds_chunk_size = avio_rl16(pb); avio_rl16(pb); // ds_data_size avio_r8(pb); // ds_silence_data } if (asf_st->ds_span > 1) { if (!asf_st->ds_chunk_size || (asf_st->ds_packet_size / asf_st->ds_chunk_size <= 1) || asf_st->ds_packet_size % asf_st->ds_chunk_size) asf_st->ds_span = 0; // disable descrambling } } else if (type == AVMEDIA_TYPE_VIDEO && size - (avio_tell(pb) - pos1 + 24) >= 51) { avio_rl32(pb); avio_rl32(pb); avio_r8(pb); avio_rl16(pb); /* size */ sizeX = avio_rl32(pb); /* size */ st->codecpar->width = avio_rl32(pb); st->codecpar->height = avio_rl32(pb); /* not available for asf */ avio_rl16(pb); /* panes */ st->codecpar->bits_per_coded_sample = avio_rl16(pb); /* depth */ tag1 = avio_rl32(pb); avio_skip(pb, 20); if (sizeX > 40) { st->codecpar->extradata_size = ffio_limit(pb, sizeX - 40); st->codecpar->extradata = av_mallocz(st->codecpar->extradata_size + AV_INPUT_BUFFER_PADDING_SIZE); if (!st->codecpar->extradata) return AVERROR(ENOMEM); avio_read(pb, st->codecpar->extradata, st->codecpar->extradata_size); } /* Extract palette from extradata if bpp <= 8 */ /* This code assumes that extradata contains only palette */ /* This is true for all paletted codecs implemented in libavcodec */ if (st->codecpar->extradata_size && (st->codecpar->bits_per_coded_sample <= 8)) { #if HAVE_BIGENDIAN int i; for (i = 0; i < FFMIN(st->codecpar->extradata_size, AVPALETTE_SIZE) / 4; i++) asf_st->palette[i] = av_bswap32(((uint32_t *)st->codecpar->extradata)[i]); #else memcpy(asf_st->palette, st->codecpar->extradata, FFMIN(st->codecpar->extradata_size, AVPALETTE_SIZE)); #endif asf_st->palette_changed = 1; } st->codecpar->codec_tag = tag1; st->codecpar->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1); if (tag1 == MKTAG('D', 'V', 'R', ' ')) { st->need_parsing = AVSTREAM_PARSE_FULL; /* issue658 contains wrong w/h and MS even puts a fake seq header * with wrong w/h in extradata while a correct one is in the stream. * maximum lameness */ st->codecpar->width = st->codecpar->height = 0; av_freep(&st->codecpar->extradata); st->codecpar->extradata_size = 0; } if (st->codecpar->codec_id == AV_CODEC_ID_H264) st->need_parsing = AVSTREAM_PARSE_FULL_ONCE; if (st->codecpar->codec_id == AV_CODEC_ID_MPEG4) st->need_parsing = AVSTREAM_PARSE_FULL_ONCE; } pos2 = avio_tell(pb); avio_skip(pb, size - (pos2 - pos1 + 24)); return 0; } static int asf_read_ext_stream_properties(AVFormatContext *s, int64_t size) { ASFContext *asf = s->priv_data; AVIOContext *pb = s->pb; ff_asf_guid g; int ext_len, payload_ext_ct, stream_ct, i; uint32_t leak_rate, stream_num; unsigned int stream_languageid_index; avio_rl64(pb); // starttime avio_rl64(pb); // endtime leak_rate = avio_rl32(pb); // leak-datarate avio_rl32(pb); // bucket-datasize avio_rl32(pb); // init-bucket-fullness avio_rl32(pb); // alt-leak-datarate avio_rl32(pb); // alt-bucket-datasize avio_rl32(pb); // alt-init-bucket-fullness avio_rl32(pb); // max-object-size avio_rl32(pb); // flags (reliable,seekable,no_cleanpoints?,resend-live-cleanpoints, rest of bits reserved) stream_num = avio_rl16(pb); // stream-num stream_languageid_index = avio_rl16(pb); // stream-language-id-index if (stream_num < 128) asf->streams[stream_num].stream_language_index = stream_languageid_index; avio_rl64(pb); // avg frametime in 100ns units stream_ct = avio_rl16(pb); // stream-name-count payload_ext_ct = avio_rl16(pb); // payload-extension-system-count if (stream_num < 128) { asf->stream_bitrates[stream_num] = leak_rate; asf->streams[stream_num].payload_ext_ct = 0; } for (i = 0; i < stream_ct; i++) { avio_rl16(pb); ext_len = avio_rl16(pb); avio_skip(pb, ext_len); } for (i = 0; i < payload_ext_ct; i++) { int size; ff_get_guid(pb, &g); size = avio_rl16(pb); ext_len = avio_rl32(pb); avio_skip(pb, ext_len); if (stream_num < 128 && i < FF_ARRAY_ELEMS(asf->streams[stream_num].payload)) { ASFPayload *p = &asf->streams[stream_num].payload[i]; p->type = g[0]; p->size = size; av_log(s, AV_LOG_DEBUG, "Payload extension %x %d\n", g[0], p->size ); asf->streams[stream_num].payload_ext_ct ++; } } return 0; } static int asf_read_content_desc(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; int len1, len2, len3, len4, len5; len1 = avio_rl16(pb); len2 = avio_rl16(pb); len3 = avio_rl16(pb); len4 = avio_rl16(pb); len5 = avio_rl16(pb); get_tag(s, "title", 0, len1, 32); get_tag(s, "author", 0, len2, 32); get_tag(s, "copyright", 0, len3, 32); get_tag(s, "comment", 0, len4, 32); avio_skip(pb, len5); return 0; } static int asf_read_ext_content_desc(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int desc_count, i, ret; desc_count = avio_rl16(pb); for (i = 0; i < desc_count; i++) { int name_len, value_type, value_len; char name[1024]; name_len = avio_rl16(pb); if (name_len % 2) // must be even, broken lavf versions wrote len-1 name_len += 1; if ((ret = avio_get_str16le(pb, name_len, name, sizeof(name))) < name_len) avio_skip(pb, name_len - ret); value_type = avio_rl16(pb); value_len = avio_rl16(pb); if (!value_type && value_len % 2) value_len += 1; /* My sample has that stream set to 0 maybe that mean the container. * ASF stream count starts at 1. I am using 0 to the container value * since it's unused. */ if (!strcmp(name, "AspectRatioX")) asf->dar[0].num = get_value(s->pb, value_type, 32); else if (!strcmp(name, "AspectRatioY")) asf->dar[0].den = get_value(s->pb, value_type, 32); else get_tag(s, name, value_type, value_len, 32); } return 0; } static int asf_read_language_list(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int j, ret; int stream_count = avio_rl16(pb); for (j = 0; j < stream_count; j++) { char lang[6]; unsigned int lang_len = avio_r8(pb); if ((ret = avio_get_str16le(pb, lang_len, lang, sizeof(lang))) < lang_len) avio_skip(pb, lang_len - ret); if (j < 128) av_strlcpy(asf->stream_languages[j], lang, sizeof(*asf->stream_languages)); } return 0; } static int asf_read_metadata(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int n, stream_num, name_len_utf16, name_len_utf8, value_len; int ret, i; n = avio_rl16(pb); for (i = 0; i < n; i++) { uint8_t *name; int value_type; avio_rl16(pb); // lang_list_index stream_num = avio_rl16(pb); name_len_utf16 = avio_rl16(pb); value_type = avio_rl16(pb); /* value_type */ value_len = avio_rl32(pb); name_len_utf8 = 2*name_len_utf16 + 1; name = av_malloc(name_len_utf8); if (!name) return AVERROR(ENOMEM); if ((ret = avio_get_str16le(pb, name_len_utf16, name, name_len_utf8)) < name_len_utf16) avio_skip(pb, name_len_utf16 - ret); av_log(s, AV_LOG_TRACE, "%d stream %d name_len %2d type %d len %4d <%s>\n", i, stream_num, name_len_utf16, value_type, value_len, name); if (!strcmp(name, "AspectRatioX")){ int aspect_x = get_value(s->pb, value_type, 16); if(stream_num < 128) asf->dar[stream_num].num = aspect_x; } else if(!strcmp(name, "AspectRatioY")){ int aspect_y = get_value(s->pb, value_type, 16); if(stream_num < 128) asf->dar[stream_num].den = aspect_y; } else { get_tag(s, name, value_type, value_len, 16); } av_freep(&name); } return 0; } static int asf_read_marker(AVFormatContext *s, int64_t size) { AVIOContext *pb = s->pb; ASFContext *asf = s->priv_data; int i, count, name_len, ret; char name[1024]; avio_rl64(pb); // reserved 16 bytes avio_rl64(pb); // ... count = avio_rl32(pb); // markers count avio_rl16(pb); // reserved 2 bytes name_len = avio_rl16(pb); // name length for (i = 0; i < name_len; i++) avio_r8(pb); // skip the name for (i = 0; i < count; i++) { int64_t pres_time; int name_len; avio_rl64(pb); // offset, 8 bytes pres_time = avio_rl64(pb); // presentation time pres_time -= asf->hdr.preroll * 10000; avio_rl16(pb); // entry length avio_rl32(pb); // send time avio_rl32(pb); // flags name_len = avio_rl32(pb); // name length if ((ret = avio_get_str16le(pb, name_len * 2, name, sizeof(name))) < name_len) avio_skip(pb, name_len - ret); avpriv_new_chapter(s, i, (AVRational) { 1, 10000000 }, pres_time, AV_NOPTS_VALUE, name); } return 0; } static int asf_read_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; ff_asf_guid g; AVIOContext *pb = s->pb; int i; int64_t gsize; ff_get_guid(pb, &g); if (ff_guidcmp(&g, &ff_asf_header)) return AVERROR_INVALIDDATA; avio_rl64(pb); avio_rl32(pb); avio_r8(pb); avio_r8(pb); memset(&asf->asfid2avid, -1, sizeof(asf->asfid2avid)); for (i = 0; i<128; i++) asf->streams[i].stream_language_index = 128; // invalid stream index means no language info for (;;) { uint64_t gpos = avio_tell(pb); int ret = 0; ff_get_guid(pb, &g); gsize = avio_rl64(pb); print_guid(&g); if (!ff_guidcmp(&g, &ff_asf_data_header)) { asf->data_object_offset = avio_tell(pb); /* If not streaming, gsize is not unlimited (how?), * and there is enough space in the file.. */ if (!(asf->hdr.flags & 0x01) && gsize >= 100) asf->data_object_size = gsize - 24; else asf->data_object_size = (uint64_t)-1; break; } if (gsize < 24) return AVERROR_INVALIDDATA; if (!ff_guidcmp(&g, &ff_asf_file_header)) { ret = asf_read_file_properties(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_stream_header)) { ret = asf_read_stream_properties(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_comment_header)) { asf_read_content_desc(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_language_guid)) { asf_read_language_list(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_extended_content_header)) { asf_read_ext_content_desc(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_metadata_header)) { asf_read_metadata(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_metadata_library_header)) { asf_read_metadata(s, gsize); } else if (!ff_guidcmp(&g, &ff_asf_ext_stream_header)) { asf_read_ext_stream_properties(s, gsize); // there could be an optional stream properties object to follow // if so the next iteration will pick it up continue; } else if (!ff_guidcmp(&g, &ff_asf_head1_guid)) { ff_get_guid(pb, &g); avio_skip(pb, 6); continue; } else if (!ff_guidcmp(&g, &ff_asf_marker_header)) { asf_read_marker(s, gsize); } else if (avio_feof(pb)) { return AVERROR_EOF; } else { if (!s->keylen) { if (!ff_guidcmp(&g, &ff_asf_content_encryption)) { unsigned int len; AVPacket pkt; av_log(s, AV_LOG_WARNING, "DRM protected stream detected, decoding will likely fail!\n"); len= avio_rl32(pb); av_log(s, AV_LOG_DEBUG, "Secret data:\n"); if ((ret = av_get_packet(pb, &pkt, len)) < 0) return ret; av_hex_dump_log(s, AV_LOG_DEBUG, pkt.data, pkt.size); av_packet_unref(&pkt); len= avio_rl32(pb); get_tag(s, "ASF_Protection_Type", -1, len, 32); len= avio_rl32(pb); get_tag(s, "ASF_Key_ID", -1, len, 32); len= avio_rl32(pb); get_tag(s, "ASF_License_URL", -1, len, 32); } else if (!ff_guidcmp(&g, &ff_asf_ext_content_encryption)) { av_log(s, AV_LOG_WARNING, "Ext DRM protected stream detected, decoding will likely fail!\n"); av_dict_set(&s->metadata, "encryption", "ASF Extended Content Encryption", 0); } else if (!ff_guidcmp(&g, &ff_asf_digital_signature)) { av_log(s, AV_LOG_INFO, "Digital signature detected!\n"); } } } if (ret < 0) return ret; if (avio_tell(pb) != gpos + gsize) av_log(s, AV_LOG_DEBUG, "gpos mismatch our pos=%"PRIu64", end=%"PRId64"\n", avio_tell(pb) - gpos, gsize); avio_seek(pb, gpos + gsize, SEEK_SET); } ff_get_guid(pb, &g); avio_rl64(pb); avio_r8(pb); avio_r8(pb); if (avio_feof(pb)) return AVERROR_EOF; asf->data_offset = avio_tell(pb); asf->packet_size_left = 0; for (i = 0; i < 128; i++) { int stream_num = asf->asfid2avid[i]; if (stream_num >= 0) { AVStream *st = s->streams[stream_num]; if (!st->codecpar->bit_rate) st->codecpar->bit_rate = asf->stream_bitrates[i]; if (asf->dar[i].num > 0 && asf->dar[i].den > 0) { av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, asf->dar[i].num, asf->dar[i].den, INT_MAX); } else if ((asf->dar[0].num > 0) && (asf->dar[0].den > 0) && // Use ASF container value if the stream doesn't set AR. (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO)) av_reduce(&st->sample_aspect_ratio.num, &st->sample_aspect_ratio.den, asf->dar[0].num, asf->dar[0].den, INT_MAX); av_log(s, AV_LOG_TRACE, "i=%d, st->codecpar->codec_type:%d, asf->dar %d:%d sar=%d:%d\n", i, st->codecpar->codec_type, asf->dar[i].num, asf->dar[i].den, st->sample_aspect_ratio.num, st->sample_aspect_ratio.den); // copy and convert language codes to the frontend if (asf->streams[i].stream_language_index < 128) { const char *rfc1766 = asf->stream_languages[asf->streams[i].stream_language_index]; if (rfc1766 && strlen(rfc1766) > 1) { const char primary_tag[3] = { rfc1766[0], rfc1766[1], '\0' }; // ignore country code if any const char *iso6392 = ff_convert_lang_to(primary_tag, AV_LANG_ISO639_2_BIBL); if (iso6392) av_dict_set(&st->metadata, "language", iso6392, 0); } } } } ff_metadata_conv(&s->metadata, NULL, ff_asf_metadata_conv); return 0; } #define DO_2BITS(bits, var, defval) \ switch (bits & 3) { \ case 3: \ var = avio_rl32(pb); \ rsize += 4; \ break; \ case 2: \ var = avio_rl16(pb); \ rsize += 2; \ break; \ case 1: \ var = avio_r8(pb); \ rsize++; \ break; \ default: \ var = defval; \ break; \ } /** * Load a single ASF packet into the demuxer. * @param s demux context * @param pb context to read data from * @return 0 on success, <0 on error */ static int asf_get_packet(AVFormatContext *s, AVIOContext *pb) { ASFContext *asf = s->priv_data; uint32_t packet_length, padsize; int rsize = 8; int c, d, e, off; if (asf->uses_std_ecc > 0) { // if we do not know packet size, allow skipping up to 32 kB off = 32768; if (asf->no_resync_search) off = 3; // else if (s->packet_size > 0 && !asf->uses_std_ecc) // off = (avio_tell(pb) - s->internal->data_offset) % s->packet_size + 3; c = d = e = -1; while (off-- > 0) { c = d; d = e; e = avio_r8(pb); if (c == 0x82 && !d && !e) break; } if (c != 0x82) { /* This code allows handling of -EAGAIN at packet boundaries (i.e. * if the packet sync code above triggers -EAGAIN). This does not * imply complete -EAGAIN handling support at random positions in * the stream. */ if (pb->error == AVERROR(EAGAIN)) return AVERROR(EAGAIN); if (!avio_feof(pb)) av_log(s, AV_LOG_ERROR, "ff asf bad header %x at:%"PRId64"\n", c, avio_tell(pb)); } if ((c & 0x8f) == 0x82) { if (d || e) { if (!avio_feof(pb)) av_log(s, AV_LOG_ERROR, "ff asf bad non zero\n"); return AVERROR_INVALIDDATA; } c = avio_r8(pb); d = avio_r8(pb); rsize += 3; } else if(!avio_feof(pb)) { avio_seek(pb, -1, SEEK_CUR); // FIXME } } else { c = avio_r8(pb); if (c & 0x80) { rsize ++; if (!(c & 0x60)) { d = avio_r8(pb); e = avio_r8(pb); avio_seek(pb, (c & 0xF) - 2, SEEK_CUR); rsize += c & 0xF; } if (c != 0x82) avpriv_request_sample(s, "Invalid ECC byte"); if (!asf->uses_std_ecc) asf->uses_std_ecc = (c == 0x82 && !d && !e) ? 1 : -1; c = avio_r8(pb); } else asf->uses_std_ecc = -1; d = avio_r8(pb); } asf->packet_flags = c; asf->packet_property = d; DO_2BITS(asf->packet_flags >> 5, packet_length, s->packet_size); DO_2BITS(asf->packet_flags >> 1, padsize, 0); // sequence ignored DO_2BITS(asf->packet_flags >> 3, padsize, 0); // padding length // the following checks prevent overflows and infinite loops if (!packet_length || packet_length >= (1U << 29)) { av_log(s, AV_LOG_ERROR, "invalid packet_length %"PRIu32" at:%"PRId64"\n", packet_length, avio_tell(pb)); return AVERROR_INVALIDDATA; } if (padsize >= packet_length) { av_log(s, AV_LOG_ERROR, "invalid padsize %"PRIu32" at:%"PRId64"\n", padsize, avio_tell(pb)); return AVERROR_INVALIDDATA; } asf->packet_timestamp = avio_rl32(pb); avio_rl16(pb); /* duration */ // rsize has at least 11 bytes which have to be present if (asf->packet_flags & 0x01) { asf->packet_segsizetype = avio_r8(pb); rsize++; asf->packet_segments = asf->packet_segsizetype & 0x3f; } else { asf->packet_segments = 1; asf->packet_segsizetype = 0x80; } if (rsize > packet_length - padsize) { asf->packet_size_left = 0; av_log(s, AV_LOG_ERROR, "invalid packet header length %d for pktlen %"PRIu32"-%"PRIu32" at %"PRId64"\n", rsize, packet_length, padsize, avio_tell(pb)); return AVERROR_INVALIDDATA; } asf->packet_size_left = packet_length - padsize - rsize; if (packet_length < asf->hdr.min_pktsize) padsize += asf->hdr.min_pktsize - packet_length; asf->packet_padsize = padsize; av_log(s, AV_LOG_TRACE, "packet: size=%d padsize=%d left=%d\n", s->packet_size, asf->packet_padsize, asf->packet_size_left); return 0; } /** * * @return <0 if error */ static int asf_read_frame_header(AVFormatContext *s, AVIOContext *pb) { ASFContext *asf = s->priv_data; ASFStream *asfst; int rsize = 1; int num = avio_r8(pb); int i; int64_t ts0, ts1 av_unused; asf->packet_segments--; asf->packet_key_frame = num >> 7; asf->stream_index = asf->asfid2avid[num & 0x7f]; asfst = &asf->streams[num & 0x7f]; // sequence should be ignored! DO_2BITS(asf->packet_property >> 4, asf->packet_seq, 0); DO_2BITS(asf->packet_property >> 2, asf->packet_frag_offset, 0); DO_2BITS(asf->packet_property, asf->packet_replic_size, 0); av_log(asf, AV_LOG_TRACE, "key:%d stream:%d seq:%d offset:%d replic_size:%d num:%X packet_property %X\n", asf->packet_key_frame, asf->stream_index, asf->packet_seq, asf->packet_frag_offset, asf->packet_replic_size, num, asf->packet_property); if (rsize+(int64_t)asf->packet_replic_size > asf->packet_size_left) { av_log(s, AV_LOG_ERROR, "packet_replic_size %d is invalid\n", asf->packet_replic_size); return AVERROR_INVALIDDATA; } if (asf->packet_replic_size >= 8) { int64_t end = avio_tell(pb) + asf->packet_replic_size; AVRational aspect; asfst->packet_obj_size = avio_rl32(pb); if (asfst->packet_obj_size >= (1 << 24) || asfst->packet_obj_size < 0) { av_log(s, AV_LOG_ERROR, "packet_obj_size %d invalid\n", asfst->packet_obj_size); asfst->packet_obj_size = 0; return AVERROR_INVALIDDATA; } asf->packet_frag_timestamp = avio_rl32(pb); // timestamp for (i = 0; i < asfst->payload_ext_ct; i++) { ASFPayload *p = &asfst->payload[i]; int size = p->size; int64_t payend; if (size == 0xFFFF) size = avio_rl16(pb); payend = avio_tell(pb) + size; if (payend > end) { av_log(s, AV_LOG_ERROR, "too long payload\n"); break; } switch (p->type) { case 0x50: // duration = avio_rl16(pb); break; case 0x54: aspect.num = avio_r8(pb); aspect.den = avio_r8(pb); if (aspect.num > 0 && aspect.den > 0 && asf->stream_index >= 0) { s->streams[asf->stream_index]->sample_aspect_ratio = aspect; } break; case 0x2A: avio_skip(pb, 8); ts0 = avio_rl64(pb); ts1 = avio_rl64(pb); if (ts0!= -1) asf->packet_frag_timestamp = ts0/10000; else asf->packet_frag_timestamp = AV_NOPTS_VALUE; asf->ts_is_pts = 1; break; case 0x5B: case 0xB7: case 0xCC: case 0xC0: case 0xA0: //unknown break; } avio_seek(pb, payend, SEEK_SET); } avio_seek(pb, end, SEEK_SET); rsize += asf->packet_replic_size; // FIXME - check validity } else if (asf->packet_replic_size == 1) { // multipacket - frag_offset is beginning timestamp asf->packet_time_start = asf->packet_frag_offset; asf->packet_frag_offset = 0; asf->packet_frag_timestamp = asf->packet_timestamp; asf->packet_time_delta = avio_r8(pb); rsize++; } else if (asf->packet_replic_size != 0) { av_log(s, AV_LOG_ERROR, "unexpected packet_replic_size of %d\n", asf->packet_replic_size); return AVERROR_INVALIDDATA; } if (asf->packet_flags & 0x01) { DO_2BITS(asf->packet_segsizetype >> 6, asf->packet_frag_size, 0); // 0 is illegal if (rsize > asf->packet_size_left) { av_log(s, AV_LOG_ERROR, "packet_replic_size is invalid\n"); return AVERROR_INVALIDDATA; } else if (asf->packet_frag_size > asf->packet_size_left - rsize) { if (asf->packet_frag_size > asf->packet_size_left - rsize + asf->packet_padsize) { av_log(s, AV_LOG_ERROR, "packet_frag_size is invalid (%d>%d-%d+%d)\n", asf->packet_frag_size, asf->packet_size_left, rsize, asf->packet_padsize); return AVERROR_INVALIDDATA; } else { int diff = asf->packet_frag_size - (asf->packet_size_left - rsize); asf->packet_size_left += diff; asf->packet_padsize -= diff; } } } else { asf->packet_frag_size = asf->packet_size_left - rsize; } if (asf->packet_replic_size == 1) { asf->packet_multi_size = asf->packet_frag_size; if (asf->packet_multi_size > asf->packet_size_left) return AVERROR_INVALIDDATA; } asf->packet_size_left -= rsize; return 0; } /** * Parse data from individual ASF packets (which were previously loaded * with asf_get_packet()). * @param s demux context * @param pb context to read data from * @param pkt pointer to store packet data into * @return 0 if data was stored in pkt, <0 on error or 1 if more ASF * packets need to be loaded (through asf_get_packet()) */ static int asf_parse_packet(AVFormatContext *s, AVIOContext *pb, AVPacket *pkt) { ASFContext *asf = s->priv_data; ASFStream *asf_st = 0; for (;;) { int ret; if (avio_feof(pb)) return AVERROR_EOF; if (asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1 && asf->packet_time_start == 0) { int ret = asf->packet_size_left + asf->packet_padsize; if (asf->packet_size_left && asf->packet_size_left < FRAME_HEADER_SIZE) av_log(s, AV_LOG_WARNING, "Skip due to FRAME_HEADER_SIZE\n"); assert(ret >= 0); /* fail safe */ avio_skip(pb, ret); asf->packet_pos = avio_tell(pb); if (asf->data_object_size != (uint64_t)-1 && (asf->packet_pos - asf->data_object_offset >= asf->data_object_size)) return AVERROR_EOF; /* Do not exceed the size of the data object */ return 1; } if (asf->packet_time_start == 0) { if (asf_read_frame_header(s, pb) < 0) { asf->packet_time_start = asf->packet_segments = 0; continue; } if (asf->stream_index < 0 || s->streams[asf->stream_index]->discard >= AVDISCARD_ALL || (!asf->packet_key_frame && (s->streams[asf->stream_index]->discard >= AVDISCARD_NONKEY || asf->streams[s->streams[asf->stream_index]->id].skip_to_key))) { asf->packet_time_start = 0; /* unhandled packet (should not happen) */ avio_skip(pb, asf->packet_frag_size); asf->packet_size_left -= asf->packet_frag_size; if (asf->stream_index < 0) av_log(s, AV_LOG_ERROR, "ff asf skip %d (unknown stream)\n", asf->packet_frag_size); continue; } asf->asf_st = &asf->streams[s->streams[asf->stream_index]->id]; if (!asf->packet_frag_offset) asf->asf_st->skip_to_key = 0; } asf_st = asf->asf_st; av_assert0(asf_st); if (!asf_st->frag_offset && asf->packet_frag_offset) { av_log(s, AV_LOG_TRACE, "skipping asf data pkt with fragment offset for " "stream:%d, expected:%d but got %d from pkt)\n", asf->stream_index, asf_st->frag_offset, asf->packet_frag_offset); avio_skip(pb, asf->packet_frag_size); asf->packet_size_left -= asf->packet_frag_size; continue; } if (asf->packet_replic_size == 1) { // frag_offset is here used as the beginning timestamp asf->packet_frag_timestamp = asf->packet_time_start; asf->packet_time_start += asf->packet_time_delta; asf_st->packet_obj_size = asf->packet_frag_size = avio_r8(pb); asf->packet_size_left--; asf->packet_multi_size--; if (asf->packet_multi_size < asf_st->packet_obj_size) { asf->packet_time_start = 0; avio_skip(pb, asf->packet_multi_size); asf->packet_size_left -= asf->packet_multi_size; continue; } asf->packet_multi_size -= asf_st->packet_obj_size; } if (asf_st->pkt.size != asf_st->packet_obj_size || // FIXME is this condition sufficient? asf_st->frag_offset + asf->packet_frag_size > asf_st->pkt.size) { int ret; if (asf_st->pkt.data) { av_log(s, AV_LOG_INFO, "freeing incomplete packet size %d, new %d\n", asf_st->pkt.size, asf_st->packet_obj_size); asf_st->frag_offset = 0; av_packet_unref(&asf_st->pkt); } /* new packet */ if ((ret = av_new_packet(&asf_st->pkt, asf_st->packet_obj_size)) < 0) return ret; asf_st->seq = asf->packet_seq; if (asf->ts_is_pts) { asf_st->pkt.pts = asf->packet_frag_timestamp - asf->hdr.preroll; } else asf_st->pkt.dts = asf->packet_frag_timestamp - asf->hdr.preroll; asf_st->pkt.stream_index = asf->stream_index; asf_st->pkt.pos = asf_st->packet_pos = asf->packet_pos; asf_st->pkt_clean = 0; if (asf_st->pkt.data && asf_st->palette_changed) { uint8_t *pal; pal = av_packet_new_side_data(&asf_st->pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); if (!pal) { av_log(s, AV_LOG_ERROR, "Cannot append palette to packet\n"); } else { memcpy(pal, asf_st->palette, AVPALETTE_SIZE); asf_st->palette_changed = 0; } } av_log(asf, AV_LOG_TRACE, "new packet: stream:%d key:%d packet_key:%d audio:%d size:%d\n", asf->stream_index, asf->packet_key_frame, asf_st->pkt.flags & AV_PKT_FLAG_KEY, s->streams[asf->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO, asf_st->packet_obj_size); if (s->streams[asf->stream_index]->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) asf->packet_key_frame = 1; if (asf->packet_key_frame) asf_st->pkt.flags |= AV_PKT_FLAG_KEY; } /* read data */ av_log(asf, AV_LOG_TRACE, "READ PACKET s:%d os:%d o:%d,%d l:%d DATA:%p\n", s->packet_size, asf_st->pkt.size, asf->packet_frag_offset, asf_st->frag_offset, asf->packet_frag_size, asf_st->pkt.data); asf->packet_size_left -= asf->packet_frag_size; if (asf->packet_size_left < 0) continue; if (asf->packet_frag_offset >= asf_st->pkt.size || asf->packet_frag_size > asf_st->pkt.size - asf->packet_frag_offset) { av_log(s, AV_LOG_ERROR, "packet fragment position invalid %u,%u not in %u\n", asf->packet_frag_offset, asf->packet_frag_size, asf_st->pkt.size); continue; } if (asf->packet_frag_offset != asf_st->frag_offset && !asf_st->pkt_clean) { memset(asf_st->pkt.data + asf_st->frag_offset, 0, asf_st->pkt.size - asf_st->frag_offset); asf_st->pkt_clean = 1; } ret = avio_read(pb, asf_st->pkt.data + asf->packet_frag_offset, asf->packet_frag_size); if (ret != asf->packet_frag_size) { if (ret < 0 || asf->packet_frag_offset + ret == 0) return ret < 0 ? ret : AVERROR_EOF; if (asf_st->ds_span > 1) { // scrambling, we can either drop it completely or fill the remainder // TODO: should we fill the whole packet instead of just the current // fragment? memset(asf_st->pkt.data + asf->packet_frag_offset + ret, 0, asf->packet_frag_size - ret); ret = asf->packet_frag_size; } else { // no scrambling, so we can return partial packets av_shrink_packet(&asf_st->pkt, asf->packet_frag_offset + ret); } } if (s->key && s->keylen == 20) ff_asfcrypt_dec(s->key, asf_st->pkt.data + asf->packet_frag_offset, ret); asf_st->frag_offset += ret; /* test if whole packet is read */ if (asf_st->frag_offset == asf_st->pkt.size) { // workaround for macroshit radio DVR-MS files if (s->streams[asf->stream_index]->codecpar->codec_id == AV_CODEC_ID_MPEG2VIDEO && asf_st->pkt.size > 100) { int i; for (i = 0; i < asf_st->pkt.size && !asf_st->pkt.data[i]; i++) ; if (i == asf_st->pkt.size) { av_log(s, AV_LOG_DEBUG, "discarding ms fart\n"); asf_st->frag_offset = 0; av_packet_unref(&asf_st->pkt); continue; } } /* return packet */ if (asf_st->ds_span > 1) { if (asf_st->pkt.size != asf_st->ds_packet_size * asf_st->ds_span) { av_log(s, AV_LOG_ERROR, "pkt.size != ds_packet_size * ds_span (%d %d %d)\n", asf_st->pkt.size, asf_st->ds_packet_size, asf_st->ds_span); } else { /* packet descrambling */ AVBufferRef *buf = av_buffer_alloc(asf_st->pkt.size + AV_INPUT_BUFFER_PADDING_SIZE); if (buf) { uint8_t *newdata = buf->data; int offset = 0; memset(newdata + asf_st->pkt.size, 0, AV_INPUT_BUFFER_PADDING_SIZE); while (offset < asf_st->pkt.size) { int off = offset / asf_st->ds_chunk_size; int row = off / asf_st->ds_span; int col = off % asf_st->ds_span; int idx = row + col * asf_st->ds_packet_size / asf_st->ds_chunk_size; assert(offset + asf_st->ds_chunk_size <= asf_st->pkt.size); assert(idx + 1 <= asf_st->pkt.size / asf_st->ds_chunk_size); memcpy(newdata + offset, asf_st->pkt.data + idx * asf_st->ds_chunk_size, asf_st->ds_chunk_size); offset += asf_st->ds_chunk_size; } av_buffer_unref(&asf_st->pkt.buf); asf_st->pkt.buf = buf; asf_st->pkt.data = buf->data; } } } asf_st->frag_offset = 0; *pkt = asf_st->pkt; asf_st->pkt.buf = 0; asf_st->pkt.size = 0; asf_st->pkt.data = 0; asf_st->pkt.side_data_elems = 0; asf_st->pkt.side_data = NULL; break; // packet completed } } return 0; } static int asf_read_packet(AVFormatContext *s, AVPacket *pkt) { ASFContext *asf = s->priv_data; for (;;) { int ret; /* parse cached packets, if any */ if ((ret = asf_parse_packet(s, s->pb, pkt)) <= 0) return ret; if ((ret = asf_get_packet(s, s->pb)) < 0) assert(asf->packet_size_left < FRAME_HEADER_SIZE || asf->packet_segments < 1); asf->packet_time_start = 0; } } // Added to support seeking after packets have been read // If information is not reset, read_packet fails due to // leftover information from previous reads static void asf_reset_header(AVFormatContext *s) { ASFContext *asf = s->priv_data; ASFStream *asf_st; int i; asf->packet_size_left = 0; asf->packet_flags = 0; asf->packet_property = 0; asf->packet_timestamp = 0; asf->packet_segsizetype = 0; asf->packet_segments = 0; asf->packet_seq = 0; asf->packet_replic_size = 0; asf->packet_key_frame = 0; asf->packet_padsize = 0; asf->packet_frag_offset = 0; asf->packet_frag_size = 0; asf->packet_frag_timestamp = 0; asf->packet_multi_size = 0; asf->packet_time_delta = 0; asf->packet_time_start = 0; for (i = 0; i < 128; i++) { asf_st = &asf->streams[i]; av_packet_unref(&asf_st->pkt); asf_st->packet_obj_size = 0; asf_st->frag_offset = 0; asf_st->seq = 0; } asf->asf_st = NULL; } static void skip_to_key(AVFormatContext *s) { ASFContext *asf = s->priv_data; int i; for (i = 0; i < 128; i++) { int j = asf->asfid2avid[i]; ASFStream *asf_st = &asf->streams[i]; if (j < 0 || s->streams[j]->codecpar->codec_type != AVMEDIA_TYPE_VIDEO) continue; asf_st->skip_to_key = 1; } } static int asf_read_close(AVFormatContext *s) { asf_reset_header(s); return 0; } static int64_t asf_read_pts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit) { ASFContext *asf = s->priv_data; AVPacket pkt1, *pkt = &pkt1; ASFStream *asf_st; int64_t pts; int64_t pos = *ppos; int i; int64_t start_pos[ASF_MAX_STREAMS]; for (i = 0; i < s->nb_streams; i++) start_pos[i] = pos; if (s->packet_size > 0) pos = (pos + s->packet_size - 1 - s->internal->data_offset) / s->packet_size * s->packet_size + s->internal->data_offset; *ppos = pos; if (avio_seek(s->pb, pos, SEEK_SET) < 0) return AV_NOPTS_VALUE; ff_read_frame_flush(s); asf_reset_header(s); for (;;) { if (av_read_frame(s, pkt) < 0) { av_log(s, AV_LOG_INFO, "asf_read_pts failed\n"); return AV_NOPTS_VALUE; } pts = pkt->dts; if (pkt->flags & AV_PKT_FLAG_KEY) { i = pkt->stream_index; asf_st = &asf->streams[s->streams[i]->id]; // assert((asf_st->packet_pos - s->data_offset) % s->packet_size == 0); pos = asf_st->packet_pos; av_assert1(pkt->pos == asf_st->packet_pos); av_add_index_entry(s->streams[i], pos, pts, pkt->size, pos - start_pos[i] + 1, AVINDEX_KEYFRAME); start_pos[i] = asf_st->packet_pos + 1; if (pkt->stream_index == stream_index) { av_packet_unref(pkt); break; } } av_packet_unref(pkt); } *ppos = pos; return pts; } static int asf_build_simple_index(AVFormatContext *s, int stream_index) { ff_asf_guid g; ASFContext *asf = s->priv_data; int64_t current_pos = avio_tell(s->pb); int64_t ret; if((ret = avio_seek(s->pb, asf->data_object_offset + asf->data_object_size, SEEK_SET)) < 0) { return ret; } if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; /* the data object can be followed by other top-level objects, * skip them until the simple index object is reached */ while (ff_guidcmp(&g, &ff_asf_simple_index_header)) { int64_t gsize = avio_rl64(s->pb); if (gsize < 24 || avio_feof(s->pb)) { goto end; } avio_skip(s->pb, gsize - 24); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; } { int64_t itime, last_pos = -1; int pct, ict; int i; int64_t av_unused gsize = avio_rl64(s->pb); if ((ret = ff_get_guid(s->pb, &g)) < 0) goto end; itime = avio_rl64(s->pb); pct = avio_rl32(s->pb); ict = avio_rl32(s->pb); av_log(s, AV_LOG_DEBUG, "itime:0x%"PRIx64", pct:%d, ict:%d\n", itime, pct, ict); for (i = 0; i < ict; i++) { int pktnum = avio_rl32(s->pb); int pktct = avio_rl16(s->pb); int64_t pos = s->internal->data_offset + s->packet_size * (int64_t)pktnum; int64_t index_pts = FFMAX(av_rescale(itime, i, 10000) - asf->hdr.preroll, 0); if (pos != last_pos) { av_log(s, AV_LOG_DEBUG, "pktnum:%d, pktct:%d pts: %"PRId64"\n", pktnum, pktct, index_pts); av_add_index_entry(s->streams[stream_index], pos, index_pts, s->packet_size, 0, AVINDEX_KEYFRAME); last_pos = pos; } } asf->index_read = ict > 1; } end: // if (avio_feof(s->pb)) { // ret = 0; // } avio_seek(s->pb, current_pos, SEEK_SET); return ret; } static int asf_read_seek(AVFormatContext *s, int stream_index, int64_t pts, int flags) { ASFContext *asf = s->priv_data; AVStream *st = s->streams[stream_index]; int ret = 0; if (s->packet_size <= 0) return -1; /* Try using the protocol's read_seek if available */ if (s->pb) { int64_t ret = avio_seek_time(s->pb, stream_index, pts, flags); if (ret >= 0) asf_reset_header(s); if (ret != AVERROR(ENOSYS)) return ret; } /* explicitly handle the case of seeking to 0 */ if (!pts) { asf_reset_header(s); avio_seek(s->pb, s->internal->data_offset, SEEK_SET); return 0; } if (!asf->index_read) { ret = asf_build_simple_index(s, stream_index); if (ret < 0) asf->index_read = -1; } if (asf->index_read > 0 && st->index_entries) { int index = av_index_search_timestamp(st, pts, flags); if (index >= 0) { /* find the position */ uint64_t pos = st->index_entries[index].pos; /* do the seek */ av_log(s, AV_LOG_DEBUG, "SEEKTO: %"PRId64"\n", pos); if(avio_seek(s->pb, pos, SEEK_SET) < 0) return -1; asf_reset_header(s); skip_to_key(s); return 0; } } /* no index or seeking by index failed */ if (ff_seek_frame_binary(s, stream_index, pts, flags) < 0) return -1; asf_reset_header(s); skip_to_key(s); return 0; } AVInputFormat ff_asf_demuxer = { .name = "asf", .long_name = NULL_IF_CONFIG_SMALL("ASF (Advanced / Active Streaming Format)"), .priv_data_size = sizeof(ASFContext), .read_probe = asf_probe, .read_header = asf_read_header, .read_packet = asf_read_packet, .read_close = asf_read_close, .read_seek = asf_read_seek, .read_timestamp = asf_read_pts, .flags = AVFMT_NOBINSEARCH | AVFMT_NOGENSEARCH, .priv_class = &asf_class, };
./CrossVul/dataset_final_sorted/CWE-834/c/bad_2764_0
crossvul-cpp_data_good_2624_0
/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tdebug.h> #include <tzlib.h> #include "id3v2framefactory.h" #include "id3v2synchdata.h" #include "id3v1genres.h" #include "frames/attachedpictureframe.h" #include "frames/commentsframe.h" #include "frames/relativevolumeframe.h" #include "frames/textidentificationframe.h" #include "frames/uniquefileidentifierframe.h" #include "frames/unknownframe.h" #include "frames/generalencapsulatedobjectframe.h" #include "frames/urllinkframe.h" #include "frames/unsynchronizedlyricsframe.h" #include "frames/popularimeterframe.h" #include "frames/privateframe.h" #include "frames/ownershipframe.h" #include "frames/synchronizedlyricsframe.h" #include "frames/eventtimingcodesframe.h" #include "frames/chapterframe.h" #include "frames/tableofcontentsframe.h" #include "frames/podcastframe.h" using namespace TagLib; using namespace ID3v2; namespace { void updateGenre(TextIdentificationFrame *frame) { StringList fields = frame->fieldList(); StringList newfields; for(StringList::ConstIterator it = fields.begin(); it != fields.end(); ++it) { String s = *it; int end = s.find(")"); if(s.startsWith("(") && end > 0) { // "(12)Genre" String text = s.substr(end + 1); bool ok; int number = s.substr(1, end - 1).toInt(&ok); if(ok && number >= 0 && number <= 255 && !(ID3v1::genre(number) == text)) newfields.append(s.substr(1, end - 1)); if(!text.isEmpty()) newfields.append(text); } else { // "Genre" or "12" newfields.append(s); } } if(newfields.isEmpty()) fields.append(String()); frame->setText(newfields); } } class FrameFactory::FrameFactoryPrivate { public: FrameFactoryPrivate() : defaultEncoding(String::Latin1), useDefaultEncoding(false) {} String::Type defaultEncoding; bool useDefaultEncoding; template <class T> void setTextEncoding(T *frame) { if(useDefaultEncoding) frame->setTextEncoding(defaultEncoding); } }; FrameFactory FrameFactory::factory; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FrameFactory *FrameFactory::instance() { return &factory; } Frame *FrameFactory::createFrame(const ByteVector &data, bool synchSafeInts) const { return createFrame(data, static_cast<unsigned int>(synchSafeInts ? 4 : 3)); } Frame *FrameFactory::createFrame(const ByteVector &data, unsigned int version) const { Header tagHeader; tagHeader.setMajorVersion(version); return createFrame(data, &tagHeader); } Frame *FrameFactory::createFrame(const ByteVector &origData, Header *tagHeader) const { ByteVector data = origData; unsigned int version = tagHeader->majorVersion(); Frame::Header *header = new Frame::Header(data, version); ByteVector frameID = header->frameID(); // A quick sanity check -- make sure that the frameID is 4 uppercase Latin1 // characters. Also make sure that there is data in the frame. if(frameID.size() != (version < 3 ? 3 : 4) || header->frameSize() <= static_cast<unsigned int>(header->dataLengthIndicator() ? 4 : 0) || header->frameSize() > data.size()) { delete header; return 0; } #ifndef NO_ITUNES_HACKS if(version == 3 && frameID.size() == 4 && frameID[3] == '\0') { // iTunes v2.3 tags store v2.2 frames - convert now frameID = frameID.mid(0, 3); header->setFrameID(frameID); header->setVersion(2); updateFrame(header); header->setVersion(3); } #endif for(ByteVector::ConstIterator it = frameID.begin(); it != frameID.end(); it++) { if( (*it < 'A' || *it > 'Z') && (*it < '0' || *it > '9') ) { delete header; return 0; } } if(version > 3 && (tagHeader->unsynchronisation() || header->unsynchronisation())) { // Data lengths are not part of the encoded data, but since they are synch-safe // integers they will be never actually encoded. ByteVector frameData = data.mid(Frame::Header::size(version), header->frameSize()); frameData = SynchData::decode(frameData); data = data.mid(0, Frame::Header::size(version)) + frameData; } // TagLib doesn't mess with encrypted frames, so just treat them // as unknown frames. if(!zlib::isAvailable() && header->compression()) { debug("Compressed frames are currently not supported."); return new UnknownFrame(data, header); } if(header->encryption()) { debug("Encrypted frames are currently not supported."); return new UnknownFrame(data, header); } if(!updateFrame(header)) { header->setTagAlterPreservation(true); return new UnknownFrame(data, header); } // updateFrame() might have updated the frame ID. frameID = header->frameID(); // This is where things get necissarily nasty. Here we determine which // Frame subclass (or if none is found simply an Frame) based // on the frame ID. Since there are a lot of possibilities, that means // a lot of if blocks. // Text Identification (frames 4.2) // Apple proprietary WFED (Podcast URL), MVNM (Movement Name), MVIN (Movement Number) are in fact text frames. if(frameID.startsWith("T") || frameID == "WFED" || frameID == "MVNM" || frameID == "MVIN") { TextIdentificationFrame *f = frameID != "TXXX" ? new TextIdentificationFrame(data, header) : new UserTextIdentificationFrame(data, header); d->setTextEncoding(f); if(frameID == "TCON") updateGenre(f); return f; } // Comments (frames 4.10) if(frameID == "COMM") { CommentsFrame *f = new CommentsFrame(data, header); d->setTextEncoding(f); return f; } // Attached Picture (frames 4.14) if(frameID == "APIC") { AttachedPictureFrame *f = new AttachedPictureFrame(data, header); d->setTextEncoding(f); return f; } // ID3v2.2 Attached Picture if(frameID == "PIC") { AttachedPictureFrame *f = new AttachedPictureFrameV22(data, header); d->setTextEncoding(f); return f; } // Relative Volume Adjustment (frames 4.11) if(frameID == "RVA2") return new RelativeVolumeFrame(data, header); // Unique File Identifier (frames 4.1) if(frameID == "UFID") return new UniqueFileIdentifierFrame(data, header); // General Encapsulated Object (frames 4.15) if(frameID == "GEOB") { GeneralEncapsulatedObjectFrame *f = new GeneralEncapsulatedObjectFrame(data, header); d->setTextEncoding(f); return f; } // URL link (frames 4.3) if(frameID.startsWith("W")) { if(frameID != "WXXX") { return new UrlLinkFrame(data, header); } else { UserUrlLinkFrame *f = new UserUrlLinkFrame(data, header); d->setTextEncoding(f); return f; } } // Unsynchronized lyric/text transcription (frames 4.8) if(frameID == "USLT") { UnsynchronizedLyricsFrame *f = new UnsynchronizedLyricsFrame(data, header); if(d->useDefaultEncoding) f->setTextEncoding(d->defaultEncoding); return f; } // Synchronised lyrics/text (frames 4.9) if(frameID == "SYLT") { SynchronizedLyricsFrame *f = new SynchronizedLyricsFrame(data, header); if(d->useDefaultEncoding) f->setTextEncoding(d->defaultEncoding); return f; } // Event timing codes (frames 4.5) if(frameID == "ETCO") return new EventTimingCodesFrame(data, header); // Popularimeter (frames 4.17) if(frameID == "POPM") return new PopularimeterFrame(data, header); // Private (frames 4.27) if(frameID == "PRIV") return new PrivateFrame(data, header); // Ownership (frames 4.22) if(frameID == "OWNE") { OwnershipFrame *f = new OwnershipFrame(data, header); d->setTextEncoding(f); return f; } // Chapter (ID3v2 chapters 1.0) if(frameID == "CHAP") return new ChapterFrame(tagHeader, data, header); // Table of contents (ID3v2 chapters 1.0) if(frameID == "CTOC") return new TableOfContentsFrame(tagHeader, data, header); // Apple proprietary PCST (Podcast) if(frameID == "PCST") return new PodcastFrame(data, header); return new UnknownFrame(data, header); } void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const { if(tag->header()->majorVersion() < 4 && tag->frameList("TDRC").size() == 1 && tag->frameList("TDAT").size() == 1) { TextIdentificationFrame *tdrc = dynamic_cast<TextIdentificationFrame *>(tag->frameList("TDRC").front()); UnknownFrame *tdat = static_cast<UnknownFrame *>(tag->frameList("TDAT").front()); if(tdrc && tdrc->fieldList().size() == 1 && tdrc->fieldList().front().size() == 4 && tdat->data().size() >= 5) { String date(tdat->data().mid(1), String::Type(tdat->data()[0])); if(date.length() == 4) { tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2)); if(tag->frameList("TIME").size() == 1) { UnknownFrame *timeframe = static_cast<UnknownFrame *>(tag->frameList("TIME").front()); if(timeframe->data().size() >= 5) { String time(timeframe->data().mid(1), String::Type(timeframe->data()[0])); if(time.length() == 4) { tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2)); } } } } } } } String::Type FrameFactory::defaultTextEncoding() const { return d->defaultEncoding; } void FrameFactory::setDefaultTextEncoding(String::Type encoding) { d->useDefaultEncoding = true; d->defaultEncoding = encoding; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// FrameFactory::FrameFactory() : d(new FrameFactoryPrivate()) { } FrameFactory::~FrameFactory() { delete d; } namespace { // Frame conversion table ID3v2.2 -> 2.4 const char *frameConversion2[][2] = { { "BUF", "RBUF" }, { "CNT", "PCNT" }, { "COM", "COMM" }, { "CRA", "AENC" }, { "ETC", "ETCO" }, { "GEO", "GEOB" }, { "IPL", "TIPL" }, { "MCI", "MCDI" }, { "MLL", "MLLT" }, { "POP", "POPM" }, { "REV", "RVRB" }, { "SLT", "SYLT" }, { "STC", "SYTC" }, { "TAL", "TALB" }, { "TBP", "TBPM" }, { "TCM", "TCOM" }, { "TCO", "TCON" }, { "TCP", "TCMP" }, { "TCR", "TCOP" }, { "TDY", "TDLY" }, { "TEN", "TENC" }, { "TFT", "TFLT" }, { "TKE", "TKEY" }, { "TLA", "TLAN" }, { "TLE", "TLEN" }, { "TMT", "TMED" }, { "TOA", "TOAL" }, { "TOF", "TOFN" }, { "TOL", "TOLY" }, { "TOR", "TDOR" }, { "TOT", "TOAL" }, { "TP1", "TPE1" }, { "TP2", "TPE2" }, { "TP3", "TPE3" }, { "TP4", "TPE4" }, { "TPA", "TPOS" }, { "TPB", "TPUB" }, { "TRC", "TSRC" }, { "TRD", "TDRC" }, { "TRK", "TRCK" }, { "TS2", "TSO2" }, { "TSA", "TSOA" }, { "TSC", "TSOC" }, { "TSP", "TSOP" }, { "TSS", "TSSE" }, { "TST", "TSOT" }, { "TT1", "TIT1" }, { "TT2", "TIT2" }, { "TT3", "TIT3" }, { "TXT", "TOLY" }, { "TXX", "TXXX" }, { "TYE", "TDRC" }, { "UFI", "UFID" }, { "ULT", "USLT" }, { "WAF", "WOAF" }, { "WAR", "WOAR" }, { "WAS", "WOAS" }, { "WCM", "WCOM" }, { "WCP", "WCOP" }, { "WPB", "WPUB" }, { "WXX", "WXXX" }, // Apple iTunes nonstandard frames { "PCS", "PCST" }, { "TCT", "TCAT" }, { "TDR", "TDRL" }, { "TDS", "TDES" }, { "TID", "TGID" }, { "WFD", "WFED" }, { "MVN", "MVNM" }, { "MVI", "MVIN" }, }; const size_t frameConversion2Size = sizeof(frameConversion2) / sizeof(frameConversion2[0]); // Frame conversion table ID3v2.3 -> 2.4 const char *frameConversion3[][2] = { { "TORY", "TDOR" }, { "TYER", "TDRC" }, { "IPLS", "TIPL" }, }; const size_t frameConversion3Size = sizeof(frameConversion3) / sizeof(frameConversion3[0]); } bool FrameFactory::updateFrame(Frame::Header *header) const { const ByteVector frameID = header->frameID(); switch(header->version()) { case 2: // ID3v2.2 { if(frameID == "CRM" || frameID == "EQU" || frameID == "LNK" || frameID == "RVA" || frameID == "TIM" || frameID == "TSI" || frameID == "TDA") { debug("ID3v2.4 no longer supports the frame type " + String(frameID) + ". It will be discarded from the tag."); return false; } // ID3v2.2 only used 3 bytes for the frame ID, so we need to convert all of // the frames to their 4 byte ID3v2.4 equivalent. for(size_t i = 0; i < frameConversion2Size; ++i) { if(frameID == frameConversion2[i][0]) { header->setFrameID(frameConversion2[i][1]); break; } } break; } case 3: // ID3v2.3 { if(frameID == "EQUA" || frameID == "RVAD" || frameID == "TIME" || frameID == "TRDA" || frameID == "TSIZ" || frameID == "TDAT") { debug("ID3v2.4 no longer supports the frame type " + String(frameID) + ". It will be discarded from the tag."); return false; } for(size_t i = 0; i < frameConversion3Size; ++i) { if(frameID == frameConversion3[i][0]) { header->setFrameID(frameConversion3[i][1]); break; } } break; } default: // This should catch a typo that existed in TagLib up to and including // version 1.1 where TRDC was used for the year rather than TDRC. if(frameID == "TRDC") header->setFrameID("TDRC"); break; } return true; }
./CrossVul/dataset_final_sorted/CWE-434/cpp/good_2624_0
crossvul-cpp_data_bad_2624_0
/*************************************************************************** copyright : (C) 2002 - 2008 by Scott Wheeler email : wheeler@kde.org ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * * 02110-1301 USA * * * * Alternatively, this file is available under the Mozilla Public * * License Version 1.1. You may obtain a copy of the License at * * http://www.mozilla.org/MPL/ * ***************************************************************************/ #include <tdebug.h> #include <tzlib.h> #include "id3v2framefactory.h" #include "id3v2synchdata.h" #include "id3v1genres.h" #include "frames/attachedpictureframe.h" #include "frames/commentsframe.h" #include "frames/relativevolumeframe.h" #include "frames/textidentificationframe.h" #include "frames/uniquefileidentifierframe.h" #include "frames/unknownframe.h" #include "frames/generalencapsulatedobjectframe.h" #include "frames/urllinkframe.h" #include "frames/unsynchronizedlyricsframe.h" #include "frames/popularimeterframe.h" #include "frames/privateframe.h" #include "frames/ownershipframe.h" #include "frames/synchronizedlyricsframe.h" #include "frames/eventtimingcodesframe.h" #include "frames/chapterframe.h" #include "frames/tableofcontentsframe.h" #include "frames/podcastframe.h" using namespace TagLib; using namespace ID3v2; namespace { void updateGenre(TextIdentificationFrame *frame) { StringList fields = frame->fieldList(); StringList newfields; for(StringList::ConstIterator it = fields.begin(); it != fields.end(); ++it) { String s = *it; int end = s.find(")"); if(s.startsWith("(") && end > 0) { // "(12)Genre" String text = s.substr(end + 1); bool ok; int number = s.substr(1, end - 1).toInt(&ok); if(ok && number >= 0 && number <= 255 && !(ID3v1::genre(number) == text)) newfields.append(s.substr(1, end - 1)); if(!text.isEmpty()) newfields.append(text); } else { // "Genre" or "12" newfields.append(s); } } if(newfields.isEmpty()) fields.append(String()); frame->setText(newfields); } } class FrameFactory::FrameFactoryPrivate { public: FrameFactoryPrivate() : defaultEncoding(String::Latin1), useDefaultEncoding(false) {} String::Type defaultEncoding; bool useDefaultEncoding; template <class T> void setTextEncoding(T *frame) { if(useDefaultEncoding) frame->setTextEncoding(defaultEncoding); } }; FrameFactory FrameFactory::factory; //////////////////////////////////////////////////////////////////////////////// // public members //////////////////////////////////////////////////////////////////////////////// FrameFactory *FrameFactory::instance() { return &factory; } Frame *FrameFactory::createFrame(const ByteVector &data, bool synchSafeInts) const { return createFrame(data, static_cast<unsigned int>(synchSafeInts ? 4 : 3)); } Frame *FrameFactory::createFrame(const ByteVector &data, unsigned int version) const { Header tagHeader; tagHeader.setMajorVersion(version); return createFrame(data, &tagHeader); } Frame *FrameFactory::createFrame(const ByteVector &origData, Header *tagHeader) const { ByteVector data = origData; unsigned int version = tagHeader->majorVersion(); Frame::Header *header = new Frame::Header(data, version); ByteVector frameID = header->frameID(); // A quick sanity check -- make sure that the frameID is 4 uppercase Latin1 // characters. Also make sure that there is data in the frame. if(frameID.size() != (version < 3 ? 3 : 4) || header->frameSize() <= static_cast<unsigned int>(header->dataLengthIndicator() ? 4 : 0) || header->frameSize() > data.size()) { delete header; return 0; } #ifndef NO_ITUNES_HACKS if(version == 3 && frameID.size() == 4 && frameID[3] == '\0') { // iTunes v2.3 tags store v2.2 frames - convert now frameID = frameID.mid(0, 3); header->setFrameID(frameID); header->setVersion(2); updateFrame(header); header->setVersion(3); } #endif for(ByteVector::ConstIterator it = frameID.begin(); it != frameID.end(); it++) { if( (*it < 'A' || *it > 'Z') && (*it < '0' || *it > '9') ) { delete header; return 0; } } if(version > 3 && (tagHeader->unsynchronisation() || header->unsynchronisation())) { // Data lengths are not part of the encoded data, but since they are synch-safe // integers they will be never actually encoded. ByteVector frameData = data.mid(Frame::Header::size(version), header->frameSize()); frameData = SynchData::decode(frameData); data = data.mid(0, Frame::Header::size(version)) + frameData; } // TagLib doesn't mess with encrypted frames, so just treat them // as unknown frames. if(!zlib::isAvailable() && header->compression()) { debug("Compressed frames are currently not supported."); return new UnknownFrame(data, header); } if(header->encryption()) { debug("Encrypted frames are currently not supported."); return new UnknownFrame(data, header); } if(!updateFrame(header)) { header->setTagAlterPreservation(true); return new UnknownFrame(data, header); } // updateFrame() might have updated the frame ID. frameID = header->frameID(); // This is where things get necissarily nasty. Here we determine which // Frame subclass (or if none is found simply an Frame) based // on the frame ID. Since there are a lot of possibilities, that means // a lot of if blocks. // Text Identification (frames 4.2) // Apple proprietary WFED (Podcast URL), MVNM (Movement Name), MVIN (Movement Number) are in fact text frames. if(frameID.startsWith("T") || frameID == "WFED" || frameID == "MVNM" || frameID == "MVIN") { TextIdentificationFrame *f = frameID != "TXXX" ? new TextIdentificationFrame(data, header) : new UserTextIdentificationFrame(data, header); d->setTextEncoding(f); if(frameID == "TCON") updateGenre(f); return f; } // Comments (frames 4.10) if(frameID == "COMM") { CommentsFrame *f = new CommentsFrame(data, header); d->setTextEncoding(f); return f; } // Attached Picture (frames 4.14) if(frameID == "APIC") { AttachedPictureFrame *f = new AttachedPictureFrame(data, header); d->setTextEncoding(f); return f; } // ID3v2.2 Attached Picture if(frameID == "PIC") { AttachedPictureFrame *f = new AttachedPictureFrameV22(data, header); d->setTextEncoding(f); return f; } // Relative Volume Adjustment (frames 4.11) if(frameID == "RVA2") return new RelativeVolumeFrame(data, header); // Unique File Identifier (frames 4.1) if(frameID == "UFID") return new UniqueFileIdentifierFrame(data, header); // General Encapsulated Object (frames 4.15) if(frameID == "GEOB") { GeneralEncapsulatedObjectFrame *f = new GeneralEncapsulatedObjectFrame(data, header); d->setTextEncoding(f); return f; } // URL link (frames 4.3) if(frameID.startsWith("W")) { if(frameID != "WXXX") { return new UrlLinkFrame(data, header); } else { UserUrlLinkFrame *f = new UserUrlLinkFrame(data, header); d->setTextEncoding(f); return f; } } // Unsynchronized lyric/text transcription (frames 4.8) if(frameID == "USLT") { UnsynchronizedLyricsFrame *f = new UnsynchronizedLyricsFrame(data, header); if(d->useDefaultEncoding) f->setTextEncoding(d->defaultEncoding); return f; } // Synchronised lyrics/text (frames 4.9) if(frameID == "SYLT") { SynchronizedLyricsFrame *f = new SynchronizedLyricsFrame(data, header); if(d->useDefaultEncoding) f->setTextEncoding(d->defaultEncoding); return f; } // Event timing codes (frames 4.5) if(frameID == "ETCO") return new EventTimingCodesFrame(data, header); // Popularimeter (frames 4.17) if(frameID == "POPM") return new PopularimeterFrame(data, header); // Private (frames 4.27) if(frameID == "PRIV") return new PrivateFrame(data, header); // Ownership (frames 4.22) if(frameID == "OWNE") { OwnershipFrame *f = new OwnershipFrame(data, header); d->setTextEncoding(f); return f; } // Chapter (ID3v2 chapters 1.0) if(frameID == "CHAP") return new ChapterFrame(tagHeader, data, header); // Table of contents (ID3v2 chapters 1.0) if(frameID == "CTOC") return new TableOfContentsFrame(tagHeader, data, header); // Apple proprietary PCST (Podcast) if(frameID == "PCST") return new PodcastFrame(data, header); return new UnknownFrame(data, header); } void FrameFactory::rebuildAggregateFrames(ID3v2::Tag *tag) const { if(tag->header()->majorVersion() < 4 && tag->frameList("TDRC").size() == 1 && tag->frameList("TDAT").size() == 1) { TextIdentificationFrame *tdrc = static_cast<TextIdentificationFrame *>(tag->frameList("TDRC").front()); UnknownFrame *tdat = static_cast<UnknownFrame *>(tag->frameList("TDAT").front()); if(tdrc->fieldList().size() == 1 && tdrc->fieldList().front().size() == 4 && tdat->data().size() >= 5) { String date(tdat->data().mid(1), String::Type(tdat->data()[0])); if(date.length() == 4) { tdrc->setText(tdrc->toString() + '-' + date.substr(2, 2) + '-' + date.substr(0, 2)); if(tag->frameList("TIME").size() == 1) { UnknownFrame *timeframe = static_cast<UnknownFrame *>(tag->frameList("TIME").front()); if(timeframe->data().size() >= 5) { String time(timeframe->data().mid(1), String::Type(timeframe->data()[0])); if(time.length() == 4) { tdrc->setText(tdrc->toString() + 'T' + time.substr(0, 2) + ':' + time.substr(2, 2)); } } } } } } } String::Type FrameFactory::defaultTextEncoding() const { return d->defaultEncoding; } void FrameFactory::setDefaultTextEncoding(String::Type encoding) { d->useDefaultEncoding = true; d->defaultEncoding = encoding; } //////////////////////////////////////////////////////////////////////////////// // protected members //////////////////////////////////////////////////////////////////////////////// FrameFactory::FrameFactory() : d(new FrameFactoryPrivate()) { } FrameFactory::~FrameFactory() { delete d; } namespace { // Frame conversion table ID3v2.2 -> 2.4 const char *frameConversion2[][2] = { { "BUF", "RBUF" }, { "CNT", "PCNT" }, { "COM", "COMM" }, { "CRA", "AENC" }, { "ETC", "ETCO" }, { "GEO", "GEOB" }, { "IPL", "TIPL" }, { "MCI", "MCDI" }, { "MLL", "MLLT" }, { "POP", "POPM" }, { "REV", "RVRB" }, { "SLT", "SYLT" }, { "STC", "SYTC" }, { "TAL", "TALB" }, { "TBP", "TBPM" }, { "TCM", "TCOM" }, { "TCO", "TCON" }, { "TCP", "TCMP" }, { "TCR", "TCOP" }, { "TDY", "TDLY" }, { "TEN", "TENC" }, { "TFT", "TFLT" }, { "TKE", "TKEY" }, { "TLA", "TLAN" }, { "TLE", "TLEN" }, { "TMT", "TMED" }, { "TOA", "TOAL" }, { "TOF", "TOFN" }, { "TOL", "TOLY" }, { "TOR", "TDOR" }, { "TOT", "TOAL" }, { "TP1", "TPE1" }, { "TP2", "TPE2" }, { "TP3", "TPE3" }, { "TP4", "TPE4" }, { "TPA", "TPOS" }, { "TPB", "TPUB" }, { "TRC", "TSRC" }, { "TRD", "TDRC" }, { "TRK", "TRCK" }, { "TS2", "TSO2" }, { "TSA", "TSOA" }, { "TSC", "TSOC" }, { "TSP", "TSOP" }, { "TSS", "TSSE" }, { "TST", "TSOT" }, { "TT1", "TIT1" }, { "TT2", "TIT2" }, { "TT3", "TIT3" }, { "TXT", "TOLY" }, { "TXX", "TXXX" }, { "TYE", "TDRC" }, { "UFI", "UFID" }, { "ULT", "USLT" }, { "WAF", "WOAF" }, { "WAR", "WOAR" }, { "WAS", "WOAS" }, { "WCM", "WCOM" }, { "WCP", "WCOP" }, { "WPB", "WPUB" }, { "WXX", "WXXX" }, // Apple iTunes nonstandard frames { "PCS", "PCST" }, { "TCT", "TCAT" }, { "TDR", "TDRL" }, { "TDS", "TDES" }, { "TID", "TGID" }, { "WFD", "WFED" }, { "MVN", "MVNM" }, { "MVI", "MVIN" }, }; const size_t frameConversion2Size = sizeof(frameConversion2) / sizeof(frameConversion2[0]); // Frame conversion table ID3v2.3 -> 2.4 const char *frameConversion3[][2] = { { "TORY", "TDOR" }, { "TYER", "TDRC" }, { "IPLS", "TIPL" }, }; const size_t frameConversion3Size = sizeof(frameConversion3) / sizeof(frameConversion3[0]); } bool FrameFactory::updateFrame(Frame::Header *header) const { const ByteVector frameID = header->frameID(); switch(header->version()) { case 2: // ID3v2.2 { if(frameID == "CRM" || frameID == "EQU" || frameID == "LNK" || frameID == "RVA" || frameID == "TIM" || frameID == "TSI" || frameID == "TDA") { debug("ID3v2.4 no longer supports the frame type " + String(frameID) + ". It will be discarded from the tag."); return false; } // ID3v2.2 only used 3 bytes for the frame ID, so we need to convert all of // the frames to their 4 byte ID3v2.4 equivalent. for(size_t i = 0; i < frameConversion2Size; ++i) { if(frameID == frameConversion2[i][0]) { header->setFrameID(frameConversion2[i][1]); break; } } break; } case 3: // ID3v2.3 { if(frameID == "EQUA" || frameID == "RVAD" || frameID == "TIME" || frameID == "TRDA" || frameID == "TSIZ" || frameID == "TDAT") { debug("ID3v2.4 no longer supports the frame type " + String(frameID) + ". It will be discarded from the tag."); return false; } for(size_t i = 0; i < frameConversion3Size; ++i) { if(frameID == frameConversion3[i][0]) { header->setFrameID(frameConversion3[i][1]); break; } } break; } default: // This should catch a typo that existed in TagLib up to and including // version 1.1 where TRDC was used for the year rather than TDRC. if(frameID == "TRDC") header->setFrameID("TDRC"); break; } return true; }
./CrossVul/dataset_final_sorted/CWE-434/cpp/bad_2624_0
crossvul-cpp_data_bad_1326_0
/* ** 2017-12-26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file implements a virtual table for reading and writing ZIP archive ** files. ** ** Usage example: ** ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename); ** ** Current limitations: ** ** * No support for encryption ** * No support for ZIP archives spanning multiple files ** * No support for zip64 extensions ** * Only the "inflate/deflate" (zlib) compression method is supported */ #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #include <stdio.h> #include <string.h> #include <assert.h> #include <zlib.h> #ifndef SQLITE_OMIT_VIRTUALTABLE #ifndef SQLITE_AMALGAMATION typedef sqlite3_int64 i64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned long u32; #define MIN(a,b) ((a)<(b) ? (a) : (b)) #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) # define ALWAYS(X) (1) # define NEVER(X) (0) #elif !defined(NDEBUG) # define ALWAYS(X) ((X)?1:(assert(0),0)) # define NEVER(X) ((X)?(assert(0),1):0) #else # define ALWAYS(X) (X) # define NEVER(X) (X) #endif #endif /* SQLITE_AMALGAMATION */ /* ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. ** ** In some ways it would be better to obtain these values from system ** header files. But, the dependency is undesirable and (a) these ** have been stable for decades, (b) the values are part of POSIX and ** are also made explicit in [man stat], and (c) are part of the ** file format for zip archives. */ #ifndef S_IFDIR # define S_IFDIR 0040000 #endif #ifndef S_IFREG # define S_IFREG 0100000 #endif #ifndef S_IFLNK # define S_IFLNK 0120000 #endif static const char ZIPFILE_SCHEMA[] = "CREATE TABLE y(" "name PRIMARY KEY," /* 0: Name of file in zip archive */ "mode," /* 1: POSIX mode for file */ "mtime," /* 2: Last modification time (secs since 1970)*/ "sz," /* 3: Size of object */ "rawdata," /* 4: Raw data */ "data," /* 5: Uncompressed data */ "method," /* 6: Compression method (integer) */ "z HIDDEN" /* 7: Name of zip file */ ") WITHOUT ROWID;"; #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ #define ZIPFILE_BUFFER_SIZE (64*1024) /* ** Magic numbers used to read and write zip files. ** ** ZIPFILE_NEWENTRY_MADEBY: ** Use this value for the "version-made-by" field in new zip file ** entries. The upper byte indicates "unix", and the lower byte ** indicates that the zip file matches pkzip specification 3.0. ** This is what info-zip seems to do. ** ** ZIPFILE_NEWENTRY_REQUIRED: ** Value for "version-required-to-extract" field of new entries. ** Version 2.0 is required to support folders and deflate compression. ** ** ZIPFILE_NEWENTRY_FLAGS: ** Value for "general-purpose-bit-flags" field of new entries. Bit ** 11 means "utf-8 filename and comment". ** ** ZIPFILE_SIGNATURE_CDS: ** First 4 bytes of a valid CDS record. ** ** ZIPFILE_SIGNATURE_LFH: ** First 4 bytes of a valid LFH record. ** ** ZIPFILE_SIGNATURE_EOCD ** First 4 bytes of a valid EOCD record. */ #define ZIPFILE_EXTRA_TIMESTAMP 0x5455 #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) #define ZIPFILE_NEWENTRY_REQUIRED 20 #define ZIPFILE_NEWENTRY_FLAGS 0x800 #define ZIPFILE_SIGNATURE_CDS 0x02014b50 #define ZIPFILE_SIGNATURE_LFH 0x04034b50 #define ZIPFILE_SIGNATURE_EOCD 0x06054b50 /* ** The sizes of the fixed-size part of each of the three main data ** structures in a zip archive. */ #define ZIPFILE_LFH_FIXED_SZ 30 #define ZIPFILE_EOCD_FIXED_SZ 22 #define ZIPFILE_CDS_FIXED_SZ 46 /* *** 4.3.16 End of central directory record: *** *** end of central dir signature 4 bytes (0x06054b50) *** number of this disk 2 bytes *** number of the disk with the *** start of the central directory 2 bytes *** total number of entries in the *** central directory on this disk 2 bytes *** total number of entries in *** the central directory 2 bytes *** size of the central directory 4 bytes *** offset of start of central *** directory with respect to *** the starting disk number 4 bytes *** .ZIP file comment length 2 bytes *** .ZIP file comment (variable size) */ typedef struct ZipfileEOCD ZipfileEOCD; struct ZipfileEOCD { u16 iDisk; u16 iFirstDisk; u16 nEntry; u16 nEntryTotal; u32 nSize; u32 iOffset; }; /* *** 4.3.12 Central directory structure: *** *** ... *** *** central file header signature 4 bytes (0x02014b50) *** version made by 2 bytes *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** file comment length 2 bytes *** disk number start 2 bytes *** internal file attributes 2 bytes *** external file attributes 4 bytes *** relative offset of local header 4 bytes */ typedef struct ZipfileCDS ZipfileCDS; struct ZipfileCDS { u16 iVersionMadeBy; u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; u16 nComment; u16 iDiskStart; u16 iInternalAttr; u32 iExternalAttr; u32 iOffset; char *zFile; /* Filename (sqlite3_malloc()) */ }; /* *** 4.3.7 Local file header: *** *** local file header signature 4 bytes (0x04034b50) *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** */ typedef struct ZipfileLFH ZipfileLFH; struct ZipfileLFH { u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; }; typedef struct ZipfileEntry ZipfileEntry; struct ZipfileEntry { ZipfileCDS cds; /* Parsed CDS record */ u32 mUnixTime; /* Modification time, in UNIX format */ u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ i64 iDataOff; /* Offset to data in file (if aData==0) */ u8 *aData; /* cds.szCompressed bytes of compressed data */ ZipfileEntry *pNext; /* Next element in in-memory CDS */ }; /* ** Cursor type for zipfile tables. */ typedef struct ZipfileCsr ZipfileCsr; struct ZipfileCsr { sqlite3_vtab_cursor base; /* Base class - must be first */ i64 iId; /* Cursor ID */ u8 bEof; /* True when at EOF */ u8 bNoop; /* If next xNext() call is no-op */ /* Used outside of write transactions */ FILE *pFile; /* Zip file */ i64 iNextOff; /* Offset of next record in central directory */ ZipfileEOCD eocd; /* Parse of central directory record */ ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ ZipfileEntry *pCurrent; /* Current entry */ ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ }; typedef struct ZipfileTab ZipfileTab; struct ZipfileTab { sqlite3_vtab base; /* Base class - must be first */ char *zFile; /* Zip file this table accesses (may be NULL) */ sqlite3 *db; /* Host database connection */ u8 *aBuffer; /* Temporary buffer used for various tasks */ ZipfileCsr *pCsrList; /* List of cursors */ i64 iNextCsrid; /* The following are used by write transactions only */ ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ FILE *pWriteFd; /* File handle open on zip archive */ i64 szCurrent; /* Current size of zip archive */ i64 szOrig; /* Size of archive at start of transaction */ }; /* ** Set the error message contained in context ctx to the results of ** vprintf(zFmt, ...). */ static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ char *zMsg = 0; va_list ap; va_start(ap, zFmt); zMsg = sqlite3_vmprintf(zFmt, ap); sqlite3_result_error(ctx, zMsg, -1); sqlite3_free(zMsg); va_end(ap); } /* ** If string zIn is quoted, dequote it in place. Otherwise, if the string ** is not quoted, do nothing. */ static void zipfileDequote(char *zIn){ char q = zIn[0]; if( q=='"' || q=='\'' || q=='`' || q=='[' ){ int iIn = 1; int iOut = 0; if( q=='[' ) q = ']'; while( ALWAYS(zIn[iIn]) ){ char c = zIn[iIn++]; if( c==q && zIn[iIn++]!=q ) break; zIn[iOut++] = c; } zIn[iOut] = '\0'; } } /* ** Construct a new ZipfileTab virtual table object. ** ** argv[0] -> module name ("zipfile") ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> "column name" and other module argument fields. */ static int zipfileConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; int nFile = 0; const char *zFile = 0; ZipfileTab *pNew = 0; int rc; /* If the table name is not "zipfile", require that the argument be ** specified. This stops zipfile tables from being created as: ** ** CREATE VIRTUAL TABLE zzz USING zipfile(); ** ** It does not prevent: ** ** CREATE VIRTUAL TABLE zipfile USING zipfile(); */ assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); return SQLITE_ERROR; } if( argc>3 ){ zFile = argv[3]; nFile = (int)strlen(zFile)+1; } rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); if( rc==SQLITE_OK ){ pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile); if( pNew==0 ) return SQLITE_NOMEM; memset(pNew, 0, nByte+nFile); pNew->db = db; pNew->aBuffer = (u8*)&pNew[1]; if( zFile ){ pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; memcpy(pNew->zFile, zFile, nFile); zipfileDequote(pNew->zFile); } } *ppVtab = (sqlite3_vtab*)pNew; return rc; } /* ** Free the ZipfileEntry structure indicated by the only argument. */ static void zipfileEntryFree(ZipfileEntry *p){ if( p ){ sqlite3_free(p->cds.zFile); sqlite3_free(p); } } /* ** Release resources that should be freed at the end of a write ** transaction. */ static void zipfileCleanupTransaction(ZipfileTab *pTab){ ZipfileEntry *pEntry; ZipfileEntry *pNext; if( pTab->pWriteFd ){ fclose(pTab->pWriteFd); pTab->pWriteFd = 0; } for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ pNext = pEntry->pNext; zipfileEntryFree(pEntry); } pTab->pFirstEntry = 0; pTab->pLastEntry = 0; pTab->szCurrent = 0; pTab->szOrig = 0; } /* ** This method is the destructor for zipfile vtab objects. */ static int zipfileDisconnect(sqlite3_vtab *pVtab){ zipfileCleanupTransaction((ZipfileTab*)pVtab); sqlite3_free(pVtab); return SQLITE_OK; } /* ** Constructor for a new ZipfileCsr object. */ static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ ZipfileTab *pTab = (ZipfileTab*)p; ZipfileCsr *pCsr; pCsr = sqlite3_malloc(sizeof(*pCsr)); *ppCsr = (sqlite3_vtab_cursor*)pCsr; if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(*pCsr)); pCsr->iId = ++pTab->iNextCsrid; pCsr->pCsrNext = pTab->pCsrList; pTab->pCsrList = pCsr; return SQLITE_OK; } /* ** Reset a cursor back to the state it was in when first returned ** by zipfileOpen(). */ static void zipfileResetCursor(ZipfileCsr *pCsr){ ZipfileEntry *p; ZipfileEntry *pNext; pCsr->bEof = 0; if( pCsr->pFile ){ fclose(pCsr->pFile); pCsr->pFile = 0; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; } for(p=pCsr->pFreeEntry; p; p=pNext){ pNext = p->pNext; zipfileEntryFree(p); } } /* ** Destructor for an ZipfileCsr. */ static int zipfileClose(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); ZipfileCsr **pp; zipfileResetCursor(pCsr); /* Remove this cursor from the ZipfileTab.pCsrList list. */ for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); *pp = pCsr->pCsrNext; sqlite3_free(pCsr); return SQLITE_OK; } /* ** Set the error message for the virtual table associated with cursor ** pCsr to the results of vprintf(zFmt, ...). */ static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pTab->base.zErrMsg); pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pCsr->base.pVtab->zErrMsg); pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } /* ** Read nRead bytes of data from offset iOff of file pFile into buffer ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code ** otherwise. ** ** If an error does occur, output variable (*pzErrmsg) may be set to point ** to an English language error message. It is the responsibility of the ** caller to eventually free this buffer using ** sqlite3_free(). */ static int zipfileReadData( FILE *pFile, /* Read from this file */ u8 *aRead, /* Read into this buffer */ int nRead, /* Number of bytes to read */ i64 iOff, /* Offset to read from */ char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ ){ size_t n; fseek(pFile, (long)iOff, SEEK_SET); n = fread(aRead, 1, nRead, pFile); if( (int)n!=nRead ){ *pzErrmsg = sqlite3_mprintf("error in fread()"); return SQLITE_ERROR; } return SQLITE_OK; } static int zipfileAppendData( ZipfileTab *pTab, const u8 *aWrite, int nWrite ){ size_t n; fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); if( (int)n!=nWrite ){ pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); return SQLITE_ERROR; } pTab->szCurrent += nWrite; return SQLITE_OK; } /* ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. */ static u16 zipfileGetU16(const u8 *aBuf){ return (aBuf[1] << 8) + aBuf[0]; } /* ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. */ static u32 zipfileGetU32(const u8 *aBuf){ return ((u32)(aBuf[3]) << 24) + ((u32)(aBuf[2]) << 16) + ((u32)(aBuf[1]) << 8) + ((u32)(aBuf[0]) << 0); } /* ** Write a 16-bit little endiate integer into buffer aBuf. */ static void zipfilePutU16(u8 *aBuf, u16 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; } /* ** Write a 32-bit little endiate integer into buffer aBuf. */ static void zipfilePutU32(u8 *aBuf, u32 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; aBuf[2] = (val>>16) & 0xFF; aBuf[3] = (val>>24) & 0xFF; } #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } /* ** Magic numbers used to read CDS records. */ #define ZIPFILE_CDS_NFILE_OFF 28 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 /* ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ u8 *aRead = aBuf; u32 sig = zipfileRead32(aRead); int rc = SQLITE_OK; if( sig!=ZIPFILE_SIGNATURE_CDS ){ rc = SQLITE_ERROR; }else{ pCDS->iVersionMadeBy = zipfileRead16(aRead); pCDS->iVersionExtract = zipfileRead16(aRead); pCDS->flags = zipfileRead16(aRead); pCDS->iCompression = zipfileRead16(aRead); pCDS->mTime = zipfileRead16(aRead); pCDS->mDate = zipfileRead16(aRead); pCDS->crc32 = zipfileRead32(aRead); pCDS->szCompressed = zipfileRead32(aRead); pCDS->szUncompressed = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); pCDS->nFile = zipfileRead16(aRead); pCDS->nExtra = zipfileRead16(aRead); pCDS->nComment = zipfileRead16(aRead); pCDS->iDiskStart = zipfileRead16(aRead); pCDS->iInternalAttr = zipfileRead16(aRead); pCDS->iExternalAttr = zipfileRead32(aRead); pCDS->iOffset = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); } return rc; } /* ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadLFH( u8 *aBuffer, ZipfileLFH *pLFH ){ u8 *aRead = aBuffer; int rc = SQLITE_OK; u32 sig = zipfileRead32(aRead); if( sig!=ZIPFILE_SIGNATURE_LFH ){ rc = SQLITE_ERROR; }else{ pLFH->iVersionExtract = zipfileRead16(aRead); pLFH->flags = zipfileRead16(aRead); pLFH->iCompression = zipfileRead16(aRead); pLFH->mTime = zipfileRead16(aRead); pLFH->mDate = zipfileRead16(aRead); pLFH->crc32 = zipfileRead32(aRead); pLFH->szCompressed = zipfileRead32(aRead); pLFH->szUncompressed = zipfileRead32(aRead); pLFH->nFile = zipfileRead16(aRead); pLFH->nExtra = zipfileRead16(aRead); } return rc; } /* ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. ** Scan through this buffer to find an "extra-timestamp" field. If one ** exists, extract the 32-bit modification-timestamp from it and store ** the value in output parameter *pmTime. ** ** Zero is returned if no extra-timestamp record could be found (and so ** *pmTime is left unchanged), or non-zero otherwise. ** ** The general format of an extra field is: ** ** Header ID 2 bytes ** Data Size 2 bytes ** Data N bytes */ static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ int ret = 0; u8 *p = aExtra; u8 *pEnd = &aExtra[nExtra]; while( p<pEnd ){ u16 id = zipfileRead16(p); u16 nByte = zipfileRead16(p); switch( id ){ case ZIPFILE_EXTRA_TIMESTAMP: { u8 b = p[0]; if( b & 0x01 ){ /* 0x01 -> modtime is present */ *pmTime = zipfileGetU32(&p[1]); ret = 1; } break; } } p += nByte; } return ret; } /* ** Convert the standard MS-DOS timestamp stored in the mTime and mDate ** fields of the CDS structure passed as the only argument to a 32-bit ** UNIX seconds-since-the-epoch timestamp. Return the result. ** ** "Standard" MS-DOS time format: ** ** File modification time: ** Bits 00-04: seconds divided by 2 ** Bits 05-10: minute ** Bits 11-15: hour ** File modification date: ** Bits 00-04: day ** Bits 05-08: month (1-12) ** Bits 09-15: years from 1980 ** ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx */ static u32 zipfileMtime(ZipfileCDS *pCDS){ int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); int M = ((pCDS->mDate >> 5) & 0x0F); int D = (pCDS->mDate & 0x1F); int B = -13; int sec = (pCDS->mTime & 0x1F)*2; int min = (pCDS->mTime >> 5) & 0x3F; int hr = (pCDS->mTime >> 11) & 0x1F; i64 JD; /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */ /* Calculate the JD in seconds for noon on the day in question */ if( M<3 ){ Y = Y-1; M = M+12; } JD = (i64)(24*60*60) * ( (int)(365.25 * (Y + 4716)) + (int)(30.6001 * (M + 1)) + D + B - 1524 ); /* Correct the JD for the time within the day */ JD += (hr-12) * 3600 + min * 60 + sec; /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */ return (u32)(JD - (i64)(24405875) * 24*60*6); } /* ** The opposite of zipfileMtime(). This function populates the mTime and ** mDate fields of the CDS structure passed as the first argument according ** to the UNIX timestamp value passed as the second. */ static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */ i64 JD = (i64)2440588 + mUnixTime / (24*60*60); int A, B, C, D, E; int yr, mon, day; int hr, min, sec; A = (int)((JD - 1867216.25)/36524.25); A = (int)(JD + 1 + A - (A/4)); B = A + 1524; C = (int)((B - 122.1)/365.25); D = (36525*(C&32767))/100; E = (int)((B-D)/30.6001); day = B - D - (int)(30.6001*E); mon = (E<14 ? E-1 : E-13); yr = mon>2 ? C-4716 : C-4715; hr = (mUnixTime % (24*60*60)) / (60*60); min = (mUnixTime % (60*60)) / 60; sec = (mUnixTime % 60); if( yr>=1980 ){ pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); }else{ pCds->mDate = pCds->mTime = 0; } assert( mUnixTime<315507600 || mUnixTime==zipfileMtime(pCds) || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) /* || (mUnixTime % 2) */ ); } /* ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in ** size) containing an entire zip archive image. Or, if aBlob is NULL, ** then pFile is a file-handle open on a zip file. In either case, this ** function creates a ZipfileEntry object based on the zip archive entry ** for which the CDS record is at offset iOff. ** ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to ** the new object. Otherwise, an SQLite error code is returned and the ** final value of (*ppEntry) undefined. */ static int zipfileGetEntry( ZipfileTab *pTab, /* Store any error message here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* If aBlob==0, read from this file */ i64 iOff, /* Offset of CDS record */ ZipfileEntry **ppEntry /* OUT: Pointer to new object */ ){ u8 *aRead; char **pzErr = &pTab->base.zErrMsg; int rc = SQLITE_OK; if( aBlob==0 ){ aRead = pTab->aBuffer; rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); }else{ aRead = (u8*)&aBlob[iOff]; } if( rc==SQLITE_OK ){ sqlite3_int64 nAlloc; ZipfileEntry *pNew; int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); nAlloc = sizeof(ZipfileEntry) + nExtra; if( aBlob ){ nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); } pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ memset(pNew, 0, sizeof(ZipfileEntry)); rc = zipfileReadCDS(aRead, &pNew->cds); if( rc!=SQLITE_OK ){ *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff); }else if( aBlob==0 ){ rc = zipfileReadData( pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr ); }else{ aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; } } if( rc==SQLITE_OK ){ u32 *pt = &pNew->mUnixTime; pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); pNew->aExtra = (u8*)&pNew[1]; memcpy(pNew->aExtra, &aRead[nFile], nExtra); if( pNew->cds.zFile==0 ){ rc = SQLITE_NOMEM; }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ pNew->mUnixTime = zipfileMtime(&pNew->cds); } } if( rc==SQLITE_OK ){ static const int szFix = ZIPFILE_LFH_FIXED_SZ; ZipfileLFH lfh; if( pFile ){ rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); }else{ aRead = (u8*)&aBlob[pNew->cds.iOffset]; } rc = zipfileReadLFH(aRead, &lfh); if( rc==SQLITE_OK ){ pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; pNew->iDataOff += lfh.nFile + lfh.nExtra; if( aBlob && pNew->cds.szCompressed ){ pNew->aData = &pNew->aExtra[nExtra]; memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); } }else{ *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", (int)pNew->cds.iOffset ); } } if( rc!=SQLITE_OK ){ zipfileEntryFree(pNew); }else{ *ppEntry = pNew; } } return rc; } /* ** Advance an ZipfileCsr to its next row of output. */ static int zipfileNext(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; int rc = SQLITE_OK; if( pCsr->pFile ){ i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; if( pCsr->iNextOff>=iEof ){ pCsr->bEof = 1; }else{ ZipfileEntry *p = 0; ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); if( rc==SQLITE_OK ){ pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; } pCsr->pCurrent = p; } }else{ if( !pCsr->bNoop ){ pCsr->pCurrent = pCsr->pCurrent->pNext; } if( pCsr->pCurrent==0 ){ pCsr->bEof = 1; } } pCsr->bNoop = 0; return rc; } static void zipfileFree(void *p) { sqlite3_free(p); } /* ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the ** size is nOut bytes. This function uncompresses the data and sets the ** return value in context pCtx to the result (a blob). ** ** If an error occurs, an error code is left in pCtx instead. */ static void zipfileInflate( sqlite3_context *pCtx, /* Store result here */ const u8 *aIn, /* Compressed data */ int nIn, /* Size of buffer aIn[] in bytes */ int nOut /* Expected output size */ ){ u8 *aRes = sqlite3_malloc(nOut); if( aRes==0 ){ sqlite3_result_error_nomem(pCtx); }else{ int err; z_stream str; memset(&str, 0, sizeof(str)); str.next_in = (Byte*)aIn; str.avail_in = nIn; str.next_out = (Byte*)aRes; str.avail_out = nOut; err = inflateInit2(&str, -15); if( err!=Z_OK ){ zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); }else{ err = inflate(&str, Z_NO_FLUSH); if( err!=Z_STREAM_END ){ zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); }else{ sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree); aRes = 0; } } sqlite3_free(aRes); inflateEnd(&str); } } /* ** Buffer aIn (size nIn bytes) contains uncompressed data. This function ** compresses it and sets (*ppOut) to point to a buffer containing the ** compressed data. The caller is responsible for eventually calling ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) ** is set to the size of buffer (*ppOut) in bytes. ** ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error ** code is returned and an error message left in virtual-table handle ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this ** case. */ static int zipfileDeflate( const u8 *aIn, int nIn, /* Input */ u8 **ppOut, int *pnOut, /* Output */ char **pzErr /* OUT: Error message */ ){ int rc = SQLITE_OK; sqlite3_int64 nAlloc; z_stream str; u8 *aOut; memset(&str, 0, sizeof(str)); str.next_in = (Bytef*)aIn; str.avail_in = nIn; deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); nAlloc = deflateBound(&str, nIn); aOut = (u8*)sqlite3_malloc64(nAlloc); if( aOut==0 ){ rc = SQLITE_NOMEM; }else{ int res; str.next_out = aOut; str.avail_out = nAlloc; deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); res = deflate(&str, Z_FINISH); if( res==Z_STREAM_END ){ *ppOut = aOut; *pnOut = (int)str.total_out; }else{ sqlite3_free(aOut); *pzErr = sqlite3_mprintf("zipfile: deflate() error"); rc = SQLITE_ERROR; } deflateEnd(&str); } return rc; } /* ** Return values of columns for the row at which the series_cursor ** is currently pointing. */ static int zipfileColumn( sqlite3_vtab_cursor *cur, /* The cursor */ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ int i /* Which column to return */ ){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileCDS *pCDS = &pCsr->pCurrent->cds; int rc = SQLITE_OK; switch( i ){ case 0: /* name */ sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); break; case 1: /* mode */ /* TODO: Whether or not the following is correct surely depends on ** the platform on which the archive was created. */ sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); break; case 2: { /* mtime */ sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); break; } case 3: { /* sz */ if( sqlite3_vtab_nochange(ctx)==0 ){ sqlite3_result_int64(ctx, pCDS->szUncompressed); } break; } case 4: /* rawdata */ if( sqlite3_vtab_nochange(ctx) ) break; case 5: { /* data */ if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ int sz = pCDS->szCompressed; int szFinal = pCDS->szUncompressed; if( szFinal>0 ){ u8 *aBuf; u8 *aFree = 0; if( pCsr->pCurrent->aData ){ aBuf = pCsr->pCurrent->aData; }else{ aBuf = aFree = sqlite3_malloc64(sz); if( aBuf==0 ){ rc = SQLITE_NOMEM; }else{ FILE *pFile = pCsr->pFile; if( pFile==0 ){ pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; } rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, &pCsr->base.pVtab->zErrMsg ); } } if( rc==SQLITE_OK ){ if( i==5 && pCDS->iCompression ){ zipfileInflate(ctx, aBuf, sz, szFinal); }else{ sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); } } sqlite3_free(aFree); }else{ /* Figure out if this is a directory or a zero-sized file. Consider ** it to be a directory either if the mode suggests so, or if ** the final character in the name is '/'. */ u32 mode = pCDS->iExternalAttr >> 16; if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){ sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); } } } break; } case 6: /* method */ sqlite3_result_int(ctx, pCDS->iCompression); break; default: /* z */ assert( i==7 ); sqlite3_result_int64(ctx, pCsr->iId); break; } return rc; } /* ** Return TRUE if the cursor is at EOF. */ static int zipfileEof(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; return pCsr->bEof; } /* ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile ** is guaranteed to be a file-handle open on a zip file. ** ** This function attempts to locate the EOCD record within the zip archive ** and populate *pEOCD with the results of decoding it. SQLITE_OK is ** returned if successful. Otherwise, an SQLite error code is returned and ** an English language error message may be left in virtual-table pTab. */ static int zipfileReadEOCD( ZipfileTab *pTab, /* Return errors here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* Read from this file if aBlob==0 */ ZipfileEOCD *pEOCD /* Object to populate */ ){ u8 *aRead = pTab->aBuffer; /* Temporary buffer */ int nRead; /* Bytes to read from file */ int rc = SQLITE_OK; if( aBlob==0 ){ i64 iOff; /* Offset to read from */ i64 szFile; /* Total size of file in bytes */ fseek(pFile, 0, SEEK_END); szFile = (i64)ftell(pFile); if( szFile==0 ){ memset(pEOCD, 0, sizeof(ZipfileEOCD)); return SQLITE_OK; } nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); iOff = szFile - nRead; rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); }else{ nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); aRead = (u8*)&aBlob[nBlob-nRead]; } if( rc==SQLITE_OK ){ int i; /* Scan backwards looking for the signature bytes */ for(i=nRead-20; i>=0; i--){ if( aRead[i]==0x50 && aRead[i+1]==0x4b && aRead[i+2]==0x05 && aRead[i+3]==0x06 ){ break; } } if( i<0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "cannot find end of central directory record" ); return SQLITE_ERROR; } aRead += i+4; pEOCD->iDisk = zipfileRead16(aRead); pEOCD->iFirstDisk = zipfileRead16(aRead); pEOCD->nEntry = zipfileRead16(aRead); pEOCD->nEntryTotal = zipfileRead16(aRead); pEOCD->nSize = zipfileRead32(aRead); pEOCD->iOffset = zipfileRead32(aRead); } return rc; } /* ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added ** to the end of the list. Otherwise, it is added to the list immediately ** before pBefore (which is guaranteed to be a part of said list). */ static void zipfileAddEntry( ZipfileTab *pTab, ZipfileEntry *pBefore, ZipfileEntry *pNew ){ assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); assert( pNew->pNext==0 ); if( pBefore==0 ){ if( pTab->pFirstEntry==0 ){ pTab->pFirstEntry = pTab->pLastEntry = pNew; }else{ assert( pTab->pLastEntry->pNext==0 ); pTab->pLastEntry->pNext = pNew; pTab->pLastEntry = pNew; } }else{ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); pNew->pNext = pBefore; *pp = pNew; } } static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){ ZipfileEOCD eocd; int rc; int i; i64 iOff; rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); iOff = eocd.iOffset; for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){ ZipfileEntry *pNew = 0; rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew); if( rc==SQLITE_OK ){ zipfileAddEntry(pTab, 0, pNew); iOff += ZIPFILE_CDS_FIXED_SZ; iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; } } return rc; } /* ** xFilter callback. */ static int zipfileFilter( sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; ZipfileCsr *pCsr = (ZipfileCsr*)cur; const char *zFile = 0; /* Zip file to scan */ int rc = SQLITE_OK; /* Return Code */ int bInMemory = 0; /* True for an in-memory zipfile */ zipfileResetCursor(pCsr); if( pTab->zFile ){ zFile = pTab->zFile; }else if( idxNum==0 ){ zipfileCursorErr(pCsr, "zipfile() function requires an argument"); return SQLITE_ERROR; }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); int nBlob = sqlite3_value_bytes(argv[0]); assert( pTab->pFirstEntry==0 ); rc = zipfileLoadDirectory(pTab, aBlob, nBlob); pCsr->pFreeEntry = pTab->pFirstEntry; pTab->pFirstEntry = pTab->pLastEntry = 0; if( rc!=SQLITE_OK ) return rc; bInMemory = 1; }else{ zFile = (const char*)sqlite3_value_text(argv[0]); } if( 0==pTab->pWriteFd && 0==bInMemory ){ pCsr->pFile = fopen(zFile, "rb"); if( pCsr->pFile==0 ){ zipfileCursorErr(pCsr, "cannot open file: %s", zFile); rc = SQLITE_ERROR; }else{ rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); if( rc==SQLITE_OK ){ if( pCsr->eocd.nEntry==0 ){ pCsr->bEof = 1; }else{ pCsr->iNextOff = pCsr->eocd.iOffset; rc = zipfileNext(cur); } } } }else{ pCsr->bNoop = 1; pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; rc = zipfileNext(cur); } return rc; } /* ** xBestIndex callback. */ static int zipfileBestIndex( sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo ){ int i; int idx = -1; int unusable = 0; for(i=0; i<pIdxInfo->nConstraint; i++){ const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; if( pCons->usable==0 ){ unusable = 1; }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ idx = i; } } if( idx>=0 ){ pIdxInfo->aConstraintUsage[idx].argvIndex = 1; pIdxInfo->aConstraintUsage[idx].omit = 1; pIdxInfo->estimatedCost = 1000.0; pIdxInfo->idxNum = 1; }else if( unusable ){ return SQLITE_CONSTRAINT; } return SQLITE_OK; } static ZipfileEntry *zipfileNewEntry(const char *zPath){ ZipfileEntry *pNew; pNew = sqlite3_malloc(sizeof(ZipfileEntry)); if( pNew ){ memset(pNew, 0, sizeof(ZipfileEntry)); pNew->cds.zFile = sqlite3_mprintf("%s", zPath); if( pNew->cds.zFile==0 ){ sqlite3_free(pNew); pNew = 0; } } return pNew; } static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ ZipfileCDS *pCds = &pEntry->cds; u8 *a = aBuf; pCds->nExtra = 9; /* Write the LFH itself */ zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); zipfileWrite16(a, pCds->iVersionExtract); zipfileWrite16(a, pCds->flags); zipfileWrite16(a, pCds->iCompression); zipfileWrite16(a, pCds->mTime); zipfileWrite16(a, pCds->mDate); zipfileWrite32(a, pCds->crc32); zipfileWrite32(a, pCds->szCompressed); zipfileWrite32(a, pCds->szUncompressed); zipfileWrite16(a, (u16)pCds->nFile); zipfileWrite16(a, pCds->nExtra); assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); /* Add the file name */ memcpy(a, pCds->zFile, (int)pCds->nFile); a += (int)pCds->nFile; /* The "extra" data */ zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); return a-aBuf; } static int zipfileAppendEntry( ZipfileTab *pTab, ZipfileEntry *pEntry, const u8 *pData, int nData ){ u8 *aBuf = pTab->aBuffer; int nBuf; int rc; nBuf = zipfileSerializeLFH(pEntry, aBuf); rc = zipfileAppendData(pTab, aBuf, nBuf); if( rc==SQLITE_OK ){ pEntry->iDataOff = pTab->szCurrent; rc = zipfileAppendData(pTab, pData, nData); } return rc; } static int zipfileGetMode( sqlite3_value *pVal, int bIsDir, /* If true, default to directory */ u32 *pMode, /* OUT: Mode value */ char **pzErr /* OUT: Error message */ ){ const char *z = (const char*)sqlite3_value_text(pVal); u32 mode = 0; if( z==0 ){ mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); }else if( z[0]>='0' && z[0]<='9' ){ mode = (unsigned int)sqlite3_value_int(pVal); }else{ const char zTemplate[11] = "-rwxrwxrwx"; int i; if( strlen(z)!=10 ) goto parse_error; switch( z[0] ){ case '-': mode |= S_IFREG; break; case 'd': mode |= S_IFDIR; break; case 'l': mode |= S_IFLNK; break; default: goto parse_error; } for(i=1; i<10; i++){ if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); else if( z[i]!='-' ) goto parse_error; } } if( ((mode & S_IFDIR)==0)==bIsDir ){ /* The "mode" attribute is a directory, but data has been specified. ** Or vice-versa - no data but "mode" is a file or symlink. */ *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); return SQLITE_CONSTRAINT; } *pMode = mode; return SQLITE_OK; parse_error: *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); return SQLITE_ERROR; } /* ** Both (const char*) arguments point to nul-terminated strings. Argument ** nB is the value of strlen(zB). This function returns 0 if the strings are ** identical, ignoring any trailing '/' character in either path. */ static int zipfileComparePath(const char *zA, const char *zB, int nB){ int nA = (int)strlen(zA); if( zA[nA-1]=='/' ) nA--; if( zB[nB-1]=='/' ) nB--; if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; return 1; } static int zipfileBegin(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; assert( pTab->pWriteFd==0 ); /* Open a write fd on the file. Also load the entire central directory ** structure into memory. During the transaction any new file data is ** appended to the archive file, but the central directory is accumulated ** in main-memory until the transaction is committed. */ pTab->pWriteFd = fopen(pTab->zFile, "ab+"); if( pTab->pWriteFd==0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "zipfile: failed to open file %s for writing", pTab->zFile ); rc = SQLITE_ERROR; }else{ fseek(pTab->pWriteFd, 0, SEEK_END); pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); rc = zipfileLoadDirectory(pTab, 0, 0); } if( rc!=SQLITE_OK ){ zipfileCleanupTransaction(pTab); } return rc; } /* ** Return the current time as a 32-bit timestamp in UNIX epoch format (like ** time(2)). */ static u32 zipfileTime(void){ sqlite3_vfs *pVfs = sqlite3_vfs_find(0); u32 ret; if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ i64 ms; pVfs->xCurrentTimeInt64(pVfs, &ms); ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); }else{ double day; pVfs->xCurrentTime(pVfs, &day); ret = (u32)((day - 2440587.5) * 86400); } return ret; } /* ** Return a 32-bit timestamp in UNIX epoch format. ** ** If the value passed as the only argument is either NULL or an SQL NULL, ** return the current time. Otherwise, return the value stored in (*pVal) ** cast to a 32-bit unsigned integer. */ static u32 zipfileGetTime(sqlite3_value *pVal){ if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ return zipfileTime(); } return (u32)sqlite3_value_int64(pVal); } /* ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry ** linked list. Remove it from the list and free the object. */ static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ if( pOld ){ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext)); *pp = (*pp)->pNext; zipfileEntryFree(pOld); } } /* ** xUpdate method. */ static int zipfileUpdate( sqlite3_vtab *pVtab, int nVal, sqlite3_value **apVal, sqlite_int64 *pRowid ){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; /* Return Code */ ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ u32 mode = 0; /* Mode for new entry */ u32 mTime = 0; /* Modification time for new entry */ i64 sz = 0; /* Uncompressed size */ const char *zPath = 0; /* Path for new entry */ int nPath = 0; /* strlen(zPath) */ const u8 *pData = 0; /* Pointer to buffer containing content */ int nData = 0; /* Size of pData buffer in bytes */ int iMethod = 0; /* Compression method for new entry */ u8 *pFree = 0; /* Free this */ char *zFree = 0; /* Also free this */ ZipfileEntry *pOld = 0; ZipfileEntry *pOld2 = 0; int bUpdate = 0; /* True for an update that modifies "name" */ int bIsDir = 0; u32 iCrc32 = 0; if( pTab->pWriteFd==0 ){ rc = zipfileBegin(pVtab); if( rc!=SQLITE_OK ) return rc; } /* If this is a DELETE or UPDATE, find the archive entry to delete. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); int nDelete = (int)strlen(zDelete); if( nVal>1 ){ const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ bUpdate = 1; } } for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ break; } assert( pOld->pNext ); } } if( nVal>1 ){ /* Check that "sz" and "rawdata" are both NULL: */ if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ zipfileTableErr(pTab, "sz must be NULL"); rc = SQLITE_CONSTRAINT; } if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ zipfileTableErr(pTab, "rawdata must be NULL"); rc = SQLITE_CONSTRAINT; } if( rc==SQLITE_OK ){ if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ /* data=NULL. A directory */ bIsDir = 1; }else{ /* Value specified for "data", and possibly "method". This must be ** a regular file or a symlink. */ const u8 *aIn = sqlite3_value_blob(apVal[7]); int nIn = sqlite3_value_bytes(apVal[7]); int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; iMethod = sqlite3_value_int(apVal[8]); sz = nIn; pData = aIn; nData = nIn; if( iMethod!=0 && iMethod!=8 ){ zipfileTableErr(pTab, "unknown compression method: %d", iMethod); rc = SQLITE_CONSTRAINT; }else{ if( bAuto || iMethod ){ int nCmp; rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); if( rc==SQLITE_OK ){ if( iMethod || nCmp<nIn ){ iMethod = 8; pData = pFree; nData = nCmp; } } } iCrc32 = crc32(0, aIn, nIn); } } } if( rc==SQLITE_OK ){ rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); } if( rc==SQLITE_OK ){ zPath = (const char*)sqlite3_value_text(apVal[2]); nPath = (int)strlen(zPath); mTime = zipfileGetTime(apVal[4]); } if( rc==SQLITE_OK && bIsDir ){ /* For a directory, check that the last character in the path is a ** '/'. This appears to be required for compatibility with info-zip ** (the unzip command on unix). It does not create directories ** otherwise. */ if( zPath[nPath-1]!='/' ){ zFree = sqlite3_mprintf("%s/", zPath); if( zFree==0 ){ rc = SQLITE_NOMEM; } zPath = (const char*)zFree; nPath++; } } /* Check that we're not inserting a duplicate entry -OR- updating an ** entry with a path, thereby making it into a duplicate. */ if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ ZipfileEntry *p; for(p=pTab->pFirstEntry; p; p=p->pNext){ if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ switch( sqlite3_vtab_on_conflict(pTab->db) ){ case SQLITE_IGNORE: { goto zipfile_update_done; } case SQLITE_REPLACE: { pOld2 = p; break; } default: { zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); rc = SQLITE_CONSTRAINT; break; } } break; } } } if( rc==SQLITE_OK ){ /* Create the new CDS record. */ pNew = zipfileNewEntry(zPath); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; pNew->cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&pNew->cds, mTime); pNew->cds.crc32 = iCrc32; pNew->cds.szCompressed = nData; pNew->cds.szUncompressed = (u32)sz; pNew->cds.iExternalAttr = (mode<<16); pNew->cds.iOffset = (u32)pTab->szCurrent; pNew->cds.nFile = (u16)nPath; pNew->mUnixTime = (u32)mTime; rc = zipfileAppendEntry(pTab, pNew, pData, nData); zipfileAddEntry(pTab, pOld, pNew); } } } if( rc==SQLITE_OK && (pOld || pOld2) ){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ pCsr->pCurrent = pCsr->pCurrent->pNext; pCsr->bNoop = 1; } } zipfileRemoveEntryFromList(pTab, pOld); zipfileRemoveEntryFromList(pTab, pOld2); } zipfile_update_done: sqlite3_free(pFree); sqlite3_free(zFree); return rc; } static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ u8 *a = aBuf; zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); zipfileWrite16(a, p->iDisk); zipfileWrite16(a, p->iFirstDisk); zipfileWrite16(a, p->nEntry); zipfileWrite16(a, p->nEntryTotal); zipfileWrite32(a, p->nSize); zipfileWrite32(a, p->iOffset); zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ return a-aBuf; } static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); return zipfileAppendData(pTab, pTab->aBuffer, nBuf); } /* ** Serialize the CDS structure into buffer aBuf[]. Return the number ** of bytes written. */ static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ u8 *a = aBuf; ZipfileCDS *pCDS = &pEntry->cds; if( pEntry->aExtra==0 ){ pCDS->nExtra = 9; } zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); zipfileWrite16(a, pCDS->iVersionMadeBy); zipfileWrite16(a, pCDS->iVersionExtract); zipfileWrite16(a, pCDS->flags); zipfileWrite16(a, pCDS->iCompression); zipfileWrite16(a, pCDS->mTime); zipfileWrite16(a, pCDS->mDate); zipfileWrite32(a, pCDS->crc32); zipfileWrite32(a, pCDS->szCompressed); zipfileWrite32(a, pCDS->szUncompressed); assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); zipfileWrite16(a, pCDS->nFile); zipfileWrite16(a, pCDS->nExtra); zipfileWrite16(a, pCDS->nComment); zipfileWrite16(a, pCDS->iDiskStart); zipfileWrite16(a, pCDS->iInternalAttr); zipfileWrite32(a, pCDS->iExternalAttr); zipfileWrite32(a, pCDS->iOffset); memcpy(a, pCDS->zFile, pCDS->nFile); a += pCDS->nFile; if( pEntry->aExtra ){ int n = (int)pCDS->nExtra + (int)pCDS->nComment; memcpy(a, pEntry->aExtra, n); a += n; }else{ assert( pCDS->nExtra==9 ); zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); } return a-aBuf; } static int zipfileCommit(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; if( pTab->pWriteFd ){ i64 iOffset = pTab->szCurrent; ZipfileEntry *p; ZipfileEOCD eocd; int nEntry = 0; /* Write out all entries */ for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ int n = zipfileSerializeCDS(p, pTab->aBuffer); rc = zipfileAppendData(pTab, pTab->aBuffer, n); nEntry++; } /* Write out the EOCD record */ eocd.iDisk = 0; eocd.iFirstDisk = 0; eocd.nEntry = (u16)nEntry; eocd.nEntryTotal = (u16)nEntry; eocd.nSize = (u32)(pTab->szCurrent - iOffset); eocd.iOffset = (u32)iOffset; rc = zipfileAppendEOCD(pTab, &eocd); zipfileCleanupTransaction(pTab); } return rc; } static int zipfileRollback(sqlite3_vtab *pVtab){ return zipfileCommit(pVtab); } static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( iId==pCsr->iId ) break; } return pCsr; } static void zipfileFunctionCds( sqlite3_context *context, int argc, sqlite3_value **argv ){ ZipfileCsr *pCsr; ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); assert( argc>0 ); pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); if( pCsr ){ ZipfileCDS *p = &pCsr->pCurrent->cds; char *zRes = sqlite3_mprintf("{" "\"version-made-by\" : %u, " "\"version-to-extract\" : %u, " "\"flags\" : %u, " "\"compression\" : %u, " "\"time\" : %u, " "\"date\" : %u, " "\"crc32\" : %u, " "\"compressed-size\" : %u, " "\"uncompressed-size\" : %u, " "\"file-name-length\" : %u, " "\"extra-field-length\" : %u, " "\"file-comment-length\" : %u, " "\"disk-number-start\" : %u, " "\"internal-attr\" : %u, " "\"external-attr\" : %u, " "\"offset\" : %u }", (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, (u32)p->flags, (u32)p->iCompression, (u32)p->mTime, (u32)p->mDate, (u32)p->crc32, (u32)p->szCompressed, (u32)p->szUncompressed, (u32)p->nFile, (u32)p->nExtra, (u32)p->nComment, (u32)p->iDiskStart, (u32)p->iInternalAttr, (u32)p->iExternalAttr, (u32)p->iOffset ); if( zRes==0 ){ sqlite3_result_error_nomem(context); }else{ sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); sqlite3_free(zRes); } } } /* ** xFindFunction method. */ static int zipfileFindFunction( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ void **ppArg /* OUT: User data for *pxFunc */ ){ if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ *pxFunc = zipfileFunctionCds; *ppArg = (void*)pVtab; return 1; } return 0; } typedef struct ZipfileBuffer ZipfileBuffer; struct ZipfileBuffer { u8 *a; /* Pointer to buffer */ int n; /* Size of buffer in bytes */ int nAlloc; /* Byte allocated at a[] */ }; typedef struct ZipfileCtx ZipfileCtx; struct ZipfileCtx { int nEntry; ZipfileBuffer body; ZipfileBuffer cds; }; static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){ if( pBuf->n+nByte>pBuf->nAlloc ){ u8 *aNew; sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; int nReq = pBuf->n + nByte; while( nNew<nReq ) nNew = nNew*2; aNew = sqlite3_realloc64(pBuf->a, nNew); if( aNew==0 ) return SQLITE_NOMEM; pBuf->a = aNew; pBuf->nAlloc = (int)nNew; } return SQLITE_OK; } /* ** xStep() callback for the zipfile() aggregate. This can be called in ** any of the following ways: ** ** SELECT zipfile(name,data) ... ** SELECT zipfile(name,mode,mtime,data) ... ** SELECT zipfile(name,mode,mtime,data,method) ... */ void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ ZipfileCtx *p; /* Aggregate function context */ ZipfileEntry e; /* New entry to add to zip archive */ sqlite3_value *pName = 0; sqlite3_value *pMode = 0; sqlite3_value *pMtime = 0; sqlite3_value *pData = 0; sqlite3_value *pMethod = 0; int bIsDir = 0; u32 mode; int rc = SQLITE_OK; char *zErr = 0; int iMethod = -1; /* Compression method to use (0 or 8) */ const u8 *aData = 0; /* Possibly compressed data for new entry */ int nData = 0; /* Size of aData[] in bytes */ int szUncompressed = 0; /* Size of data before compression */ u8 *aFree = 0; /* Free this before returning */ u32 iCrc32 = 0; /* crc32 of uncompressed data */ char *zName = 0; /* Path (name) of new entry */ int nName = 0; /* Size of zName in bytes */ char *zFree = 0; /* Free this before returning */ int nByte; memset(&e, 0, sizeof(e)); p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; /* Martial the arguments into stack variables */ if( nVal!=2 && nVal!=4 && nVal!=5 ){ zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); rc = SQLITE_ERROR; goto zipfile_step_out; } pName = apVal[0]; if( nVal==2 ){ pData = apVal[1]; }else{ pMode = apVal[1]; pMtime = apVal[2]; pData = apVal[3]; if( nVal==5 ){ pMethod = apVal[4]; } } /* Check that the 'name' parameter looks ok. */ zName = (char*)sqlite3_value_text(pName); nName = sqlite3_value_bytes(pName); if( zName==0 ){ zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); rc = SQLITE_ERROR; goto zipfile_step_out; } /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use ** deflate compression) or NULL (choose automatically). */ if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ iMethod = (int)sqlite3_value_int64(pMethod); if( iMethod!=0 && iMethod!=8 ){ zErr = sqlite3_mprintf("illegal method value: %d", iMethod); rc = SQLITE_ERROR; goto zipfile_step_out; } } /* Now inspect the data. If this is NULL, then the new entry must be a ** directory. Otherwise, figure out whether or not the data should ** be deflated or simply stored in the zip archive. */ if( sqlite3_value_type(pData)==SQLITE_NULL ){ bIsDir = 1; iMethod = 0; }else{ aData = sqlite3_value_blob(pData); szUncompressed = nData = sqlite3_value_bytes(pData); iCrc32 = crc32(0, aData, nData); if( iMethod<0 || iMethod==8 ){ int nOut = 0; rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); if( rc!=SQLITE_OK ){ goto zipfile_step_out; } if( iMethod==8 || nOut<nData ){ aData = aFree; nData = nOut; iMethod = 8; }else{ iMethod = 0; } } } /* Decode the "mode" argument. */ rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr); if( rc ) goto zipfile_step_out; /* Decode the "mtime" argument. */ e.mUnixTime = zipfileGetTime(pMtime); /* If this is a directory entry, ensure that there is exactly one '/' ** at the end of the path. Or, if this is not a directory and the path ** ends in '/' it is an error. */ if( bIsDir==0 ){ if( zName[nName-1]=='/' ){ zErr = sqlite3_mprintf("non-directory name must not end with /"); rc = SQLITE_ERROR; goto zipfile_step_out; } }else{ if( zName[nName-1]!='/' ){ zName = zFree = sqlite3_mprintf("%s/", zName); nName++; if( zName==0 ){ rc = SQLITE_NOMEM; goto zipfile_step_out; } }else{ while( nName>1 && zName[nName-2]=='/' ) nName--; } } /* Assemble the ZipfileEntry object for the new zip archive entry */ e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; e.cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); e.cds.crc32 = iCrc32; e.cds.szCompressed = nData; e.cds.szUncompressed = szUncompressed; e.cds.iExternalAttr = (mode<<16); e.cds.iOffset = p->body.n; e.cds.nFile = (u16)nName; e.cds.zFile = zName; /* Append the LFH to the body of the new archive */ nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); /* Append the data to the body of the new archive */ if( nData>0 ){ if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; memcpy(&p->body.a[p->body.n], aData, nData); p->body.n += nData; } /* Append the CDS record to the directory of the new archive */ nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); /* Increment the count of entries in the archive */ p->nEntry++; zipfile_step_out: sqlite3_free(aFree); sqlite3_free(zFree); if( rc ){ if( zErr ){ sqlite3_result_error(pCtx, zErr, -1); }else{ sqlite3_result_error_code(pCtx, rc); } } sqlite3_free(zErr); } /* ** xFinalize() callback for zipfile aggregate function. */ void zipfileFinal(sqlite3_context *pCtx){ ZipfileCtx *p; ZipfileEOCD eocd; sqlite3_int64 nZip; u8 *aZip; p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; if( p->nEntry>0 ){ memset(&eocd, 0, sizeof(eocd)); eocd.nEntry = (u16)p->nEntry; eocd.nEntryTotal = (u16)p->nEntry; eocd.nSize = p->cds.n; eocd.iOffset = p->body.n; nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; aZip = (u8*)sqlite3_malloc64(nZip); if( aZip==0 ){ sqlite3_result_error_nomem(pCtx); }else{ memcpy(aZip, p->body.a, p->body.n); memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree); } } sqlite3_free(p->body.a); sqlite3_free(p->cds.a); } /* ** Register the "zipfile" virtual table. */ static int zipfileRegister(sqlite3 *db){ static sqlite3_module zipfileModule = { 1, /* iVersion */ zipfileConnect, /* xCreate */ zipfileConnect, /* xConnect */ zipfileBestIndex, /* xBestIndex */ zipfileDisconnect, /* xDisconnect */ zipfileDisconnect, /* xDestroy */ zipfileOpen, /* xOpen - open a cursor */ zipfileClose, /* xClose - close a cursor */ zipfileFilter, /* xFilter - configure scan constraints */ zipfileNext, /* xNext - advance a cursor */ zipfileEof, /* xEof - check for end of scan */ zipfileColumn, /* xColumn - read data */ 0, /* xRowid - read data */ zipfileUpdate, /* xUpdate */ zipfileBegin, /* xBegin */ 0, /* xSync */ zipfileCommit, /* xCommit */ zipfileRollback, /* xRollback */ zipfileFindFunction, /* xFindMethod */ 0, /* xRename */ }; int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, zipfileStep, zipfileFinal ); } return rc; } #else /* SQLITE_OMIT_VIRTUALTABLE */ # define zipfileRegister(x) SQLITE_OK #endif #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_zipfile_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return zipfileRegister(db); }
./CrossVul/dataset_final_sorted/CWE-434/c/bad_1326_0
crossvul-cpp_data_good_1326_0
/* ** 2017-12-26 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ****************************************************************************** ** ** This file implements a virtual table for reading and writing ZIP archive ** files. ** ** Usage example: ** ** SELECT name, sz, datetime(mtime,'unixepoch') FROM zipfile($filename); ** ** Current limitations: ** ** * No support for encryption ** * No support for ZIP archives spanning multiple files ** * No support for zip64 extensions ** * Only the "inflate/deflate" (zlib) compression method is supported */ #include "sqlite3ext.h" SQLITE_EXTENSION_INIT1 #include <stdio.h> #include <string.h> #include <assert.h> #include <zlib.h> #ifndef SQLITE_OMIT_VIRTUALTABLE #ifndef SQLITE_AMALGAMATION typedef sqlite3_int64 i64; typedef unsigned char u8; typedef unsigned short u16; typedef unsigned long u32; #define MIN(a,b) ((a)<(b) ? (a) : (b)) #if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST) # define ALWAYS(X) (1) # define NEVER(X) (0) #elif !defined(NDEBUG) # define ALWAYS(X) ((X)?1:(assert(0),0)) # define NEVER(X) ((X)?(assert(0),1):0) #else # define ALWAYS(X) (X) # define NEVER(X) (X) #endif #endif /* SQLITE_AMALGAMATION */ /* ** Definitions for mode bitmasks S_IFDIR, S_IFREG and S_IFLNK. ** ** In some ways it would be better to obtain these values from system ** header files. But, the dependency is undesirable and (a) these ** have been stable for decades, (b) the values are part of POSIX and ** are also made explicit in [man stat], and (c) are part of the ** file format for zip archives. */ #ifndef S_IFDIR # define S_IFDIR 0040000 #endif #ifndef S_IFREG # define S_IFREG 0100000 #endif #ifndef S_IFLNK # define S_IFLNK 0120000 #endif static const char ZIPFILE_SCHEMA[] = "CREATE TABLE y(" "name PRIMARY KEY," /* 0: Name of file in zip archive */ "mode," /* 1: POSIX mode for file */ "mtime," /* 2: Last modification time (secs since 1970)*/ "sz," /* 3: Size of object */ "rawdata," /* 4: Raw data */ "data," /* 5: Uncompressed data */ "method," /* 6: Compression method (integer) */ "z HIDDEN" /* 7: Name of zip file */ ") WITHOUT ROWID;"; #define ZIPFILE_F_COLUMN_IDX 7 /* Index of column "file" in the above */ #define ZIPFILE_BUFFER_SIZE (64*1024) /* ** Magic numbers used to read and write zip files. ** ** ZIPFILE_NEWENTRY_MADEBY: ** Use this value for the "version-made-by" field in new zip file ** entries. The upper byte indicates "unix", and the lower byte ** indicates that the zip file matches pkzip specification 3.0. ** This is what info-zip seems to do. ** ** ZIPFILE_NEWENTRY_REQUIRED: ** Value for "version-required-to-extract" field of new entries. ** Version 2.0 is required to support folders and deflate compression. ** ** ZIPFILE_NEWENTRY_FLAGS: ** Value for "general-purpose-bit-flags" field of new entries. Bit ** 11 means "utf-8 filename and comment". ** ** ZIPFILE_SIGNATURE_CDS: ** First 4 bytes of a valid CDS record. ** ** ZIPFILE_SIGNATURE_LFH: ** First 4 bytes of a valid LFH record. ** ** ZIPFILE_SIGNATURE_EOCD ** First 4 bytes of a valid EOCD record. */ #define ZIPFILE_EXTRA_TIMESTAMP 0x5455 #define ZIPFILE_NEWENTRY_MADEBY ((3<<8) + 30) #define ZIPFILE_NEWENTRY_REQUIRED 20 #define ZIPFILE_NEWENTRY_FLAGS 0x800 #define ZIPFILE_SIGNATURE_CDS 0x02014b50 #define ZIPFILE_SIGNATURE_LFH 0x04034b50 #define ZIPFILE_SIGNATURE_EOCD 0x06054b50 /* ** The sizes of the fixed-size part of each of the three main data ** structures in a zip archive. */ #define ZIPFILE_LFH_FIXED_SZ 30 #define ZIPFILE_EOCD_FIXED_SZ 22 #define ZIPFILE_CDS_FIXED_SZ 46 /* *** 4.3.16 End of central directory record: *** *** end of central dir signature 4 bytes (0x06054b50) *** number of this disk 2 bytes *** number of the disk with the *** start of the central directory 2 bytes *** total number of entries in the *** central directory on this disk 2 bytes *** total number of entries in *** the central directory 2 bytes *** size of the central directory 4 bytes *** offset of start of central *** directory with respect to *** the starting disk number 4 bytes *** .ZIP file comment length 2 bytes *** .ZIP file comment (variable size) */ typedef struct ZipfileEOCD ZipfileEOCD; struct ZipfileEOCD { u16 iDisk; u16 iFirstDisk; u16 nEntry; u16 nEntryTotal; u32 nSize; u32 iOffset; }; /* *** 4.3.12 Central directory structure: *** *** ... *** *** central file header signature 4 bytes (0x02014b50) *** version made by 2 bytes *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** file comment length 2 bytes *** disk number start 2 bytes *** internal file attributes 2 bytes *** external file attributes 4 bytes *** relative offset of local header 4 bytes */ typedef struct ZipfileCDS ZipfileCDS; struct ZipfileCDS { u16 iVersionMadeBy; u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; u16 nComment; u16 iDiskStart; u16 iInternalAttr; u32 iExternalAttr; u32 iOffset; char *zFile; /* Filename (sqlite3_malloc()) */ }; /* *** 4.3.7 Local file header: *** *** local file header signature 4 bytes (0x04034b50) *** version needed to extract 2 bytes *** general purpose bit flag 2 bytes *** compression method 2 bytes *** last mod file time 2 bytes *** last mod file date 2 bytes *** crc-32 4 bytes *** compressed size 4 bytes *** uncompressed size 4 bytes *** file name length 2 bytes *** extra field length 2 bytes *** */ typedef struct ZipfileLFH ZipfileLFH; struct ZipfileLFH { u16 iVersionExtract; u16 flags; u16 iCompression; u16 mTime; u16 mDate; u32 crc32; u32 szCompressed; u32 szUncompressed; u16 nFile; u16 nExtra; }; typedef struct ZipfileEntry ZipfileEntry; struct ZipfileEntry { ZipfileCDS cds; /* Parsed CDS record */ u32 mUnixTime; /* Modification time, in UNIX format */ u8 *aExtra; /* cds.nExtra+cds.nComment bytes of extra data */ i64 iDataOff; /* Offset to data in file (if aData==0) */ u8 *aData; /* cds.szCompressed bytes of compressed data */ ZipfileEntry *pNext; /* Next element in in-memory CDS */ }; /* ** Cursor type for zipfile tables. */ typedef struct ZipfileCsr ZipfileCsr; struct ZipfileCsr { sqlite3_vtab_cursor base; /* Base class - must be first */ i64 iId; /* Cursor ID */ u8 bEof; /* True when at EOF */ u8 bNoop; /* If next xNext() call is no-op */ /* Used outside of write transactions */ FILE *pFile; /* Zip file */ i64 iNextOff; /* Offset of next record in central directory */ ZipfileEOCD eocd; /* Parse of central directory record */ ZipfileEntry *pFreeEntry; /* Free this list when cursor is closed or reset */ ZipfileEntry *pCurrent; /* Current entry */ ZipfileCsr *pCsrNext; /* Next cursor on same virtual table */ }; typedef struct ZipfileTab ZipfileTab; struct ZipfileTab { sqlite3_vtab base; /* Base class - must be first */ char *zFile; /* Zip file this table accesses (may be NULL) */ sqlite3 *db; /* Host database connection */ u8 *aBuffer; /* Temporary buffer used for various tasks */ ZipfileCsr *pCsrList; /* List of cursors */ i64 iNextCsrid; /* The following are used by write transactions only */ ZipfileEntry *pFirstEntry; /* Linked list of all files (if pWriteFd!=0) */ ZipfileEntry *pLastEntry; /* Last element in pFirstEntry list */ FILE *pWriteFd; /* File handle open on zip archive */ i64 szCurrent; /* Current size of zip archive */ i64 szOrig; /* Size of archive at start of transaction */ }; /* ** Set the error message contained in context ctx to the results of ** vprintf(zFmt, ...). */ static void zipfileCtxErrorMsg(sqlite3_context *ctx, const char *zFmt, ...){ char *zMsg = 0; va_list ap; va_start(ap, zFmt); zMsg = sqlite3_vmprintf(zFmt, ap); sqlite3_result_error(ctx, zMsg, -1); sqlite3_free(zMsg); va_end(ap); } /* ** If string zIn is quoted, dequote it in place. Otherwise, if the string ** is not quoted, do nothing. */ static void zipfileDequote(char *zIn){ char q = zIn[0]; if( q=='"' || q=='\'' || q=='`' || q=='[' ){ int iIn = 1; int iOut = 0; if( q=='[' ) q = ']'; while( ALWAYS(zIn[iIn]) ){ char c = zIn[iIn++]; if( c==q && zIn[iIn++]!=q ) break; zIn[iOut++] = c; } zIn[iOut] = '\0'; } } /* ** Construct a new ZipfileTab virtual table object. ** ** argv[0] -> module name ("zipfile") ** argv[1] -> database name ** argv[2] -> table name ** argv[...] -> "column name" and other module argument fields. */ static int zipfileConnect( sqlite3 *db, void *pAux, int argc, const char *const*argv, sqlite3_vtab **ppVtab, char **pzErr ){ int nByte = sizeof(ZipfileTab) + ZIPFILE_BUFFER_SIZE; int nFile = 0; const char *zFile = 0; ZipfileTab *pNew = 0; int rc; /* If the table name is not "zipfile", require that the argument be ** specified. This stops zipfile tables from being created as: ** ** CREATE VIRTUAL TABLE zzz USING zipfile(); ** ** It does not prevent: ** ** CREATE VIRTUAL TABLE zipfile USING zipfile(); */ assert( 0==sqlite3_stricmp(argv[0], "zipfile") ); if( (0!=sqlite3_stricmp(argv[2], "zipfile") && argc<4) || argc>4 ){ *pzErr = sqlite3_mprintf("zipfile constructor requires one argument"); return SQLITE_ERROR; } if( argc>3 ){ zFile = argv[3]; nFile = (int)strlen(zFile)+1; } rc = sqlite3_declare_vtab(db, ZIPFILE_SCHEMA); if( rc==SQLITE_OK ){ pNew = (ZipfileTab*)sqlite3_malloc64((sqlite3_int64)nByte+nFile); if( pNew==0 ) return SQLITE_NOMEM; memset(pNew, 0, nByte+nFile); pNew->db = db; pNew->aBuffer = (u8*)&pNew[1]; if( zFile ){ pNew->zFile = (char*)&pNew->aBuffer[ZIPFILE_BUFFER_SIZE]; memcpy(pNew->zFile, zFile, nFile); zipfileDequote(pNew->zFile); } } *ppVtab = (sqlite3_vtab*)pNew; return rc; } /* ** Free the ZipfileEntry structure indicated by the only argument. */ static void zipfileEntryFree(ZipfileEntry *p){ if( p ){ sqlite3_free(p->cds.zFile); sqlite3_free(p); } } /* ** Release resources that should be freed at the end of a write ** transaction. */ static void zipfileCleanupTransaction(ZipfileTab *pTab){ ZipfileEntry *pEntry; ZipfileEntry *pNext; if( pTab->pWriteFd ){ fclose(pTab->pWriteFd); pTab->pWriteFd = 0; } for(pEntry=pTab->pFirstEntry; pEntry; pEntry=pNext){ pNext = pEntry->pNext; zipfileEntryFree(pEntry); } pTab->pFirstEntry = 0; pTab->pLastEntry = 0; pTab->szCurrent = 0; pTab->szOrig = 0; } /* ** This method is the destructor for zipfile vtab objects. */ static int zipfileDisconnect(sqlite3_vtab *pVtab){ zipfileCleanupTransaction((ZipfileTab*)pVtab); sqlite3_free(pVtab); return SQLITE_OK; } /* ** Constructor for a new ZipfileCsr object. */ static int zipfileOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCsr){ ZipfileTab *pTab = (ZipfileTab*)p; ZipfileCsr *pCsr; pCsr = sqlite3_malloc(sizeof(*pCsr)); *ppCsr = (sqlite3_vtab_cursor*)pCsr; if( pCsr==0 ){ return SQLITE_NOMEM; } memset(pCsr, 0, sizeof(*pCsr)); pCsr->iId = ++pTab->iNextCsrid; pCsr->pCsrNext = pTab->pCsrList; pTab->pCsrList = pCsr; return SQLITE_OK; } /* ** Reset a cursor back to the state it was in when first returned ** by zipfileOpen(). */ static void zipfileResetCursor(ZipfileCsr *pCsr){ ZipfileEntry *p; ZipfileEntry *pNext; pCsr->bEof = 0; if( pCsr->pFile ){ fclose(pCsr->pFile); pCsr->pFile = 0; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; } for(p=pCsr->pFreeEntry; p; p=pNext){ pNext = p->pNext; zipfileEntryFree(p); } } /* ** Destructor for an ZipfileCsr. */ static int zipfileClose(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileTab *pTab = (ZipfileTab*)(pCsr->base.pVtab); ZipfileCsr **pp; zipfileResetCursor(pCsr); /* Remove this cursor from the ZipfileTab.pCsrList list. */ for(pp=&pTab->pCsrList; *pp!=pCsr; pp=&((*pp)->pCsrNext)); *pp = pCsr->pCsrNext; sqlite3_free(pCsr); return SQLITE_OK; } /* ** Set the error message for the virtual table associated with cursor ** pCsr to the results of vprintf(zFmt, ...). */ static void zipfileTableErr(ZipfileTab *pTab, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pTab->base.zErrMsg); pTab->base.zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } static void zipfileCursorErr(ZipfileCsr *pCsr, const char *zFmt, ...){ va_list ap; va_start(ap, zFmt); sqlite3_free(pCsr->base.pVtab->zErrMsg); pCsr->base.pVtab->zErrMsg = sqlite3_vmprintf(zFmt, ap); va_end(ap); } /* ** Read nRead bytes of data from offset iOff of file pFile into buffer ** aRead[]. Return SQLITE_OK if successful, or an SQLite error code ** otherwise. ** ** If an error does occur, output variable (*pzErrmsg) may be set to point ** to an English language error message. It is the responsibility of the ** caller to eventually free this buffer using ** sqlite3_free(). */ static int zipfileReadData( FILE *pFile, /* Read from this file */ u8 *aRead, /* Read into this buffer */ int nRead, /* Number of bytes to read */ i64 iOff, /* Offset to read from */ char **pzErrmsg /* OUT: Error message (from sqlite3_malloc) */ ){ size_t n; fseek(pFile, (long)iOff, SEEK_SET); n = fread(aRead, 1, nRead, pFile); if( (int)n!=nRead ){ *pzErrmsg = sqlite3_mprintf("error in fread()"); return SQLITE_ERROR; } return SQLITE_OK; } static int zipfileAppendData( ZipfileTab *pTab, const u8 *aWrite, int nWrite ){ size_t n; fseek(pTab->pWriteFd, (long)pTab->szCurrent, SEEK_SET); n = fwrite(aWrite, 1, nWrite, pTab->pWriteFd); if( (int)n!=nWrite ){ pTab->base.zErrMsg = sqlite3_mprintf("error in fwrite()"); return SQLITE_ERROR; } pTab->szCurrent += nWrite; return SQLITE_OK; } /* ** Read and return a 16-bit little-endian unsigned integer from buffer aBuf. */ static u16 zipfileGetU16(const u8 *aBuf){ return (aBuf[1] << 8) + aBuf[0]; } /* ** Read and return a 32-bit little-endian unsigned integer from buffer aBuf. */ static u32 zipfileGetU32(const u8 *aBuf){ return ((u32)(aBuf[3]) << 24) + ((u32)(aBuf[2]) << 16) + ((u32)(aBuf[1]) << 8) + ((u32)(aBuf[0]) << 0); } /* ** Write a 16-bit little endiate integer into buffer aBuf. */ static void zipfilePutU16(u8 *aBuf, u16 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; } /* ** Write a 32-bit little endiate integer into buffer aBuf. */ static void zipfilePutU32(u8 *aBuf, u32 val){ aBuf[0] = val & 0xFF; aBuf[1] = (val>>8) & 0xFF; aBuf[2] = (val>>16) & 0xFF; aBuf[3] = (val>>24) & 0xFF; } #define zipfileRead32(aBuf) ( aBuf+=4, zipfileGetU32(aBuf-4) ) #define zipfileRead16(aBuf) ( aBuf+=2, zipfileGetU16(aBuf-2) ) #define zipfileWrite32(aBuf,val) { zipfilePutU32(aBuf,val); aBuf+=4; } #define zipfileWrite16(aBuf,val) { zipfilePutU16(aBuf,val); aBuf+=2; } /* ** Magic numbers used to read CDS records. */ #define ZIPFILE_CDS_NFILE_OFF 28 #define ZIPFILE_CDS_SZCOMPRESSED_OFF 20 /* ** Decode the CDS record in buffer aBuf into (*pCDS). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadCDS(u8 *aBuf, ZipfileCDS *pCDS){ u8 *aRead = aBuf; u32 sig = zipfileRead32(aRead); int rc = SQLITE_OK; if( sig!=ZIPFILE_SIGNATURE_CDS ){ rc = SQLITE_ERROR; }else{ pCDS->iVersionMadeBy = zipfileRead16(aRead); pCDS->iVersionExtract = zipfileRead16(aRead); pCDS->flags = zipfileRead16(aRead); pCDS->iCompression = zipfileRead16(aRead); pCDS->mTime = zipfileRead16(aRead); pCDS->mDate = zipfileRead16(aRead); pCDS->crc32 = zipfileRead32(aRead); pCDS->szCompressed = zipfileRead32(aRead); pCDS->szUncompressed = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); pCDS->nFile = zipfileRead16(aRead); pCDS->nExtra = zipfileRead16(aRead); pCDS->nComment = zipfileRead16(aRead); pCDS->iDiskStart = zipfileRead16(aRead); pCDS->iInternalAttr = zipfileRead16(aRead); pCDS->iExternalAttr = zipfileRead32(aRead); pCDS->iOffset = zipfileRead32(aRead); assert( aRead==&aBuf[ZIPFILE_CDS_FIXED_SZ] ); } return rc; } /* ** Decode the LFH record in buffer aBuf into (*pLFH). Return SQLITE_ERROR ** if the record is not well-formed, or SQLITE_OK otherwise. */ static int zipfileReadLFH( u8 *aBuffer, ZipfileLFH *pLFH ){ u8 *aRead = aBuffer; int rc = SQLITE_OK; u32 sig = zipfileRead32(aRead); if( sig!=ZIPFILE_SIGNATURE_LFH ){ rc = SQLITE_ERROR; }else{ pLFH->iVersionExtract = zipfileRead16(aRead); pLFH->flags = zipfileRead16(aRead); pLFH->iCompression = zipfileRead16(aRead); pLFH->mTime = zipfileRead16(aRead); pLFH->mDate = zipfileRead16(aRead); pLFH->crc32 = zipfileRead32(aRead); pLFH->szCompressed = zipfileRead32(aRead); pLFH->szUncompressed = zipfileRead32(aRead); pLFH->nFile = zipfileRead16(aRead); pLFH->nExtra = zipfileRead16(aRead); } return rc; } /* ** Buffer aExtra (size nExtra bytes) contains zip archive "extra" fields. ** Scan through this buffer to find an "extra-timestamp" field. If one ** exists, extract the 32-bit modification-timestamp from it and store ** the value in output parameter *pmTime. ** ** Zero is returned if no extra-timestamp record could be found (and so ** *pmTime is left unchanged), or non-zero otherwise. ** ** The general format of an extra field is: ** ** Header ID 2 bytes ** Data Size 2 bytes ** Data N bytes */ static int zipfileScanExtra(u8 *aExtra, int nExtra, u32 *pmTime){ int ret = 0; u8 *p = aExtra; u8 *pEnd = &aExtra[nExtra]; while( p<pEnd ){ u16 id = zipfileRead16(p); u16 nByte = zipfileRead16(p); switch( id ){ case ZIPFILE_EXTRA_TIMESTAMP: { u8 b = p[0]; if( b & 0x01 ){ /* 0x01 -> modtime is present */ *pmTime = zipfileGetU32(&p[1]); ret = 1; } break; } } p += nByte; } return ret; } /* ** Convert the standard MS-DOS timestamp stored in the mTime and mDate ** fields of the CDS structure passed as the only argument to a 32-bit ** UNIX seconds-since-the-epoch timestamp. Return the result. ** ** "Standard" MS-DOS time format: ** ** File modification time: ** Bits 00-04: seconds divided by 2 ** Bits 05-10: minute ** Bits 11-15: hour ** File modification date: ** Bits 00-04: day ** Bits 05-08: month (1-12) ** Bits 09-15: years from 1980 ** ** https://msdn.microsoft.com/en-us/library/9kkf9tah.aspx */ static u32 zipfileMtime(ZipfileCDS *pCDS){ int Y = (1980 + ((pCDS->mDate >> 9) & 0x7F)); int M = ((pCDS->mDate >> 5) & 0x0F); int D = (pCDS->mDate & 0x1F); int B = -13; int sec = (pCDS->mTime & 0x1F)*2; int min = (pCDS->mTime >> 5) & 0x3F; int hr = (pCDS->mTime >> 11) & 0x1F; i64 JD; /* JD = INT(365.25 * (Y+4716)) + INT(30.6001 * (M+1)) + D + B - 1524.5 */ /* Calculate the JD in seconds for noon on the day in question */ if( M<3 ){ Y = Y-1; M = M+12; } JD = (i64)(24*60*60) * ( (int)(365.25 * (Y + 4716)) + (int)(30.6001 * (M + 1)) + D + B - 1524 ); /* Correct the JD for the time within the day */ JD += (hr-12) * 3600 + min * 60 + sec; /* Convert JD to unix timestamp (the JD epoch is 2440587.5) */ return (u32)(JD - (i64)(24405875) * 24*60*6); } /* ** The opposite of zipfileMtime(). This function populates the mTime and ** mDate fields of the CDS structure passed as the first argument according ** to the UNIX timestamp value passed as the second. */ static void zipfileMtimeToDos(ZipfileCDS *pCds, u32 mUnixTime){ /* Convert unix timestamp to JD (2440588 is noon on 1/1/1970) */ i64 JD = (i64)2440588 + mUnixTime / (24*60*60); int A, B, C, D, E; int yr, mon, day; int hr, min, sec; A = (int)((JD - 1867216.25)/36524.25); A = (int)(JD + 1 + A - (A/4)); B = A + 1524; C = (int)((B - 122.1)/365.25); D = (36525*(C&32767))/100; E = (int)((B-D)/30.6001); day = B - D - (int)(30.6001*E); mon = (E<14 ? E-1 : E-13); yr = mon>2 ? C-4716 : C-4715; hr = (mUnixTime % (24*60*60)) / (60*60); min = (mUnixTime % (60*60)) / 60; sec = (mUnixTime % 60); if( yr>=1980 ){ pCds->mDate = (u16)(day + (mon << 5) + ((yr-1980) << 9)); pCds->mTime = (u16)(sec/2 + (min<<5) + (hr<<11)); }else{ pCds->mDate = pCds->mTime = 0; } assert( mUnixTime<315507600 || mUnixTime==zipfileMtime(pCds) || ((mUnixTime % 2) && mUnixTime-1==zipfileMtime(pCds)) /* || (mUnixTime % 2) */ ); } /* ** If aBlob is not NULL, then it is a pointer to a buffer (nBlob bytes in ** size) containing an entire zip archive image. Or, if aBlob is NULL, ** then pFile is a file-handle open on a zip file. In either case, this ** function creates a ZipfileEntry object based on the zip archive entry ** for which the CDS record is at offset iOff. ** ** If successful, SQLITE_OK is returned and (*ppEntry) set to point to ** the new object. Otherwise, an SQLite error code is returned and the ** final value of (*ppEntry) undefined. */ static int zipfileGetEntry( ZipfileTab *pTab, /* Store any error message here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* If aBlob==0, read from this file */ i64 iOff, /* Offset of CDS record */ ZipfileEntry **ppEntry /* OUT: Pointer to new object */ ){ u8 *aRead; char **pzErr = &pTab->base.zErrMsg; int rc = SQLITE_OK; if( aBlob==0 ){ aRead = pTab->aBuffer; rc = zipfileReadData(pFile, aRead, ZIPFILE_CDS_FIXED_SZ, iOff, pzErr); }else{ aRead = (u8*)&aBlob[iOff]; } if( rc==SQLITE_OK ){ sqlite3_int64 nAlloc; ZipfileEntry *pNew; int nFile = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF]); int nExtra = zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+2]); nExtra += zipfileGetU16(&aRead[ZIPFILE_CDS_NFILE_OFF+4]); nAlloc = sizeof(ZipfileEntry) + nExtra; if( aBlob ){ nAlloc += zipfileGetU32(&aRead[ZIPFILE_CDS_SZCOMPRESSED_OFF]); } pNew = (ZipfileEntry*)sqlite3_malloc64(nAlloc); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ memset(pNew, 0, sizeof(ZipfileEntry)); rc = zipfileReadCDS(aRead, &pNew->cds); if( rc!=SQLITE_OK ){ *pzErr = sqlite3_mprintf("failed to read CDS at offset %lld", iOff); }else if( aBlob==0 ){ rc = zipfileReadData( pFile, aRead, nExtra+nFile, iOff+ZIPFILE_CDS_FIXED_SZ, pzErr ); }else{ aRead = (u8*)&aBlob[iOff + ZIPFILE_CDS_FIXED_SZ]; } } if( rc==SQLITE_OK ){ u32 *pt = &pNew->mUnixTime; pNew->cds.zFile = sqlite3_mprintf("%.*s", nFile, aRead); pNew->aExtra = (u8*)&pNew[1]; memcpy(pNew->aExtra, &aRead[nFile], nExtra); if( pNew->cds.zFile==0 ){ rc = SQLITE_NOMEM; }else if( 0==zipfileScanExtra(&aRead[nFile], pNew->cds.nExtra, pt) ){ pNew->mUnixTime = zipfileMtime(&pNew->cds); } } if( rc==SQLITE_OK ){ static const int szFix = ZIPFILE_LFH_FIXED_SZ; ZipfileLFH lfh; if( pFile ){ rc = zipfileReadData(pFile, aRead, szFix, pNew->cds.iOffset, pzErr); }else{ aRead = (u8*)&aBlob[pNew->cds.iOffset]; } rc = zipfileReadLFH(aRead, &lfh); if( rc==SQLITE_OK ){ pNew->iDataOff = pNew->cds.iOffset + ZIPFILE_LFH_FIXED_SZ; pNew->iDataOff += lfh.nFile + lfh.nExtra; if( aBlob && pNew->cds.szCompressed ){ pNew->aData = &pNew->aExtra[nExtra]; memcpy(pNew->aData, &aBlob[pNew->iDataOff], pNew->cds.szCompressed); } }else{ *pzErr = sqlite3_mprintf("failed to read LFH at offset %d", (int)pNew->cds.iOffset ); } } if( rc!=SQLITE_OK ){ zipfileEntryFree(pNew); }else{ *ppEntry = pNew; } } return rc; } /* ** Advance an ZipfileCsr to its next row of output. */ static int zipfileNext(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; int rc = SQLITE_OK; if( pCsr->pFile ){ i64 iEof = pCsr->eocd.iOffset + pCsr->eocd.nSize; zipfileEntryFree(pCsr->pCurrent); pCsr->pCurrent = 0; if( pCsr->iNextOff>=iEof ){ pCsr->bEof = 1; }else{ ZipfileEntry *p = 0; ZipfileTab *pTab = (ZipfileTab*)(cur->pVtab); rc = zipfileGetEntry(pTab, 0, 0, pCsr->pFile, pCsr->iNextOff, &p); if( rc==SQLITE_OK ){ pCsr->iNextOff += ZIPFILE_CDS_FIXED_SZ; pCsr->iNextOff += (int)p->cds.nExtra + p->cds.nFile + p->cds.nComment; } pCsr->pCurrent = p; } }else{ if( !pCsr->bNoop ){ pCsr->pCurrent = pCsr->pCurrent->pNext; } if( pCsr->pCurrent==0 ){ pCsr->bEof = 1; } } pCsr->bNoop = 0; return rc; } static void zipfileFree(void *p) { sqlite3_free(p); } /* ** Buffer aIn (size nIn bytes) contains compressed data. Uncompressed, the ** size is nOut bytes. This function uncompresses the data and sets the ** return value in context pCtx to the result (a blob). ** ** If an error occurs, an error code is left in pCtx instead. */ static void zipfileInflate( sqlite3_context *pCtx, /* Store result here */ const u8 *aIn, /* Compressed data */ int nIn, /* Size of buffer aIn[] in bytes */ int nOut /* Expected output size */ ){ u8 *aRes = sqlite3_malloc(nOut); if( aRes==0 ){ sqlite3_result_error_nomem(pCtx); }else{ int err; z_stream str; memset(&str, 0, sizeof(str)); str.next_in = (Byte*)aIn; str.avail_in = nIn; str.next_out = (Byte*)aRes; str.avail_out = nOut; err = inflateInit2(&str, -15); if( err!=Z_OK ){ zipfileCtxErrorMsg(pCtx, "inflateInit2() failed (%d)", err); }else{ err = inflate(&str, Z_NO_FLUSH); if( err!=Z_STREAM_END ){ zipfileCtxErrorMsg(pCtx, "inflate() failed (%d)", err); }else{ sqlite3_result_blob(pCtx, aRes, nOut, zipfileFree); aRes = 0; } } sqlite3_free(aRes); inflateEnd(&str); } } /* ** Buffer aIn (size nIn bytes) contains uncompressed data. This function ** compresses it and sets (*ppOut) to point to a buffer containing the ** compressed data. The caller is responsible for eventually calling ** sqlite3_free() to release buffer (*ppOut). Before returning, (*pnOut) ** is set to the size of buffer (*ppOut) in bytes. ** ** If no error occurs, SQLITE_OK is returned. Otherwise, an SQLite error ** code is returned and an error message left in virtual-table handle ** pTab. The values of (*ppOut) and (*pnOut) are left unchanged in this ** case. */ static int zipfileDeflate( const u8 *aIn, int nIn, /* Input */ u8 **ppOut, int *pnOut, /* Output */ char **pzErr /* OUT: Error message */ ){ int rc = SQLITE_OK; sqlite3_int64 nAlloc; z_stream str; u8 *aOut; memset(&str, 0, sizeof(str)); str.next_in = (Bytef*)aIn; str.avail_in = nIn; deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); nAlloc = deflateBound(&str, nIn); aOut = (u8*)sqlite3_malloc64(nAlloc); if( aOut==0 ){ rc = SQLITE_NOMEM; }else{ int res; str.next_out = aOut; str.avail_out = nAlloc; deflateInit2(&str, 9, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY); res = deflate(&str, Z_FINISH); if( res==Z_STREAM_END ){ *ppOut = aOut; *pnOut = (int)str.total_out; }else{ sqlite3_free(aOut); *pzErr = sqlite3_mprintf("zipfile: deflate() error"); rc = SQLITE_ERROR; } deflateEnd(&str); } return rc; } /* ** Return values of columns for the row at which the series_cursor ** is currently pointing. */ static int zipfileColumn( sqlite3_vtab_cursor *cur, /* The cursor */ sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ int i /* Which column to return */ ){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; ZipfileCDS *pCDS = &pCsr->pCurrent->cds; int rc = SQLITE_OK; switch( i ){ case 0: /* name */ sqlite3_result_text(ctx, pCDS->zFile, -1, SQLITE_TRANSIENT); break; case 1: /* mode */ /* TODO: Whether or not the following is correct surely depends on ** the platform on which the archive was created. */ sqlite3_result_int(ctx, pCDS->iExternalAttr >> 16); break; case 2: { /* mtime */ sqlite3_result_int64(ctx, pCsr->pCurrent->mUnixTime); break; } case 3: { /* sz */ if( sqlite3_vtab_nochange(ctx)==0 ){ sqlite3_result_int64(ctx, pCDS->szUncompressed); } break; } case 4: /* rawdata */ if( sqlite3_vtab_nochange(ctx) ) break; case 5: { /* data */ if( i==4 || pCDS->iCompression==0 || pCDS->iCompression==8 ){ int sz = pCDS->szCompressed; int szFinal = pCDS->szUncompressed; if( szFinal>0 ){ u8 *aBuf; u8 *aFree = 0; if( pCsr->pCurrent->aData ){ aBuf = pCsr->pCurrent->aData; }else{ aBuf = aFree = sqlite3_malloc64(sz); if( aBuf==0 ){ rc = SQLITE_NOMEM; }else{ FILE *pFile = pCsr->pFile; if( pFile==0 ){ pFile = ((ZipfileTab*)(pCsr->base.pVtab))->pWriteFd; } rc = zipfileReadData(pFile, aBuf, sz, pCsr->pCurrent->iDataOff, &pCsr->base.pVtab->zErrMsg ); } } if( rc==SQLITE_OK ){ if( i==5 && pCDS->iCompression ){ zipfileInflate(ctx, aBuf, sz, szFinal); }else{ sqlite3_result_blob(ctx, aBuf, sz, SQLITE_TRANSIENT); } } sqlite3_free(aFree); }else{ /* Figure out if this is a directory or a zero-sized file. Consider ** it to be a directory either if the mode suggests so, or if ** the final character in the name is '/'. */ u32 mode = pCDS->iExternalAttr >> 16; if( !(mode & S_IFDIR) && pCDS->zFile[pCDS->nFile-1]!='/' ){ sqlite3_result_blob(ctx, "", 0, SQLITE_STATIC); } } } break; } case 6: /* method */ sqlite3_result_int(ctx, pCDS->iCompression); break; default: /* z */ assert( i==7 ); sqlite3_result_int64(ctx, pCsr->iId); break; } return rc; } /* ** Return TRUE if the cursor is at EOF. */ static int zipfileEof(sqlite3_vtab_cursor *cur){ ZipfileCsr *pCsr = (ZipfileCsr*)cur; return pCsr->bEof; } /* ** If aBlob is not NULL, then it points to a buffer nBlob bytes in size ** containing an entire zip archive image. Or, if aBlob is NULL, then pFile ** is guaranteed to be a file-handle open on a zip file. ** ** This function attempts to locate the EOCD record within the zip archive ** and populate *pEOCD with the results of decoding it. SQLITE_OK is ** returned if successful. Otherwise, an SQLite error code is returned and ** an English language error message may be left in virtual-table pTab. */ static int zipfileReadEOCD( ZipfileTab *pTab, /* Return errors here */ const u8 *aBlob, /* Pointer to in-memory file image */ int nBlob, /* Size of aBlob[] in bytes */ FILE *pFile, /* Read from this file if aBlob==0 */ ZipfileEOCD *pEOCD /* Object to populate */ ){ u8 *aRead = pTab->aBuffer; /* Temporary buffer */ int nRead; /* Bytes to read from file */ int rc = SQLITE_OK; if( aBlob==0 ){ i64 iOff; /* Offset to read from */ i64 szFile; /* Total size of file in bytes */ fseek(pFile, 0, SEEK_END); szFile = (i64)ftell(pFile); if( szFile==0 ){ memset(pEOCD, 0, sizeof(ZipfileEOCD)); return SQLITE_OK; } nRead = (int)(MIN(szFile, ZIPFILE_BUFFER_SIZE)); iOff = szFile - nRead; rc = zipfileReadData(pFile, aRead, nRead, iOff, &pTab->base.zErrMsg); }else{ nRead = (int)(MIN(nBlob, ZIPFILE_BUFFER_SIZE)); aRead = (u8*)&aBlob[nBlob-nRead]; } if( rc==SQLITE_OK ){ int i; /* Scan backwards looking for the signature bytes */ for(i=nRead-20; i>=0; i--){ if( aRead[i]==0x50 && aRead[i+1]==0x4b && aRead[i+2]==0x05 && aRead[i+3]==0x06 ){ break; } } if( i<0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "cannot find end of central directory record" ); return SQLITE_ERROR; } aRead += i+4; pEOCD->iDisk = zipfileRead16(aRead); pEOCD->iFirstDisk = zipfileRead16(aRead); pEOCD->nEntry = zipfileRead16(aRead); pEOCD->nEntryTotal = zipfileRead16(aRead); pEOCD->nSize = zipfileRead32(aRead); pEOCD->iOffset = zipfileRead32(aRead); } return rc; } /* ** Add object pNew to the linked list that begins at ZipfileTab.pFirstEntry ** and ends with pLastEntry. If argument pBefore is NULL, then pNew is added ** to the end of the list. Otherwise, it is added to the list immediately ** before pBefore (which is guaranteed to be a part of said list). */ static void zipfileAddEntry( ZipfileTab *pTab, ZipfileEntry *pBefore, ZipfileEntry *pNew ){ assert( (pTab->pFirstEntry==0)==(pTab->pLastEntry==0) ); assert( pNew->pNext==0 ); if( pBefore==0 ){ if( pTab->pFirstEntry==0 ){ pTab->pFirstEntry = pTab->pLastEntry = pNew; }else{ assert( pTab->pLastEntry->pNext==0 ); pTab->pLastEntry->pNext = pNew; pTab->pLastEntry = pNew; } }else{ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; *pp!=pBefore; pp=&((*pp)->pNext)); pNew->pNext = pBefore; *pp = pNew; } } static int zipfileLoadDirectory(ZipfileTab *pTab, const u8 *aBlob, int nBlob){ ZipfileEOCD eocd; int rc; int i; i64 iOff; rc = zipfileReadEOCD(pTab, aBlob, nBlob, pTab->pWriteFd, &eocd); iOff = eocd.iOffset; for(i=0; rc==SQLITE_OK && i<eocd.nEntry; i++){ ZipfileEntry *pNew = 0; rc = zipfileGetEntry(pTab, aBlob, nBlob, pTab->pWriteFd, iOff, &pNew); if( rc==SQLITE_OK ){ zipfileAddEntry(pTab, 0, pNew); iOff += ZIPFILE_CDS_FIXED_SZ; iOff += (int)pNew->cds.nExtra + pNew->cds.nFile + pNew->cds.nComment; } } return rc; } /* ** xFilter callback. */ static int zipfileFilter( sqlite3_vtab_cursor *cur, int idxNum, const char *idxStr, int argc, sqlite3_value **argv ){ ZipfileTab *pTab = (ZipfileTab*)cur->pVtab; ZipfileCsr *pCsr = (ZipfileCsr*)cur; const char *zFile = 0; /* Zip file to scan */ int rc = SQLITE_OK; /* Return Code */ int bInMemory = 0; /* True for an in-memory zipfile */ zipfileResetCursor(pCsr); if( pTab->zFile ){ zFile = pTab->zFile; }else if( idxNum==0 ){ zipfileCursorErr(pCsr, "zipfile() function requires an argument"); return SQLITE_ERROR; }else if( sqlite3_value_type(argv[0])==SQLITE_BLOB ){ const u8 *aBlob = (const u8*)sqlite3_value_blob(argv[0]); int nBlob = sqlite3_value_bytes(argv[0]); assert( pTab->pFirstEntry==0 ); rc = zipfileLoadDirectory(pTab, aBlob, nBlob); pCsr->pFreeEntry = pTab->pFirstEntry; pTab->pFirstEntry = pTab->pLastEntry = 0; if( rc!=SQLITE_OK ) return rc; bInMemory = 1; }else{ zFile = (const char*)sqlite3_value_text(argv[0]); } if( 0==pTab->pWriteFd && 0==bInMemory ){ pCsr->pFile = fopen(zFile, "rb"); if( pCsr->pFile==0 ){ zipfileCursorErr(pCsr, "cannot open file: %s", zFile); rc = SQLITE_ERROR; }else{ rc = zipfileReadEOCD(pTab, 0, 0, pCsr->pFile, &pCsr->eocd); if( rc==SQLITE_OK ){ if( pCsr->eocd.nEntry==0 ){ pCsr->bEof = 1; }else{ pCsr->iNextOff = pCsr->eocd.iOffset; rc = zipfileNext(cur); } } } }else{ pCsr->bNoop = 1; pCsr->pCurrent = pCsr->pFreeEntry ? pCsr->pFreeEntry : pTab->pFirstEntry; rc = zipfileNext(cur); } return rc; } /* ** xBestIndex callback. */ static int zipfileBestIndex( sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo ){ int i; int idx = -1; int unusable = 0; for(i=0; i<pIdxInfo->nConstraint; i++){ const struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i]; if( pCons->iColumn!=ZIPFILE_F_COLUMN_IDX ) continue; if( pCons->usable==0 ){ unusable = 1; }else if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){ idx = i; } } if( idx>=0 ){ pIdxInfo->aConstraintUsage[idx].argvIndex = 1; pIdxInfo->aConstraintUsage[idx].omit = 1; pIdxInfo->estimatedCost = 1000.0; pIdxInfo->idxNum = 1; }else if( unusable ){ return SQLITE_CONSTRAINT; } return SQLITE_OK; } static ZipfileEntry *zipfileNewEntry(const char *zPath){ ZipfileEntry *pNew; pNew = sqlite3_malloc(sizeof(ZipfileEntry)); if( pNew ){ memset(pNew, 0, sizeof(ZipfileEntry)); pNew->cds.zFile = sqlite3_mprintf("%s", zPath); if( pNew->cds.zFile==0 ){ sqlite3_free(pNew); pNew = 0; } } return pNew; } static int zipfileSerializeLFH(ZipfileEntry *pEntry, u8 *aBuf){ ZipfileCDS *pCds = &pEntry->cds; u8 *a = aBuf; pCds->nExtra = 9; /* Write the LFH itself */ zipfileWrite32(a, ZIPFILE_SIGNATURE_LFH); zipfileWrite16(a, pCds->iVersionExtract); zipfileWrite16(a, pCds->flags); zipfileWrite16(a, pCds->iCompression); zipfileWrite16(a, pCds->mTime); zipfileWrite16(a, pCds->mDate); zipfileWrite32(a, pCds->crc32); zipfileWrite32(a, pCds->szCompressed); zipfileWrite32(a, pCds->szUncompressed); zipfileWrite16(a, (u16)pCds->nFile); zipfileWrite16(a, pCds->nExtra); assert( a==&aBuf[ZIPFILE_LFH_FIXED_SZ] ); /* Add the file name */ memcpy(a, pCds->zFile, (int)pCds->nFile); a += (int)pCds->nFile; /* The "extra" data */ zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); return a-aBuf; } static int zipfileAppendEntry( ZipfileTab *pTab, ZipfileEntry *pEntry, const u8 *pData, int nData ){ u8 *aBuf = pTab->aBuffer; int nBuf; int rc; nBuf = zipfileSerializeLFH(pEntry, aBuf); rc = zipfileAppendData(pTab, aBuf, nBuf); if( rc==SQLITE_OK ){ pEntry->iDataOff = pTab->szCurrent; rc = zipfileAppendData(pTab, pData, nData); } return rc; } static int zipfileGetMode( sqlite3_value *pVal, int bIsDir, /* If true, default to directory */ u32 *pMode, /* OUT: Mode value */ char **pzErr /* OUT: Error message */ ){ const char *z = (const char*)sqlite3_value_text(pVal); u32 mode = 0; if( z==0 ){ mode = (bIsDir ? (S_IFDIR + 0755) : (S_IFREG + 0644)); }else if( z[0]>='0' && z[0]<='9' ){ mode = (unsigned int)sqlite3_value_int(pVal); }else{ const char zTemplate[11] = "-rwxrwxrwx"; int i; if( strlen(z)!=10 ) goto parse_error; switch( z[0] ){ case '-': mode |= S_IFREG; break; case 'd': mode |= S_IFDIR; break; case 'l': mode |= S_IFLNK; break; default: goto parse_error; } for(i=1; i<10; i++){ if( z[i]==zTemplate[i] ) mode |= 1 << (9-i); else if( z[i]!='-' ) goto parse_error; } } if( ((mode & S_IFDIR)==0)==bIsDir ){ /* The "mode" attribute is a directory, but data has been specified. ** Or vice-versa - no data but "mode" is a file or symlink. */ *pzErr = sqlite3_mprintf("zipfile: mode does not match data"); return SQLITE_CONSTRAINT; } *pMode = mode; return SQLITE_OK; parse_error: *pzErr = sqlite3_mprintf("zipfile: parse error in mode: %s", z); return SQLITE_ERROR; } /* ** Both (const char*) arguments point to nul-terminated strings. Argument ** nB is the value of strlen(zB). This function returns 0 if the strings are ** identical, ignoring any trailing '/' character in either path. */ static int zipfileComparePath(const char *zA, const char *zB, int nB){ int nA = (int)strlen(zA); if( zA[nA-1]=='/' ) nA--; if( zB[nB-1]=='/' ) nB--; if( nA==nB && memcmp(zA, zB, nA)==0 ) return 0; return 1; } static int zipfileBegin(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; assert( pTab->pWriteFd==0 ); /* Open a write fd on the file. Also load the entire central directory ** structure into memory. During the transaction any new file data is ** appended to the archive file, but the central directory is accumulated ** in main-memory until the transaction is committed. */ pTab->pWriteFd = fopen(pTab->zFile, "ab+"); if( pTab->pWriteFd==0 ){ pTab->base.zErrMsg = sqlite3_mprintf( "zipfile: failed to open file %s for writing", pTab->zFile ); rc = SQLITE_ERROR; }else{ fseek(pTab->pWriteFd, 0, SEEK_END); pTab->szCurrent = pTab->szOrig = (i64)ftell(pTab->pWriteFd); rc = zipfileLoadDirectory(pTab, 0, 0); } if( rc!=SQLITE_OK ){ zipfileCleanupTransaction(pTab); } return rc; } /* ** Return the current time as a 32-bit timestamp in UNIX epoch format (like ** time(2)). */ static u32 zipfileTime(void){ sqlite3_vfs *pVfs = sqlite3_vfs_find(0); u32 ret; if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){ i64 ms; pVfs->xCurrentTimeInt64(pVfs, &ms); ret = (u32)((ms/1000) - ((i64)24405875 * 8640)); }else{ double day; pVfs->xCurrentTime(pVfs, &day); ret = (u32)((day - 2440587.5) * 86400); } return ret; } /* ** Return a 32-bit timestamp in UNIX epoch format. ** ** If the value passed as the only argument is either NULL or an SQL NULL, ** return the current time. Otherwise, return the value stored in (*pVal) ** cast to a 32-bit unsigned integer. */ static u32 zipfileGetTime(sqlite3_value *pVal){ if( pVal==0 || sqlite3_value_type(pVal)==SQLITE_NULL ){ return zipfileTime(); } return (u32)sqlite3_value_int64(pVal); } /* ** Unless it is NULL, entry pOld is currently part of the pTab->pFirstEntry ** linked list. Remove it from the list and free the object. */ static void zipfileRemoveEntryFromList(ZipfileTab *pTab, ZipfileEntry *pOld){ if( pOld ){ ZipfileEntry **pp; for(pp=&pTab->pFirstEntry; (*pp)!=pOld; pp=&((*pp)->pNext)); *pp = (*pp)->pNext; zipfileEntryFree(pOld); } } /* ** xUpdate method. */ static int zipfileUpdate( sqlite3_vtab *pVtab, int nVal, sqlite3_value **apVal, sqlite_int64 *pRowid ){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; /* Return Code */ ZipfileEntry *pNew = 0; /* New in-memory CDS entry */ u32 mode = 0; /* Mode for new entry */ u32 mTime = 0; /* Modification time for new entry */ i64 sz = 0; /* Uncompressed size */ const char *zPath = 0; /* Path for new entry */ int nPath = 0; /* strlen(zPath) */ const u8 *pData = 0; /* Pointer to buffer containing content */ int nData = 0; /* Size of pData buffer in bytes */ int iMethod = 0; /* Compression method for new entry */ u8 *pFree = 0; /* Free this */ char *zFree = 0; /* Also free this */ ZipfileEntry *pOld = 0; ZipfileEntry *pOld2 = 0; int bUpdate = 0; /* True for an update that modifies "name" */ int bIsDir = 0; u32 iCrc32 = 0; if( pTab->pWriteFd==0 ){ rc = zipfileBegin(pVtab); if( rc!=SQLITE_OK ) return rc; } /* If this is a DELETE or UPDATE, find the archive entry to delete. */ if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){ const char *zDelete = (const char*)sqlite3_value_text(apVal[0]); int nDelete = (int)strlen(zDelete); if( nVal>1 ){ const char *zUpdate = (const char*)sqlite3_value_text(apVal[1]); if( zUpdate && zipfileComparePath(zUpdate, zDelete, nDelete)!=0 ){ bUpdate = 1; } } for(pOld=pTab->pFirstEntry; 1; pOld=pOld->pNext){ if( zipfileComparePath(pOld->cds.zFile, zDelete, nDelete)==0 ){ break; } assert( pOld->pNext ); } } if( nVal>1 ){ /* Check that "sz" and "rawdata" are both NULL: */ if( sqlite3_value_type(apVal[5])!=SQLITE_NULL ){ zipfileTableErr(pTab, "sz must be NULL"); rc = SQLITE_CONSTRAINT; } if( sqlite3_value_type(apVal[6])!=SQLITE_NULL ){ zipfileTableErr(pTab, "rawdata must be NULL"); rc = SQLITE_CONSTRAINT; } if( rc==SQLITE_OK ){ if( sqlite3_value_type(apVal[7])==SQLITE_NULL ){ /* data=NULL. A directory */ bIsDir = 1; }else{ /* Value specified for "data", and possibly "method". This must be ** a regular file or a symlink. */ const u8 *aIn = sqlite3_value_blob(apVal[7]); int nIn = sqlite3_value_bytes(apVal[7]); int bAuto = sqlite3_value_type(apVal[8])==SQLITE_NULL; iMethod = sqlite3_value_int(apVal[8]); sz = nIn; pData = aIn; nData = nIn; if( iMethod!=0 && iMethod!=8 ){ zipfileTableErr(pTab, "unknown compression method: %d", iMethod); rc = SQLITE_CONSTRAINT; }else{ if( bAuto || iMethod ){ int nCmp; rc = zipfileDeflate(aIn, nIn, &pFree, &nCmp, &pTab->base.zErrMsg); if( rc==SQLITE_OK ){ if( iMethod || nCmp<nIn ){ iMethod = 8; pData = pFree; nData = nCmp; } } } iCrc32 = crc32(0, aIn, nIn); } } } if( rc==SQLITE_OK ){ rc = zipfileGetMode(apVal[3], bIsDir, &mode, &pTab->base.zErrMsg); } if( rc==SQLITE_OK ){ zPath = (const char*)sqlite3_value_text(apVal[2]); if( zPath==0 ) zPath = ""; nPath = (int)strlen(zPath); mTime = zipfileGetTime(apVal[4]); } if( rc==SQLITE_OK && bIsDir ){ /* For a directory, check that the last character in the path is a ** '/'. This appears to be required for compatibility with info-zip ** (the unzip command on unix). It does not create directories ** otherwise. */ if( zPath[nPath-1]!='/' ){ zFree = sqlite3_mprintf("%s/", zPath); if( zFree==0 ){ rc = SQLITE_NOMEM; } zPath = (const char*)zFree; nPath++; } } /* Check that we're not inserting a duplicate entry -OR- updating an ** entry with a path, thereby making it into a duplicate. */ if( (pOld==0 || bUpdate) && rc==SQLITE_OK ){ ZipfileEntry *p; for(p=pTab->pFirstEntry; p; p=p->pNext){ if( zipfileComparePath(p->cds.zFile, zPath, nPath)==0 ){ switch( sqlite3_vtab_on_conflict(pTab->db) ){ case SQLITE_IGNORE: { goto zipfile_update_done; } case SQLITE_REPLACE: { pOld2 = p; break; } default: { zipfileTableErr(pTab, "duplicate name: \"%s\"", zPath); rc = SQLITE_CONSTRAINT; break; } } break; } } } if( rc==SQLITE_OK ){ /* Create the new CDS record. */ pNew = zipfileNewEntry(zPath); if( pNew==0 ){ rc = SQLITE_NOMEM; }else{ pNew->cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; pNew->cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; pNew->cds.flags = ZIPFILE_NEWENTRY_FLAGS; pNew->cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&pNew->cds, mTime); pNew->cds.crc32 = iCrc32; pNew->cds.szCompressed = nData; pNew->cds.szUncompressed = (u32)sz; pNew->cds.iExternalAttr = (mode<<16); pNew->cds.iOffset = (u32)pTab->szCurrent; pNew->cds.nFile = (u16)nPath; pNew->mUnixTime = (u32)mTime; rc = zipfileAppendEntry(pTab, pNew, pData, nData); zipfileAddEntry(pTab, pOld, pNew); } } } if( rc==SQLITE_OK && (pOld || pOld2) ){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( pCsr->pCurrent && (pCsr->pCurrent==pOld || pCsr->pCurrent==pOld2) ){ pCsr->pCurrent = pCsr->pCurrent->pNext; pCsr->bNoop = 1; } } zipfileRemoveEntryFromList(pTab, pOld); zipfileRemoveEntryFromList(pTab, pOld2); } zipfile_update_done: sqlite3_free(pFree); sqlite3_free(zFree); return rc; } static int zipfileSerializeEOCD(ZipfileEOCD *p, u8 *aBuf){ u8 *a = aBuf; zipfileWrite32(a, ZIPFILE_SIGNATURE_EOCD); zipfileWrite16(a, p->iDisk); zipfileWrite16(a, p->iFirstDisk); zipfileWrite16(a, p->nEntry); zipfileWrite16(a, p->nEntryTotal); zipfileWrite32(a, p->nSize); zipfileWrite32(a, p->iOffset); zipfileWrite16(a, 0); /* Size of trailing comment in bytes*/ return a-aBuf; } static int zipfileAppendEOCD(ZipfileTab *pTab, ZipfileEOCD *p){ int nBuf = zipfileSerializeEOCD(p, pTab->aBuffer); assert( nBuf==ZIPFILE_EOCD_FIXED_SZ ); return zipfileAppendData(pTab, pTab->aBuffer, nBuf); } /* ** Serialize the CDS structure into buffer aBuf[]. Return the number ** of bytes written. */ static int zipfileSerializeCDS(ZipfileEntry *pEntry, u8 *aBuf){ u8 *a = aBuf; ZipfileCDS *pCDS = &pEntry->cds; if( pEntry->aExtra==0 ){ pCDS->nExtra = 9; } zipfileWrite32(a, ZIPFILE_SIGNATURE_CDS); zipfileWrite16(a, pCDS->iVersionMadeBy); zipfileWrite16(a, pCDS->iVersionExtract); zipfileWrite16(a, pCDS->flags); zipfileWrite16(a, pCDS->iCompression); zipfileWrite16(a, pCDS->mTime); zipfileWrite16(a, pCDS->mDate); zipfileWrite32(a, pCDS->crc32); zipfileWrite32(a, pCDS->szCompressed); zipfileWrite32(a, pCDS->szUncompressed); assert( a==&aBuf[ZIPFILE_CDS_NFILE_OFF] ); zipfileWrite16(a, pCDS->nFile); zipfileWrite16(a, pCDS->nExtra); zipfileWrite16(a, pCDS->nComment); zipfileWrite16(a, pCDS->iDiskStart); zipfileWrite16(a, pCDS->iInternalAttr); zipfileWrite32(a, pCDS->iExternalAttr); zipfileWrite32(a, pCDS->iOffset); memcpy(a, pCDS->zFile, pCDS->nFile); a += pCDS->nFile; if( pEntry->aExtra ){ int n = (int)pCDS->nExtra + (int)pCDS->nComment; memcpy(a, pEntry->aExtra, n); a += n; }else{ assert( pCDS->nExtra==9 ); zipfileWrite16(a, ZIPFILE_EXTRA_TIMESTAMP); zipfileWrite16(a, 5); *a++ = 0x01; zipfileWrite32(a, pEntry->mUnixTime); } return a-aBuf; } static int zipfileCommit(sqlite3_vtab *pVtab){ ZipfileTab *pTab = (ZipfileTab*)pVtab; int rc = SQLITE_OK; if( pTab->pWriteFd ){ i64 iOffset = pTab->szCurrent; ZipfileEntry *p; ZipfileEOCD eocd; int nEntry = 0; /* Write out all entries */ for(p=pTab->pFirstEntry; rc==SQLITE_OK && p; p=p->pNext){ int n = zipfileSerializeCDS(p, pTab->aBuffer); rc = zipfileAppendData(pTab, pTab->aBuffer, n); nEntry++; } /* Write out the EOCD record */ eocd.iDisk = 0; eocd.iFirstDisk = 0; eocd.nEntry = (u16)nEntry; eocd.nEntryTotal = (u16)nEntry; eocd.nSize = (u32)(pTab->szCurrent - iOffset); eocd.iOffset = (u32)iOffset; rc = zipfileAppendEOCD(pTab, &eocd); zipfileCleanupTransaction(pTab); } return rc; } static int zipfileRollback(sqlite3_vtab *pVtab){ return zipfileCommit(pVtab); } static ZipfileCsr *zipfileFindCursor(ZipfileTab *pTab, i64 iId){ ZipfileCsr *pCsr; for(pCsr=pTab->pCsrList; pCsr; pCsr=pCsr->pCsrNext){ if( iId==pCsr->iId ) break; } return pCsr; } static void zipfileFunctionCds( sqlite3_context *context, int argc, sqlite3_value **argv ){ ZipfileCsr *pCsr; ZipfileTab *pTab = (ZipfileTab*)sqlite3_user_data(context); assert( argc>0 ); pCsr = zipfileFindCursor(pTab, sqlite3_value_int64(argv[0])); if( pCsr ){ ZipfileCDS *p = &pCsr->pCurrent->cds; char *zRes = sqlite3_mprintf("{" "\"version-made-by\" : %u, " "\"version-to-extract\" : %u, " "\"flags\" : %u, " "\"compression\" : %u, " "\"time\" : %u, " "\"date\" : %u, " "\"crc32\" : %u, " "\"compressed-size\" : %u, " "\"uncompressed-size\" : %u, " "\"file-name-length\" : %u, " "\"extra-field-length\" : %u, " "\"file-comment-length\" : %u, " "\"disk-number-start\" : %u, " "\"internal-attr\" : %u, " "\"external-attr\" : %u, " "\"offset\" : %u }", (u32)p->iVersionMadeBy, (u32)p->iVersionExtract, (u32)p->flags, (u32)p->iCompression, (u32)p->mTime, (u32)p->mDate, (u32)p->crc32, (u32)p->szCompressed, (u32)p->szUncompressed, (u32)p->nFile, (u32)p->nExtra, (u32)p->nComment, (u32)p->iDiskStart, (u32)p->iInternalAttr, (u32)p->iExternalAttr, (u32)p->iOffset ); if( zRes==0 ){ sqlite3_result_error_nomem(context); }else{ sqlite3_result_text(context, zRes, -1, SQLITE_TRANSIENT); sqlite3_free(zRes); } } } /* ** xFindFunction method. */ static int zipfileFindFunction( sqlite3_vtab *pVtab, /* Virtual table handle */ int nArg, /* Number of SQL function arguments */ const char *zName, /* Name of SQL function */ void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */ void **ppArg /* OUT: User data for *pxFunc */ ){ if( sqlite3_stricmp("zipfile_cds", zName)==0 ){ *pxFunc = zipfileFunctionCds; *ppArg = (void*)pVtab; return 1; } return 0; } typedef struct ZipfileBuffer ZipfileBuffer; struct ZipfileBuffer { u8 *a; /* Pointer to buffer */ int n; /* Size of buffer in bytes */ int nAlloc; /* Byte allocated at a[] */ }; typedef struct ZipfileCtx ZipfileCtx; struct ZipfileCtx { int nEntry; ZipfileBuffer body; ZipfileBuffer cds; }; static int zipfileBufferGrow(ZipfileBuffer *pBuf, int nByte){ if( pBuf->n+nByte>pBuf->nAlloc ){ u8 *aNew; sqlite3_int64 nNew = pBuf->n ? pBuf->n*2 : 512; int nReq = pBuf->n + nByte; while( nNew<nReq ) nNew = nNew*2; aNew = sqlite3_realloc64(pBuf->a, nNew); if( aNew==0 ) return SQLITE_NOMEM; pBuf->a = aNew; pBuf->nAlloc = (int)nNew; } return SQLITE_OK; } /* ** xStep() callback for the zipfile() aggregate. This can be called in ** any of the following ways: ** ** SELECT zipfile(name,data) ... ** SELECT zipfile(name,mode,mtime,data) ... ** SELECT zipfile(name,mode,mtime,data,method) ... */ void zipfileStep(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal){ ZipfileCtx *p; /* Aggregate function context */ ZipfileEntry e; /* New entry to add to zip archive */ sqlite3_value *pName = 0; sqlite3_value *pMode = 0; sqlite3_value *pMtime = 0; sqlite3_value *pData = 0; sqlite3_value *pMethod = 0; int bIsDir = 0; u32 mode; int rc = SQLITE_OK; char *zErr = 0; int iMethod = -1; /* Compression method to use (0 or 8) */ const u8 *aData = 0; /* Possibly compressed data for new entry */ int nData = 0; /* Size of aData[] in bytes */ int szUncompressed = 0; /* Size of data before compression */ u8 *aFree = 0; /* Free this before returning */ u32 iCrc32 = 0; /* crc32 of uncompressed data */ char *zName = 0; /* Path (name) of new entry */ int nName = 0; /* Size of zName in bytes */ char *zFree = 0; /* Free this before returning */ int nByte; memset(&e, 0, sizeof(e)); p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; /* Martial the arguments into stack variables */ if( nVal!=2 && nVal!=4 && nVal!=5 ){ zErr = sqlite3_mprintf("wrong number of arguments to function zipfile()"); rc = SQLITE_ERROR; goto zipfile_step_out; } pName = apVal[0]; if( nVal==2 ){ pData = apVal[1]; }else{ pMode = apVal[1]; pMtime = apVal[2]; pData = apVal[3]; if( nVal==5 ){ pMethod = apVal[4]; } } /* Check that the 'name' parameter looks ok. */ zName = (char*)sqlite3_value_text(pName); nName = sqlite3_value_bytes(pName); if( zName==0 ){ zErr = sqlite3_mprintf("first argument to zipfile() must be non-NULL"); rc = SQLITE_ERROR; goto zipfile_step_out; } /* Inspect the 'method' parameter. This must be either 0 (store), 8 (use ** deflate compression) or NULL (choose automatically). */ if( pMethod && SQLITE_NULL!=sqlite3_value_type(pMethod) ){ iMethod = (int)sqlite3_value_int64(pMethod); if( iMethod!=0 && iMethod!=8 ){ zErr = sqlite3_mprintf("illegal method value: %d", iMethod); rc = SQLITE_ERROR; goto zipfile_step_out; } } /* Now inspect the data. If this is NULL, then the new entry must be a ** directory. Otherwise, figure out whether or not the data should ** be deflated or simply stored in the zip archive. */ if( sqlite3_value_type(pData)==SQLITE_NULL ){ bIsDir = 1; iMethod = 0; }else{ aData = sqlite3_value_blob(pData); szUncompressed = nData = sqlite3_value_bytes(pData); iCrc32 = crc32(0, aData, nData); if( iMethod<0 || iMethod==8 ){ int nOut = 0; rc = zipfileDeflate(aData, nData, &aFree, &nOut, &zErr); if( rc!=SQLITE_OK ){ goto zipfile_step_out; } if( iMethod==8 || nOut<nData ){ aData = aFree; nData = nOut; iMethod = 8; }else{ iMethod = 0; } } } /* Decode the "mode" argument. */ rc = zipfileGetMode(pMode, bIsDir, &mode, &zErr); if( rc ) goto zipfile_step_out; /* Decode the "mtime" argument. */ e.mUnixTime = zipfileGetTime(pMtime); /* If this is a directory entry, ensure that there is exactly one '/' ** at the end of the path. Or, if this is not a directory and the path ** ends in '/' it is an error. */ if( bIsDir==0 ){ if( zName[nName-1]=='/' ){ zErr = sqlite3_mprintf("non-directory name must not end with /"); rc = SQLITE_ERROR; goto zipfile_step_out; } }else{ if( zName[nName-1]!='/' ){ zName = zFree = sqlite3_mprintf("%s/", zName); nName++; if( zName==0 ){ rc = SQLITE_NOMEM; goto zipfile_step_out; } }else{ while( nName>1 && zName[nName-2]=='/' ) nName--; } } /* Assemble the ZipfileEntry object for the new zip archive entry */ e.cds.iVersionMadeBy = ZIPFILE_NEWENTRY_MADEBY; e.cds.iVersionExtract = ZIPFILE_NEWENTRY_REQUIRED; e.cds.flags = ZIPFILE_NEWENTRY_FLAGS; e.cds.iCompression = (u16)iMethod; zipfileMtimeToDos(&e.cds, (u32)e.mUnixTime); e.cds.crc32 = iCrc32; e.cds.szCompressed = nData; e.cds.szUncompressed = szUncompressed; e.cds.iExternalAttr = (mode<<16); e.cds.iOffset = p->body.n; e.cds.nFile = (u16)nName; e.cds.zFile = zName; /* Append the LFH to the body of the new archive */ nByte = ZIPFILE_LFH_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->body, nByte)) ) goto zipfile_step_out; p->body.n += zipfileSerializeLFH(&e, &p->body.a[p->body.n]); /* Append the data to the body of the new archive */ if( nData>0 ){ if( (rc = zipfileBufferGrow(&p->body, nData)) ) goto zipfile_step_out; memcpy(&p->body.a[p->body.n], aData, nData); p->body.n += nData; } /* Append the CDS record to the directory of the new archive */ nByte = ZIPFILE_CDS_FIXED_SZ + e.cds.nFile + 9; if( (rc = zipfileBufferGrow(&p->cds, nByte)) ) goto zipfile_step_out; p->cds.n += zipfileSerializeCDS(&e, &p->cds.a[p->cds.n]); /* Increment the count of entries in the archive */ p->nEntry++; zipfile_step_out: sqlite3_free(aFree); sqlite3_free(zFree); if( rc ){ if( zErr ){ sqlite3_result_error(pCtx, zErr, -1); }else{ sqlite3_result_error_code(pCtx, rc); } } sqlite3_free(zErr); } /* ** xFinalize() callback for zipfile aggregate function. */ void zipfileFinal(sqlite3_context *pCtx){ ZipfileCtx *p; ZipfileEOCD eocd; sqlite3_int64 nZip; u8 *aZip; p = (ZipfileCtx*)sqlite3_aggregate_context(pCtx, sizeof(ZipfileCtx)); if( p==0 ) return; if( p->nEntry>0 ){ memset(&eocd, 0, sizeof(eocd)); eocd.nEntry = (u16)p->nEntry; eocd.nEntryTotal = (u16)p->nEntry; eocd.nSize = p->cds.n; eocd.iOffset = p->body.n; nZip = p->body.n + p->cds.n + ZIPFILE_EOCD_FIXED_SZ; aZip = (u8*)sqlite3_malloc64(nZip); if( aZip==0 ){ sqlite3_result_error_nomem(pCtx); }else{ memcpy(aZip, p->body.a, p->body.n); memcpy(&aZip[p->body.n], p->cds.a, p->cds.n); zipfileSerializeEOCD(&eocd, &aZip[p->body.n + p->cds.n]); sqlite3_result_blob(pCtx, aZip, (int)nZip, zipfileFree); } } sqlite3_free(p->body.a); sqlite3_free(p->cds.a); } /* ** Register the "zipfile" virtual table. */ static int zipfileRegister(sqlite3 *db){ static sqlite3_module zipfileModule = { 1, /* iVersion */ zipfileConnect, /* xCreate */ zipfileConnect, /* xConnect */ zipfileBestIndex, /* xBestIndex */ zipfileDisconnect, /* xDisconnect */ zipfileDisconnect, /* xDestroy */ zipfileOpen, /* xOpen - open a cursor */ zipfileClose, /* xClose - close a cursor */ zipfileFilter, /* xFilter - configure scan constraints */ zipfileNext, /* xNext - advance a cursor */ zipfileEof, /* xEof - check for end of scan */ zipfileColumn, /* xColumn - read data */ 0, /* xRowid - read data */ zipfileUpdate, /* xUpdate */ zipfileBegin, /* xBegin */ 0, /* xSync */ zipfileCommit, /* xCommit */ zipfileRollback, /* xRollback */ zipfileFindFunction, /* xFindMethod */ 0, /* xRename */ }; int rc = sqlite3_create_module(db, "zipfile" , &zipfileModule, 0); if( rc==SQLITE_OK ) rc = sqlite3_overload_function(db, "zipfile_cds", -1); if( rc==SQLITE_OK ){ rc = sqlite3_create_function(db, "zipfile", -1, SQLITE_UTF8, 0, 0, zipfileStep, zipfileFinal ); } return rc; } #else /* SQLITE_OMIT_VIRTUALTABLE */ # define zipfileRegister(x) SQLITE_OK #endif #ifdef _WIN32 __declspec(dllexport) #endif int sqlite3_zipfile_init( sqlite3 *db, char **pzErrMsg, const sqlite3_api_routines *pApi ){ SQLITE_EXTENSION_INIT2(pApi); (void)pzErrMsg; /* Unused parameter */ return zipfileRegister(db); }
./CrossVul/dataset_final_sorted/CWE-434/c/good_1326_0
crossvul-cpp_data_bad_844_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/gd/ext_gd.h" #include <sys/types.h> #include <sys/stat.h> #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/comparisons.h" #include "hphp/runtime/base/plain-file.h" #include "hphp/runtime/base/request-event-handler.h" #include "hphp/runtime/base/runtime-option.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-printf.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/ext/std/ext_std_file.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/util/alloc.h" #include "hphp/util/rds-local.h" #include "hphp/runtime/ext/gd/libgd/gd.h" #include "hphp/runtime/ext/gd/libgd/gdfontt.h" /* 1 Tiny font */ #include "hphp/runtime/ext/gd/libgd/gdfonts.h" /* 2 Small font */ #include "hphp/runtime/ext/gd/libgd/gdfontmb.h" /* 3 Medium bold font */ #include "hphp/runtime/ext/gd/libgd/gdfontl.h" /* 4 Large font */ #include "hphp/runtime/ext/gd/libgd/gdfontg.h" /* 5 Giant font */ #include <zlib.h> #include <set> #include <folly/portability/Stdlib.h> #include <folly/portability/Unistd.h> /* Section Filters Declarations */ /* IMPORTANT NOTE FOR NEW FILTER * Do not forget to update: * IMAGE_FILTER_MAX: define the last filter index * IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments * image_filter array in PHP_FUNCTION(imagefilter) */ #define IMAGE_FILTER_NEGATE 0 #define IMAGE_FILTER_GRAYSCALE 1 #define IMAGE_FILTER_BRIGHTNESS 2 #define IMAGE_FILTER_CONTRAST 3 #define IMAGE_FILTER_COLORIZE 4 #define IMAGE_FILTER_EDGEDETECT 5 #define IMAGE_FILTER_EMBOSS 6 #define IMAGE_FILTER_GAUSSIAN_BLUR 7 #define IMAGE_FILTER_SELECTIVE_BLUR 8 #define IMAGE_FILTER_MEAN_REMOVAL 9 #define IMAGE_FILTER_SMOOTH 10 #define IMAGE_FILTER_PIXELATE 11 #define IMAGE_FILTER_MAX 11 #define IMAGE_FILTER_MAX_ARGS 6 #define IMAGE_TYPE_GIF 1 #define IMAGE_TYPE_JPEG 2 #define IMAGE_TYPE_PNG 4 #define IMAGE_TYPE_WBMP 8 #define IMAGE_TYPE_XPM 16 // #define IM_MEMORY_CHECK namespace HPHP { /////////////////////////////////////////////////////////////////////////////// #define HAS_GDIMAGESETANTIALIASED #if defined(HAS_GDIMAGEANTIALIAS) #define SetAntiAliased(gd, flag) gdImageAntialias(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #elif defined(HAS_GDIMAGESETANTIALIASED) #define SetAntiAliased(gd, flag) ((gd)->AA = (flag)) #define SetupAntiAliasedColor(gd, color) \ ((gd)->AA ? \ gdImageSetAntiAliased(im, color), gdAntiAliased : \ color) #else #define SetAntiAliased(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #endif /////////////////////////////////////////////////////////////////////////////// // sweep() { this->~Image(); } IMPLEMENT_RESOURCE_ALLOCATION(Image) void Image::reset() { if (m_gdImage) { gdImageDestroy(m_gdImage); m_gdImage = nullptr; } } Image::~Image() { reset(); } struct ImageMemoryAlloc final : RequestEventHandler { ImageMemoryAlloc() : m_mallocSize(0) {} void requestInit() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); #endif assertx(m_mallocSize == 0); m_mallocSize = 0; } void requestShutdown() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); assertx(m_mallocSize == 0); #endif m_mallocSize = 0; } void *imMalloc(size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); if (m_mallocSize + size < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &size, sizeof(size)); m_mallocSize += size; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &size, sizeof(size)); m_mallocSize += size; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void *imCalloc(size_t nmemb, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); size_t bytes = nmemb * size; if (m_mallocSize + bytes < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + bytes); if (!ptr) return nullptr; memset(ptr, 0, sizeof(ln) + sizeof(size) + bytes); memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &bytes, sizeof(bytes)); m_mallocSize += bytes; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + bytes); if (!ptr) return nullptr; memcpy(ptr, &bytes, sizeof(bytes)); memset((char *)ptr + sizeof(size), 0, bytes); m_mallocSize += bytes; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void imFree(void *ptr #ifdef IM_MEMORY_CHECK , int ln #endif ) { size_t size; void *sizePtr = (char *)ptr - sizeof(size); memcpy(&size, sizePtr, sizeof(size)); m_mallocSize -= size; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); int count = m_alloced.erase((char*)sizePtr - sizeof(ln)); assertx(count == 1); // double free on failure assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(lnPtr); #else assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(sizePtr); #endif } // wrapper of realloc, the original buffer is freed on failure void *imRealloc(void *ptr, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); #ifdef IM_MEMORY_CHECK if (!ptr) return imMalloc(size, ln); if (!size) { imFree(ptr, ln); return nullptr; } #else if (!ptr) return imMalloc(size); if (!size) { imFree(ptr); return nullptr; } #endif void *sizePtr = (char *)ptr - sizeof(size); size_t oldSize = 0; if (ptr) memcpy(&oldSize, sizePtr, sizeof(oldSize)); int diff = size - oldSize; void *tmp; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(lnPtr, sizeof(ln) + sizeof(size) + size))) { int count = m_alloced.erase(ptr); assertx(count == 1); // double free on failure local_free(lnPtr); return nullptr; } memcpy(tmp, &ln, sizeof(ln)); memcpy((char*)tmp + sizeof(ln), &size, sizeof(size)); m_mallocSize += diff; if (tmp != lnPtr) { int count = m_alloced.erase(lnPtr); assertx(count == 1); m_alloced.insert(tmp); } return ((char *)tmp + sizeof(ln) + sizeof(size)); #else if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(sizePtr, sizeof(size) + size))) { local_free(sizePtr); return nullptr; } memcpy(tmp, &size, sizeof(size)); m_mallocSize += diff; return ((char *)tmp + sizeof(size)); #endif } #ifdef IM_MEMORY_CHECK void imDump(void *ptrs[], int &n) { int i = 0; for (auto iter = m_alloced.begin(); iter != m_alloced.end(); ++i, ++iter) { void *p = *iter; assertx(p); if (i < n) ptrs[i] = p; int ln; size_t size; memcpy(&ln, p, sizeof(ln)); memcpy(&size, (char*)p + sizeof(ln), sizeof(size)); printf("%d: (%p, %lu)\n", ln, p, size); } n = (i < n) ? i : n; } #endif private: size_t m_mallocSize; #ifdef IM_MEMORY_CHECK std::set<void *> m_alloced; #endif }; IMPLEMENT_STATIC_REQUEST_LOCAL(ImageMemoryAlloc, s_ima); #ifdef IM_MEMORY_CHECK #define IM_MALLOC(size) s_ima->imMalloc((size), __LINE__) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size), __LINE__) #define IM_FREE(ptr) s_ima->imFree((ptr), __LINE__) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size), __LINE__) #else #define IM_MALLOC(size) s_ima->imMalloc((size)) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size)) #define IM_FREE(ptr) s_ima->imFree((ptr)) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size)) #endif #define CHECK_BUFFER(begin, end, size) \ do { \ if (((char*)end) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d)", \ __FUNCTION__, __LINE__, begin, end, size); \ return; \ } \ } while (0) #define CHECK_BUFFER_R(begin, end, size, retcod) \ do { \ if (((char*)(end)) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d, %d)", \ __FUNCTION__, __LINE__, begin, end, size, retcod); \ return retcod; \ } \ } while (0) #define CHECK_ALLOC(ptr, size) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return; \ } \ } while (0) #define CHECK_ALLOC_R(ptr, size, retcod) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return retcod; \ } \ } while (0) // original Zend name is _estrndup static char *php_strndup_impl(const char* s, uint32_t length #ifdef IM_MEMORY_CHECK , int ln #endif ) { char *p; #ifdef IM_MEMORY_CHECK p = (char *)s_ima->imMalloc((length+1), ln); #else p = (char *)s_ima->imMalloc((length+1)); #endif CHECK_ALLOC_R(p, length+1, nullptr); memcpy(p, s, length); p[length] = 0; return p; } static char *php_strdup_impl(const char* s #ifdef IM_MEMORY_CHECK , int ln #endif ) { #ifdef IM_MEMORY_CHECK return php_strndup_impl(s, strlen(s), ln); #else return php_strndup_impl(s, strlen(s)); #endif } #ifdef IM_MEMORY_CHECK #define PHP_STRNDUP(var, s, length) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strndup_impl((s), (length), __LINE__); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strdup_impl(s, __LINE__); \ } while (0) #else #define PHP_STRNDUP(var, s, length) \ do { \ if (var) IM_FREE(var); \ (var) = php_strndup_impl((s), (length)); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) IM_FREE(var); \ (var) = php_strdup_impl(s); \ } while (0) #endif typedef enum { IMAGE_FILETYPE_UNKNOWN=0, IMAGE_FILETYPE_GIF=1, IMAGE_FILETYPE_JPEG, IMAGE_FILETYPE_PNG, IMAGE_FILETYPE_SWF, IMAGE_FILETYPE_PSD, IMAGE_FILETYPE_BMP, IMAGE_FILETYPE_TIFF_II, /* intel */ IMAGE_FILETYPE_TIFF_MM, /* motorola */ IMAGE_FILETYPE_JPC, IMAGE_FILETYPE_JP2, IMAGE_FILETYPE_JPX, IMAGE_FILETYPE_JB2, IMAGE_FILETYPE_SWC, IMAGE_FILETYPE_IFF, IMAGE_FILETYPE_WBMP, /* IMAGE_FILETYPE_JPEG2000 is a userland alias for IMAGE_FILETYPE_JPC */ IMAGE_FILETYPE_XBM, IMAGE_FILETYPE_ICO, IMAGE_FILETYPE_COUNT /* Must remain last */ } image_filetype; // PHP extension STANDARD: image.c /* file type markers */ static const char php_sig_gif[3] = {'G', 'I', 'F'}; static const char php_sig_psd[4] = {'8', 'B', 'P', 'S'}; static const char php_sig_bmp[2] = {'B', 'M'}; static const char php_sig_swf[3] = {'F', 'W', 'S'}; static const char php_sig_swc[3] = {'C', 'W', 'S'}; static const char php_sig_jpg[3] = {(char) 0xff, (char) 0xd8, (char) 0xff}; static const char php_sig_png[8] = {(char) 0x89, (char) 0x50, (char) 0x4e, (char) 0x47, (char) 0x0d, (char) 0x0a, (char) 0x1a, (char) 0x0a}; static const char php_sig_tif_ii[4] = {'I','I', (char)0x2A, (char)0x00}; static const char php_sig_tif_mm[4] = {'M','M', (char)0x00, (char)0x2A}; static const char php_sig_jpc[3] = {(char)0xff, (char)0x4f, (char)0xff}; static const char php_sig_jp2[12] = {(char)0x00, (char)0x00, (char)0x00, (char)0x0c, (char)0x6a, (char)0x50, (char)0x20, (char)0x20, (char)0x0d, (char)0x0a, (char)0x87, (char)0x0a}; static const char php_sig_iff[4] = {'F','O','R','M'}; static const char php_sig_ico[4] = {(char)0x00, (char)0x00, (char)0x01, (char)0x00}; static struct gfxinfo *php_handle_gif(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(3, SEEK_CUR)) return nullptr; String dim = stream->read(5); if (dim.length() != 5) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->width = (unsigned int)s[0] | (((unsigned int)s[1])<<8); result->height = (unsigned int)s[2] | (((unsigned int)s[3])<<8); result->bits = s[4]&0x80 ? ((((unsigned int)s[4])&0x07) + 1) : 0; result->channels = 3; /* always */ return result; } static struct gfxinfo *php_handle_psd(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(8); if (dim.length() != 8) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->height = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->width = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); return result; } static struct gfxinfo *php_handle_bmp(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int size; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(16); if (dim.length() != 16) return nullptr; s = (unsigned char *)dim.c_str(); size = (((unsigned int)s[3]) << 24) + (((unsigned int)s[2]) << 16) + (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (size == 12) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); result->bits = ((unsigned int)s[11]); } else if (size > 12 && (size <= 64 || size == 108 || size == 124)) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[7]) << 24) + (((unsigned int)s[6]) << 16) + (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[11]) << 24) + (((unsigned int)s[10]) << 16) + (((unsigned int)s[9]) << 8) + ((unsigned int)s[8]); result->height = abs((int32_t)result->height); result->bits = (((unsigned int)s[15]) << 8) + ((unsigned int)s[14]); } else { return nullptr; } return result; } static unsigned long int php_swf_get_bits(unsigned char* buffer, unsigned int pos, unsigned int count) { unsigned int loop; unsigned long int result = 0; for (loop = pos; loop < pos + count; loop++) { result = result + ((((buffer[loop / 8]) >> (7 - (loop % 8))) & 0x01) << (count - (loop - pos) - 1)); } return result; } static struct gfxinfo *php_handle_swc(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned long len=64, szlength; int factor=1,maxfactor=16; int slength, status=0; unsigned char *b, *buf=nullptr; String bufz; String tmp; b = (unsigned char *)IM_CALLOC(1, len + 1); CHECK_ALLOC_R(b, (len + 1), nullptr); if (!stream->seek(5, SEEK_CUR)) { IM_FREE(b); return nullptr; } String a = stream->read(64); if (a.length() != 64) { IM_FREE(b); return nullptr; } if (uncompress((Bytef*)b, &len, (const Bytef*)a.c_str(), 64) != Z_OK) { /* failed to decompress the file, will try reading the rest of the file */ if (!stream->seek(8, SEEK_SET)) { IM_FREE(b); return nullptr; } while (!(tmp = stream->read(8192)).empty()) { bufz += tmp; } slength = bufz.length(); /* * zlib::uncompress() wants to know the output data length * if none was given as a parameter * we try from input length * 2 up to input length * 2^8 * doubling it whenever it wasn't big enough * that should be eneugh for all real life cases */ do { szlength=slength*(1<<factor++); buf = (unsigned char *) IM_REALLOC(buf,szlength); if (!buf) IM_FREE(b); CHECK_ALLOC_R(buf, szlength, nullptr); status = uncompress((Bytef*)buf, &szlength, (const Bytef*)bufz.c_str(), slength); } while ((status==Z_BUF_ERROR)&&(factor<maxfactor)); if (status == Z_OK) { memcpy(b, buf, len); } if (buf) { IM_FREE(buf); } } if (!status) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); if (!result) IM_FREE(b); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (b, 0, 5); result->width = (php_swf_get_bits (b, 5 + bits, bits) - php_swf_get_bits (b, 5, bits)) / 20; result->height = (php_swf_get_bits (b, 5 + (3 * bits), bits) - php_swf_get_bits (b, 5 + (2 * bits), bits)) / 20; } else { result = nullptr; } IM_FREE(b); return result; } static struct gfxinfo *php_handle_swf(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned char *a; if (!stream->seek(5, SEEK_CUR)) return nullptr; String str = stream->read(32); if (str.length() != 32) return nullptr; a = (unsigned char *)str.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (a, 0, 5); result->width = (php_swf_get_bits (a, 5 + bits, bits) - php_swf_get_bits (a, 5, bits)) / 20; result->height = (php_swf_get_bits (a, 5 + (3 * bits), bits) - php_swf_get_bits (a, 5 + (2 * bits), bits)) / 20; result->bits = 0; result->channels = 0; return result; } static struct gfxinfo *php_handle_png(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; /* Width: 4 bytes * Height: 4 bytes * Bit depth: 1 byte * Color type: 1 byte * Compression method: 1 byte * Filter method: 1 byte * Interlace method: 1 byte */ if (!stream->seek(8, SEEK_CUR)) return nullptr; String dim = stream->read(9); if (dim.length() < 9) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->height = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); result->bits = (unsigned int)s[8]; return result; } /* routines to handle JPEG data */ /* some defines for the different JPEG block types */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_APP0 0xe0 #define M_APP1 0xe1 #define M_APP2 0xe2 #define M_APP3 0xe3 #define M_APP4 0xe4 #define M_APP5 0xe5 #define M_APP6 0xe6 #define M_APP7 0xe7 #define M_APP8 0xe8 #define M_APP9 0xe9 #define M_APP10 0xea #define M_APP11 0xeb #define M_APP12 0xec #define M_APP13 0xed #define M_APP14 0xee #define M_APP15 0xef #define M_COM 0xFE /* COMment */ #define M_PSEUDO 0xFFD8 /* pseudo marker for start of image(byte 0) */ #define M_EXIF 0xE1 /* Exif Attribute Information */ static unsigned short php_read2(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(2); /* just return 0 if we hit the end-of-file */ if (str.length() != 2) return 0; a = (unsigned char *)str.c_str(); return (((unsigned short)a[0]) << 8) + ((unsigned short)a[1]); } static unsigned int php_next_marker(const req::ptr<File>& file, int /*last_marker*/, int ff_read) { int a=0, marker; // get marker byte, swallowing possible padding if (!ff_read) { size_t extraneous = 0; while ((marker = file->getc()) != 0xff) { if (marker == EOF) { return M_EOI;/* we hit EOF */ } extraneous++; } if (extraneous) { raise_warning("corrupt JPEG data: %zu extraneous bytes before marker", extraneous); } } a = 1; do { if ((marker = file->getc()) == EOF) { return M_EOI;/* we hit EOF */ } ++a; } while (marker == 0xff); if (a < 2) { return M_EOI; /* at least one 0xff is needed before marker code */ } return (unsigned int)marker; } static int php_skip_variable(const req::ptr<File>& stream) { off_t length = (unsigned int)php_read2(stream); if (length < 2) { return 0; } length = length - 2; stream->seek(length, SEEK_CUR); return 1; } static int php_read_APP(const req::ptr<File>& stream, unsigned int marker, Array& info) { unsigned short length; unsigned char markername[16]; length = php_read2(stream); if (length < 2) { return 0; } length -= 2; /* length includes itself */ String buffer = stream->read(length); if (buffer.empty()) { return 0; } snprintf((char*)markername, sizeof(markername), "APP%d", marker - M_APP0); if (!info.exists(String((const char *)markername))) { /* XXX we only catch the 1st tag of it's kind! */ info.set(String((char*)markername, CopyString), buffer); } return 1; } static struct gfxinfo *php_handle_jpeg(const req::ptr<File>& file, Array& info) { struct gfxinfo *result = nullptr; unsigned int marker = M_PSEUDO; unsigned short length, ff_read=1; for (;;) { marker = php_next_marker(file, marker, ff_read); ff_read = 0; switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if (result == nullptr) { /* handle SOFn block */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); length = php_read2(file); result->bits = file->getc(); result->height = php_read2(file); result->width = php_read2(file); result->channels = file->getc(); if (info.isNull() || length < 8) { /* if we don't want an extanded info -> return */ return result; } if (!file->seek(length - 8, SEEK_CUR)) { /* file error after info */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_APP0: case M_APP1: case M_APP2: case M_APP3: case M_APP4: case M_APP5: case M_APP6: case M_APP7: case M_APP8: case M_APP9: case M_APP10: case M_APP11: case M_APP12: case M_APP13: case M_APP14: case M_APP15: if (!info.isNull()) { if (!php_read_APP(file, marker, info)) { /* read all the app markes... */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_SOS: case M_EOI: /* we're about to hit image data, or are at EOF. stop processing. */ return result; default: if (!php_skip_variable(file)) { /* anything else isn't interesting */ return result; } break; } } return result; /* perhaps image broken -> no info but size */ } static unsigned short php_read4(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(4); /* just return 0 if we hit the end-of-file */ if (str.length() != 4) return 0; a = (unsigned char *)str.c_str(); return (((unsigned int)a[0]) << 24) + (((unsigned int)a[1]) << 16) + (((unsigned int)a[2]) << 8) + (((unsigned int)a[3])); } /* JPEG 2000 Marker Codes */ #define JPEG2000_MARKER_PREFIX 0xFF /* All marker codes start with this */ #define JPEG2000_MARKER_SOC 0x4F /* Start of Codestream */ #define JPEG2000_MARKER_SOT 0x90 /* Start of Tile part */ #define JPEG2000_MARKER_SOD 0x93 /* Start of Data */ #define JPEG2000_MARKER_EOC 0xD9 /* End of Codestream */ #define JPEG2000_MARKER_SIZ 0x51 /* Image and tile size */ #define JPEG2000_MARKER_COD 0x52 /* Coding style default */ #define JPEG2000_MARKER_COC 0x53 /* Coding style component */ #define JPEG2000_MARKER_RGN 0x5E /* Region of interest */ #define JPEG2000_MARKER_QCD 0x5C /* Quantization default */ #define JPEG2000_MARKER_QCC 0x5D /* Quantization component */ #define JPEG2000_MARKER_POC 0x5F /* Progression order change */ #define JPEG2000_MARKER_TLM 0x55 /* Tile-part lengths */ #define JPEG2000_MARKER_PLM 0x57 /* Packet length, main header */ #define JPEG2000_MARKER_PLT 0x58 /* Packet length, tile-part header */ #define JPEG2000_MARKER_PPM 0x60 /* Packed packet headers, main header */ #define JPEG2000_MARKER_PPT 0x61 /* Packed packet headers, tile part header */ #define JPEG2000_MARKER_SOP 0x91 /* Start of packet */ #define JPEG2000_MARKER_EPH 0x92 /* End of packet header */ #define JPEG2000_MARKER_CRG 0x63 /* Component registration */ #define JPEG2000_MARKER_COM 0x64 /* Comment */ /* Main loop to parse JPEG2000 raw codestream structure */ static struct gfxinfo *php_handle_jpc(const req::ptr<File>& file) { struct gfxinfo *result = nullptr; int highest_bit_depth, bit_depth; unsigned char first_marker_id; unsigned int i; /* JPEG 2000 components can be vastly different from one another. Each component can be sampled at a different resolution, use a different colour space, have a separate colour depth, and be compressed totally differently! This makes giving a single "bit depth" answer somewhat problematic. For this implementation we'll use the highest depth encountered. */ /* Get the single byte that remains after the file type indentification */ first_marker_id = file->getc(); /* Ensure that this marker is SIZ (as is mandated by the standard) */ if (first_marker_id != JPEG2000_MARKER_SIZ) { raise_warning("JPEG2000 codestream corrupt(Expected SIZ marker " "not found after SOC)"); return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); php_read2(file); /* Lsiz */ php_read2(file); /* Rsiz */ result->width = php_read4(file); /* Xsiz */ result->height = php_read4(file); /* Ysiz */ #if MBO_0 php_read4(file); /* XOsiz */ php_read4(file); /* YOsiz */ php_read4(file); /* XTsiz */ php_read4(file); /* YTsiz */ php_read4(file); /* XTOsiz */ php_read4(file); /* YTOsiz */ #else if (!file->seek(24, SEEK_CUR)) { IM_FREE(result); return nullptr; } #endif result->channels = php_read2(file); /* Csiz */ if (result->channels > 256) { IM_FREE(result); return nullptr; } /* Collect bit depth info */ highest_bit_depth = bit_depth = 0; for (i = 0; i < result->channels; i++) { bit_depth = file->getc(); /* Ssiz[i] */ bit_depth++; if (bit_depth > highest_bit_depth) { highest_bit_depth = bit_depth; } file->getc(); /* XRsiz[i] */ file->getc(); /* YRsiz[i] */ } result->bits = highest_bit_depth; return result; } /* main loop to parse JPEG 2000 JP2 wrapper format structure */ static struct gfxinfo *php_handle_jp2(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; unsigned int box_length; unsigned int box_type; char jp2c_box_id[] = {(char)0x6a, (char)0x70, (char)0x32, (char)0x63}; /* JP2 is a wrapper format for JPEG 2000. Data is contained within "boxes". Boxes themselves can be contained within "super-boxes". Super-Boxes can contain super-boxes which provides us with a hierarchical storage system. It is valid for a JP2 file to contain multiple individual codestreams. We'll just look for the first codestream at the root of the box structure and handle that. */ for (;;) { box_length = php_read4(stream); /* LBox */ /* TBox */ String str = stream->read(sizeof(box_type)); if (str.length() != sizeof(box_type)) { /* Use this as a general "out of stream" error */ break; } memcpy(&box_type, str.c_str(), sizeof(box_type)); if (box_length == 1) { /* We won't handle XLBoxes */ return nullptr; } if (!memcmp(&box_type, jp2c_box_id, 4)) { /* Skip the first 3 bytes to emulate the file type examination */ stream->seek(3, SEEK_CUR); result = php_handle_jpc(stream); break; } /* Stop if this was the last box */ if ((int)box_length <= 0) { break; } /* Skip over LBox (Which includes both TBox and LBox itself */ if (!stream->seek(box_length - 8, SEEK_CUR)) { break; } } if (result == nullptr) { raise_warning("JP2 file has no codestreams at root level"); } return result; } /* tiff constants */ static const int php_tiff_bytes_per_format[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1}; static int get_php_tiff_bytes_per_format(int format) { int size = sizeof(php_tiff_bytes_per_format)/sizeof(int); if (format >= size) { raise_warning("Invalid format %d", format); format = 0; } return php_tiff_bytes_per_format[format]; } /* uncompressed only */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 /* compressed images only */ #define TAG_COMP_IMAGEWIDTH 0xA002 #define TAG_COMP_IMAGEHEIGHT 0xA003 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 static int php_vspprintf(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, ...) ATTRIBUTE_PRINTF(3,4); static int php_vspprintf(char **pbuf, size_t max_len, const char *fmt, ...) { va_list arglist; char *buf; va_start(arglist, fmt); int len = vspprintf_ap(&buf, max_len, fmt, arglist); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } va_end(arglist); return len; } static int php_vspprintf_ap(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, va_list ap) ATTRIBUTE_PRINTF(3,0); static int php_vspprintf_ap(char **pbuf, size_t max_len, const char *fmt, va_list ap) { char *buf; int len = vspprintf_ap(&buf, max_len, fmt, ap); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } return len; } /* Convert a 16 bit unsigned value from file's native byte order */ static int php_ifd_get16u(void *Short, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Short)[0] << 8) | ((unsigned char *)Short)[1]; } else { return (((unsigned char *)Short)[1] << 8) | ((unsigned char *)Short)[0]; } } /* Convert a 16 bit signed value from file's native byte order */ static signed short php_ifd_get16s(void *Short, int motorola_intel) { return (signed short)php_ifd_get16u(Short, motorola_intel); } /* Convert a 32 bit signed value from file's native byte order */ static int php_ifd_get32s(void *Long, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Long)[0] << 24) | (((unsigned char *)Long)[1] << 16) | (((unsigned char *)Long)[2] << 8) | (((unsigned char *)Long)[3] << 0); } else { return (((unsigned char *)Long)[3] << 24) | (((unsigned char *)Long)[2] << 16) | (((unsigned char *)Long)[1] << 8) | (((unsigned char *)Long)[0] << 0); } } /* Convert a 32 bit unsigned value from file's native byte order */ static unsigned php_ifd_get32u(void *Long, int motorola_intel) { return (unsigned)php_ifd_get32s(Long, motorola_intel) & 0xffffffff; } /* main loop to parse TIFF structure */ static struct gfxinfo *php_handle_tiff(const req::ptr<File>& stream, int motorola_intel) { struct gfxinfo *result = nullptr; int i, num_entries; unsigned char *dir_entry; size_t dir_size, entry_value, width=0, height=0, ifd_addr; int entry_tag , entry_type; String ifd_ptr = stream->read(4); if (ifd_ptr.length() != 4) return nullptr; ifd_addr = php_ifd_get32u((void*)ifd_ptr.c_str(), motorola_intel); if (!stream->seek(ifd_addr-8, SEEK_CUR)) return nullptr; String ifd_data = stream->read(2); if (ifd_data.length() != 2) return nullptr; num_entries = php_ifd_get16u((void*)ifd_data.c_str(), motorola_intel); dir_size = 2/*num dir entries*/ +12/*length of entry*/* num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; String ifd_data2 = stream->read(dir_size-2); if ((size_t)ifd_data2.length() != dir_size-2) return nullptr; ifd_data += ifd_data2; /* now we have the directory we can look how long it should be */ for(i=0;i<num_entries;i++) { dir_entry = (unsigned char*)ifd_data.c_str()+2+i*12; entry_tag = php_ifd_get16u(dir_entry+0, motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, motorola_intel); switch(entry_type) { case TAG_FMT_BYTE: case TAG_FMT_SBYTE: entry_value = (size_t)(dir_entry[8]); break; case TAG_FMT_USHORT: entry_value = php_ifd_get16u(dir_entry+8, motorola_intel); break; case TAG_FMT_SSHORT: entry_value = php_ifd_get16s(dir_entry+8, motorola_intel); break; case TAG_FMT_ULONG: entry_value = php_ifd_get32u(dir_entry+8, motorola_intel); break; case TAG_FMT_SLONG: entry_value = php_ifd_get32s(dir_entry+8, motorola_intel); break; default: continue; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGEWIDTH: width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGEHEIGHT: height = entry_value; break; } } if ( width && height) { /* not the same when in for-loop */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->height = height; result->width = width; result->bits = 0; result->channels = 0; return result; } return nullptr; } static struct gfxinfo *php_handle_iff(const req::ptr<File>& stream) { struct gfxinfo * result; char *a; int chunkId; int size; short width, height, bits; String str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); if (strncmp(a+4, "ILBM", 4) && strncmp(a+4, "PBM ", 4)) { return nullptr; } /* loop chunks to find BMHD chunk */ do { str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); chunkId = php_ifd_get32s(a+0, 1); size = php_ifd_get32s(a+4, 1); if (size < 0) return nullptr; if ((size & 1) == 1) { size++; } if (chunkId == 0x424d4844) { /* BMHD chunk */ if (size < 9) return nullptr; str = stream->read(9); if (str.length() != 9) return nullptr; a = (char *)str.c_str(); width = php_ifd_get16s(a+0, 1); height = php_ifd_get16s(a+2, 1); bits = a[8] & 0xff; if (width > 0 && height > 0 && bits > 0 && bits < 33) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = width; result->height = height; result->bits = bits; result->channels = 0; return result; } } else { if (!stream->seek(size, SEEK_CUR)) return nullptr; } } while (1); } /* * int WBMP file format type * byte Header Type * byte Extended Header * byte Header Data (type 00 = multibyte) * byte Header Data (type 11 = name/pairs) * int Number of columns * int Number of rows */ static int php_get_wbmp(const req::ptr<File>& file, struct gfxinfo **result, int check) { int i, width = 0, height = 0; if (!file->rewind()) { return 0; } /* get type */ if (file->getc() != 0) { return 0; } /* skip header */ do { i = file->getc(); if (i < 0) { return 0; } } while (i & 0x80); /* get width */ do { i = file->getc(); if (i < 0) { return 0; } width = (width << 7) | (i & 0x7f); } while (i & 0x80); /* get height */ do { i = file->getc(); if (i < 0) { return 0; } height = (height << 7) | (i & 0x7f); } while (i & 0x80); // maximum valid sizes for wbmp (although 127x127 may be a // more accurate one) if (!height || !width || height > 2048 || width > 2048) { return 0; } if (!check) { (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_WBMP; } static struct gfxinfo *php_handle_wbmp(const req::ptr<File>& stream) { struct gfxinfo *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); if (!php_get_wbmp(stream, &result, 0)) { IM_FREE(result); return nullptr; } return result; } static int php_get_xbm(const req::ptr<File>& stream, struct gfxinfo **result) { String fline; char *iname; char *type; int value; unsigned int width = 0, height = 0; if (result) { *result = nullptr; } if (!stream->rewind()) { return 0; } while (!(fline = HHVM_FN(fgets)(Resource(stream), 0).toString()).empty()) { iname = (char *)IM_MALLOC(fline.size() + 1); CHECK_ALLOC_R(iname, (fline.size() + 1), 0); if (sscanf(fline.c_str(), "#define %s %d", iname, &value) == 2) { if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("width", type)) { width = (unsigned int)value; if (height) { IM_FREE(iname); break; } } if (!strcmp("height", type)) { height = (unsigned int)value; if (width) { IM_FREE(iname); break; } } } IM_FREE(iname); } if (width && height) { if (result) { *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(*result, sizeof(struct gfxinfo), 0); (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_XBM; } return 0; } static struct gfxinfo *php_handle_xbm(const req::ptr<File>& stream) { struct gfxinfo *result; php_get_xbm(stream, &result); return result; } static struct gfxinfo *php_handle_ico(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int num_icons = 0; String dim = stream->read(2); if (dim.length() != 2) { return nullptr; } s = (unsigned char *)dim.c_str(); num_icons = (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (num_icons < 1 || num_icons > 255) { return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); while (num_icons > 0) { dim = stream->read(16); if (dim.length() != 16) { break; } s = (unsigned char *)dim.c_str(); if ((((unsigned int)s[7]) << 8) + ((unsigned int)s[6]) >= result->bits) { result->width = (unsigned int)s[0]; result->height = (unsigned int)s[1]; result->bits = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); } num_icons--; } return result; } /* Convert internal image_type to mime type */ static char *php_image_type_to_mime_type(int image_type) { switch( image_type) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } /* detect filetype from first bytes */ static int php_getimagetype(const req::ptr<File>& file) { String fileType = file->read(3); if (fileType.length() != 3) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 3 */ if (!memcmp(fileType.c_str(), php_sig_gif, 3)) { return IMAGE_FILETYPE_GIF; } else if (!memcmp(fileType.c_str(), php_sig_jpg, 3)) { return IMAGE_FILETYPE_JPEG; } else if (!memcmp(fileType.c_str(), php_sig_png, 3)) { String data = file->read(5); if (data.length() != 5) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } if (!memcmp((fileType + data).c_str(), php_sig_png, 8)) { return IMAGE_FILETYPE_PNG; } else { raise_warning("PNG file corrupted by ASCII conversion"); return IMAGE_FILETYPE_UNKNOWN; } } else if (!memcmp(fileType.c_str(), php_sig_swf, 3)) { return IMAGE_FILETYPE_SWF; } else if (!memcmp(fileType.c_str(), php_sig_swc, 3)) { return IMAGE_FILETYPE_SWC; } else if (!memcmp(fileType.c_str(), php_sig_psd, 3)) { return IMAGE_FILETYPE_PSD; } else if (!memcmp(fileType.c_str(), php_sig_bmp, 2)) { return IMAGE_FILETYPE_BMP; } else if (!memcmp(fileType.c_str(), php_sig_jpc, 3)) { return IMAGE_FILETYPE_JPC; } String data = file->read(1); if (data.length() != 1) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 4 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_tif_ii, 4)) { return IMAGE_FILETYPE_TIFF_II; } else if (!memcmp(fileType.c_str(), php_sig_tif_mm, 4)) { return IMAGE_FILETYPE_TIFF_MM; } else if (!memcmp(fileType.c_str(), php_sig_iff, 4)) { return IMAGE_FILETYPE_IFF; } else if (!memcmp(fileType.c_str(), php_sig_ico, 4)) { return IMAGE_FILETYPE_ICO; } data = file->read(8); if (data.length() != 8) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 12 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_jp2, 12)) { return IMAGE_FILETYPE_JP2; } /* AFTER ALL ABOVE FAILED */ if (php_get_wbmp(file, nullptr, 1)) { return IMAGE_FILETYPE_WBMP; } if (php_get_xbm(file, nullptr)) { return IMAGE_FILETYPE_XBM; } return IMAGE_FILETYPE_UNKNOWN; } String HHVM_FUNCTION(image_type_to_mime_type, int64_t imagetype) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } Variant HHVM_FUNCTION(image_type_to_extension, int64_t imagetype, bool include_dot /*=true */) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return include_dot ? String(".gif") : String("gif"); case IMAGE_FILETYPE_JPEG: return include_dot ? String(".jpeg") : String("jpeg"); case IMAGE_FILETYPE_PNG: return include_dot ? String(".png") : String("png"); case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return include_dot ? String(".swf") : String("swf"); case IMAGE_FILETYPE_PSD: return include_dot ? String(".psd") : String("psd"); case IMAGE_FILETYPE_BMP: case IMAGE_FILETYPE_WBMP: return include_dot ? String(".bmp") : String("bmp"); case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return include_dot ? String(".tiff") : String("tiff"); case IMAGE_FILETYPE_IFF: return include_dot ? String(".iff") : String("iff"); case IMAGE_FILETYPE_JPC: return include_dot ? String(".jpc") : String("jpc"); case IMAGE_FILETYPE_JP2: return include_dot ? String(".jp2") : String("jp2"); case IMAGE_FILETYPE_JPX: return include_dot ? String(".jpx") : String("jpx"); case IMAGE_FILETYPE_JB2: return include_dot ? String(".jb2") : String("jb2"); case IMAGE_FILETYPE_XBM: return include_dot ? String(".xbm") : String("xbm"); case IMAGE_FILETYPE_ICO: return include_dot ? String(".ico") : String("ico"); default: return false; } } const StaticString s_bits("bits"), s_channels("channels"), s_mime("mime"), s_linespacing("linespacing"); gdImagePtr get_valid_image_resource(const Resource& image) { auto img_res = dyn_cast_or_null<Image>(image); if (!img_res || !img_res->get()) { raise_warning("supplied resource is not a valid Image resource"); return nullptr; } return img_res->get(); } Variant getImageSize(const req::ptr<File>& stream, VRefParam imageinfo) { int itype = 0; struct gfxinfo *result = nullptr; auto imageInfoPtr = imageinfo.getVariantOrNull(); if (imageInfoPtr) { *imageInfoPtr = Array::Create(); } itype = php_getimagetype(stream); switch( itype) { case IMAGE_FILETYPE_GIF: result = php_handle_gif(stream); break; case IMAGE_FILETYPE_JPEG: { Array infoArr; if (imageInfoPtr) { infoArr = Array::Create(); } result = php_handle_jpeg(stream, infoArr); if (imageInfoPtr) { *imageInfoPtr = infoArr; } } break; case IMAGE_FILETYPE_PNG: result = php_handle_png(stream); break; case IMAGE_FILETYPE_SWF: result = php_handle_swf(stream); break; case IMAGE_FILETYPE_SWC: result = php_handle_swc(stream); break; case IMAGE_FILETYPE_PSD: result = php_handle_psd(stream); break; case IMAGE_FILETYPE_BMP: result = php_handle_bmp(stream); break; case IMAGE_FILETYPE_TIFF_II: result = php_handle_tiff(stream, 0); break; case IMAGE_FILETYPE_TIFF_MM: result = php_handle_tiff(stream, 1); break; case IMAGE_FILETYPE_JPC: result = php_handle_jpc(stream); break; case IMAGE_FILETYPE_JP2: result = php_handle_jp2(stream); break; case IMAGE_FILETYPE_IFF: result = php_handle_iff(stream); break; case IMAGE_FILETYPE_WBMP: result = php_handle_wbmp(stream); break; case IMAGE_FILETYPE_XBM: result = php_handle_xbm(stream); break; case IMAGE_FILETYPE_ICO: result = php_handle_ico(stream); break; default: case IMAGE_FILETYPE_UNKNOWN: break; } if (result) { DArrayInit ret(7); ret.set(0, (int64_t)result->width); ret.set(1, (int64_t)result->height); ret.set(2, itype); char *temp; php_vspprintf(&temp, 0, "width=\"%d\" height=\"%d\"", result->width, result->height); ret.set(3, String(temp, CopyString)); if (temp) IM_FREE(temp); if (result->bits != 0) { ret.set(s_bits, (int64_t)result->bits); } if (result->channels != 0) { ret.set(s_channels, (int64_t)result->channels); } ret.set(s_mime, (char*)php_image_type_to_mime_type(itype)); IM_FREE(result); return ret.toVariant(); } else { return false; } } Variant HHVM_FUNCTION(getimagesize, const String& filename, VRefParam imageinfo /*=null */) { if (auto stream = File::Open(filename, "rb")) { return getImageSize(stream, imageinfo); } return false; } Variant HHVM_FUNCTION(getimagesizefromstring, const String& imagedata, VRefParam imageinfo /*=null */) { String data = "data://text/plain;base64,"; data += StringUtil::Base64Encode(imagedata); if (auto stream = File::Open(data, "r")) { return getImageSize(stream, imageinfo); } return false; } // PHP extension gd.c #define HAVE_GDIMAGECREATEFROMPNG 1 #if HAVE_LIBTTF|HAVE_LIBFREETYPE #ifndef ENABLE_GD_TTF #define ENABLE_GD_TTF #endif #endif #define PHP_GDIMG_TYPE_GIF 1 #define PHP_GDIMG_TYPE_PNG 2 #define PHP_GDIMG_TYPE_JPG 3 #define PHP_GDIMG_TYPE_WBM 4 #define PHP_GDIMG_TYPE_XBM 5 #define PHP_GDIMG_TYPE_XPM 6 #define PHP_GDIMG_CONVERT_WBM 7 #define PHP_GDIMG_TYPE_GD 8 #define PHP_GDIMG_TYPE_GD2 9 #define PHP_GDIMG_TYPE_GD2PART 10 #define PHP_GDIMG_TYPE_WEBP 11 #define PHP_GD_VERSION_STRING "bundled (2.0.34 compatible)" #define USE_GD_IOCTX 1 #define CTX_PUTC(c,ctx) ctx->putC(ctx, c) #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static req::ptr<File> php_open_plain_file(const String& filename, const char *mode, FILE **fpp) { auto file = File::Open(filename, mode); auto plain_file = dyn_cast_or_null<PlainFile>(file); if (!plain_file) return nullptr; if (FILE* fp = plain_file->getStream()) { if (fpp) *fpp = fp; return file; } file->close(); return nullptr; } static int php_write(void *buf, uint32_t size) { g_context->write((const char *)buf, size); return size; } static void _php_image_output_putc(struct gdIOCtx* /*ctx*/, int c) { /* without the following downcast, the write will fail * (i.e., will write a zero byte) for all * big endian architectures: */ unsigned char ch = (unsigned char) c; php_write(&ch, 1); } static int _php_image_output_putbuf(struct gdIOCtx* /*ctx*/, const void* buf, int len) { return php_write((void *)buf, len); } static void _php_image_output_ctxfree(struct gdIOCtx *ctx) { if (ctx) { IM_FREE(ctx); } } static bool _php_image_output_ctx(const Resource& image, const String& filename, int quality, int basefilter, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp = nullptr; int q = quality, i; int f = basefilter; gdIOCtx *ctx; /* The third (quality) parameter for Wbmp stands for the threshold when called from image2wbmp(). The third (quality) parameter for Wbmp and Xbm stands for the foreground color index when called from imagey<type>(). */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } ctx = gdNewFileCtx(fp); } else { ctx = (gdIOCtx *)IM_MALLOC(sizeof(gdIOCtx)); CHECK_ALLOC_R(ctx, sizeof(gdIOCtx), false); ctx->putC = _php_image_output_putc; ctx->putBuf = _php_image_output_putbuf; ctx->gd_free = _php_image_output_ctxfree; } switch(image_type) { case PHP_GDIMG_CONVERT_WBM: if (q<0||q>255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); } case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, gdIOCtx *, int))(func_p))(im, ctx, q); break; case PHP_GDIMG_TYPE_PNG: ((void(*)(gdImagePtr, gdIOCtx *, int, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_WEBP: ((void(*)(gdImagePtr, gdIOCtx *, int64_t, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_XBM: case PHP_GDIMG_TYPE_WBM: if (q == -1) { // argc < 3 for(i=0; i < gdImageColorsTotal(im); i++) { if (!gdImageRed(im, i) && !gdImageGreen(im, i) && !gdImageBlue(im, i)) break; } q = i; } if (image_type == PHP_GDIMG_TYPE_XBM) { ((void(*)(gdImagePtr, char *, int, gdIOCtx *))(func_p)) (im, (char*)filename.c_str(), q, ctx); } else { ((void(*)(gdImagePtr, int, gdIOCtx *))(func_p))(im, q, ctx); } break; default: ((void(*)(gdImagePtr, gdIOCtx *))(func_p))(im, ctx); break; } ctx->gd_free(ctx); if (fp) { fflush(fp); file->close(); } return true; } /* It converts a gd Image to bw using a threshold value */ static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold) { gdImagePtr im_dest; int white, black; int color, color_org, median; int dest_height = gdImageSY(im_org); int dest_width = gdImageSX(im_org); int x, y; im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate temporary buffer"); return; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } if (im_org->trueColor) { gdImageTrueColorToPalette(im_org, 1, 256); } for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel(im_org, x, y); median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageWBMPCtx (im_dest, black, out); } /* * converts jpeg/png images to wbmp and resizes them as needed */ static bool _php_image_convert(const String& f_org, const String& f_dest, int dest_height, int dest_width, int threshold, int image_type) { gdImagePtr im_org, im_dest, im_tmp; req::ptr<File> org_file, dest_file; FILE *org, *dest; int org_height, org_width; int white, black; int color, color_org, median; int x, y; float x_ratio, y_ratio; #ifdef HAVE_GD_JPG // long ignore_warning; #endif /* Check threshold value */ if (threshold < 0 || threshold > 8) { raise_warning("Invalid threshold value '%d'", threshold); return false; } /* Open origin file */ org_file = php_open_plain_file(f_org, "rb", &org); if (!org_file) { return false; } /* Open destination file */ dest_file = php_open_plain_file(f_dest, "wb", &dest); if (!dest_file) { return false; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid GIF file", f_org.c_str()); return false; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im_org = gdImageCreateFromJpeg(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid JPEG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid PNG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_PNG */ #ifdef HAVE_LIBVPX case PHP_GDIMG_TYPE_WEBP: im_org = gdImageCreateFromWebp(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid webp file", f_org.c_str()); return false; } break; #endif /* HAVE_LIBVPX */ default: raise_warning("Format not supported"); return false; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == nullptr) { raise_warning("Unable to allocate temporary buffer"); return false; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); org_file->close(); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate destination buffer"); return false; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } threshold = threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel(im_dest, x, y, color); } } gdImageDestroy(im_tmp); gdImageWBMP(im_dest, black , dest); fflush(dest); dest_file->close(); gdImageDestroy(im_dest); return true; } // For quality and type, -1 means that the argument does not exist static bool _php_image_output(const Resource& image, const String& filename, int quality, int type, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp; int q = quality, i, t = type; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ /* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */ /* The quality parameter for gd2 stands for chunk size */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, fp); break; case PHP_GDIMG_TYPE_JPG: { // gdImageJpeg ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, fp, q); break; } case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) break; } // gdImageWBMP ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, i, fp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } // gdImageGd ((void(*)(gdImagePtr, FILE *))(func_p))(im, fp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } // gdImageGd2 ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; default: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; } fflush(fp); file->close(); } else { int b; FILE *tmp; char buf[4096]; char path[PATH_MAX]; // open a temporary file snprintf(path, sizeof(path), "/tmp/XXXXXX"); int fd = mkstemp(path); if (fd == -1 || (tmp = fdopen(fd, "r+b")) == nullptr) { if (fd != -1) close(fd); raise_warning("Unable to open temporary file"); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, tmp); break; case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, tmp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) { break; } } ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, q, tmp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, tmp, q, t); break; default: ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; } fseek(tmp, 0, SEEK_SET); while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) { g_context->write(buf, b); } fclose(tmp); /* make sure that the temporary file is removed */ unlink((const char *)path); } return true; } static gdImagePtr _php_image_create_from(const String& filename, int srcX, int srcY, int width, int height, int image_type, char *tn, gdImagePtr(*func_p)(), gdImagePtr(*ioctx_func_p)()) { VMRegAnchor _; gdImagePtr im = nullptr; #ifdef HAVE_GD_JPG // long ignore_warning; #endif if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (width < 1 || height < 1) { raise_warning("Zero width or height not allowed"); return nullptr; } } auto file = File::Open(filename, "rb"); if (!file) { raise_warning("failed to open stream: %s", filename.c_str()); return nullptr; } FILE *fp = nullptr; auto plain_file = dyn_cast<PlainFile>(file); if (plain_file) { fp = plain_file->getStream(); } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; // copy all String buff = file->read(8192); String str; do { str = file->read(8192); buff += str; } while (!str.empty()); if (buff.empty()) { raise_warning("Cannot read image data"); return nullptr; } io_ctx = gdNewDynamicCtxEx(buff.length(), (char *)buff.c_str(), 0); if (!io_ctx) { raise_warning("Cannot allocate GD IO context"); return nullptr; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = ((gdImagePtr(*)(gdIOCtx *, int, int, int, int))(ioctx_func_p)) (io_ctx, srcX, srcY, width, height); } else { im = ((gdImagePtr(*)(gdIOCtx *))(ioctx_func_p))(io_ctx); } io_ctx->gd_free(io_ctx); } else { /* TODO: try and force the stream to be FILE* */ assertx(false); } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = ((gdImagePtr(*)(FILE *, int, int, int, int))(func_p)) (fp, srcX, srcY, width, height); break; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(filename); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im = gdImageCreateFromJpeg(fp); break; #endif default: im = ((gdImagePtr(*)(FILE*))(func_p))(fp); break; } fflush(fp); } if (im) { file->close(); return im; } raise_warning("'%s' is not a valid %s file", filename.c_str(), tn); file->close(); return nullptr; } static const char php_sig_gd2[3] = {'g', 'd', '2'}; /* getmbi ** ------ ** Get a multibyte integer from a generic getin function ** 'getin' can be getc, with in = NULL ** you can find getin as a function just above the main function ** This way you gain a lot of flexibilty about how this package ** reads a wbmp file. */ static int getmbi(gdIOCtx *ctx) { int i, mbi = 0; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); mbi = (mbi << 7) | (i & 0x7f); } while (i & 0x80); return (mbi); } /* skipheader ** ---------- ** Skips the ExtHeader. Not needed for the moment ** */ int skipheader (gdIOCtx *ctx) { int i; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); } while (i & 0x80); return (0); } static int _php_image_type (char data[8]) { if (data == nullptr) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (getmbi(io_ctx) == 0 && skipheader(io_ctx) == 0 ) { io_ctx->gd_free(io_ctx); return PHP_GDIMG_TYPE_WBM; } else { io_ctx->gd_free(io_ctx); } } } return -1; } gdImagePtr _php_image_create_from_string(const String& image, char *tn, gdImagePtr (*ioctx_func_p)()) { VMRegAnchor _; gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(image.length(), (char *)image.c_str(), 0); if (!io_ctx) { return nullptr; } gdImagePtr im = (*(gdImagePtr (*)(gdIOCtx *))ioctx_func_p)(io_ctx); if (!im) { raise_warning("Passed data is not in '%s' format", tn); io_ctx->gd_free(io_ctx); return nullptr; } io_ctx->gd_free(io_ctx); return im; } static gdFontPtr php_find_gd_font(int size) { gdFontPtr font; switch (size) { case 1: font = gdFontTiny; break; case 2: font = gdFontSmall; break; case 3: font = gdFontMediumBold; break; case 4: font = gdFontLarge; break; case 5: font = gdFontGiant; break; default: raise_warning("Unsupported font: %d", size); // font = zend_list_find(size - 5, &ind_type); // if (!font || ind_type != le_gd_font) { if (size < 1) { font = gdFontTiny; } else { font = gdFontGiant; } break; } return font; } /* workaround for a bug in gd 1.2 */ static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy, px, py, fline; cx = 0; cy = 0; if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } /* * arg = 0 ImageChar * arg = 1 ImageCharUp * arg = 2 ImageString * arg = 3 ImageStringUp */ static bool php_imagechar(const Resource& image, int size, int x, int y, const String& c, int color, int mode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ch = 0; gdFontPtr font; if (mode < 2) { ch = (int)((unsigned char)(c.charAt(0))); } font = php_find_gd_font(size); switch (mode) { case 0: gdImageChar(im, font, x, y, ch, color); break; case 1: php_gdimagecharup(im, font, x, y, ch, color); break; case 2: for (int i = 0; (i < c.length()); i++) { gdImageChar(im, font, x, y, (int)((unsigned char)c.charAt(i)), color); x += font->w; } break; case 3: for (int i = 0; (i < c.length()); i++) { gdImageCharUp(im, font, x, y, (int)c.charAt(i), color); y -= font->w; } break; } return true; } /* arg = 0 normal polygon arg = 1 filled polygon */ static bool php_imagepolygon(const Resource& image, const Array& points, int num_points, int color, int filled) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdPointPtr pts; int nelem, i; nelem = points.size(); if (nelem < 6) { raise_warning("You must have at least 3 points in your array"); return false; } if (nelem < num_points * 2) { raise_warning("Trying to use %d points in array with only %d points", num_points, nelem/2); return false; } pts = (gdPointPtr)IM_MALLOC(num_points * sizeof(gdPoint)); CHECK_ALLOC_R(pts, (num_points * sizeof(gdPoint)), false); for (i = 0; i < num_points; i++) { if (points.exists(i * 2)) { pts[i].x = points[i * 2].toInt32(); } if (points.exists(i * 2 + 1)) { pts[i].y = points[i * 2 + 1].toInt32(); } } if (filled) { gdImageFilledPolygon(im, pts, num_points, color); } else { color = SetupAntiAliasedColor(im, color); gdImagePolygon(im, pts, num_points, color); } IM_FREE(pts); return true; } static bool php_image_filter_negate(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageNegate(im) == 1; } static bool php_image_filter_grayscale(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGrayScale(im) == 1; } static bool php_image_filter_brightness(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int brightness = arg1; return gdImageBrightness(im, brightness) == 1; } static bool php_image_filter_contrast(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int contrast = arg1; return gdImageContrast(im, contrast) == 1; } static bool php_image_filter_colorize(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int arg3 /* = 0 */, int /*arg4*/ /* = 0 */) { int r = arg1; int g = arg2; int b = arg3; int a = arg1; return gdImageColor(im, r, g, b, a) == 1; } static bool php_image_filter_edgedetect(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEdgeDetectQuick(im) == 1; } static bool php_image_filter_emboss(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEmboss(im) == 1; } static bool php_image_filter_gaussian_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGaussianBlur(im) == 1; } static bool php_image_filter_selective_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageSelectiveBlur(im) == 1; } static bool php_image_filter_mean_removal(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageMeanRemoval(im) == 1; } static bool php_image_filter_smooth(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int weight = arg1; return gdImageSmooth(im, weight) == 1; } static bool php_image_filter_pixelate(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int blocksize = arg1; unsigned mode = arg2; return gdImagePixelate(im, blocksize, mode) == 1; } /* * arg = 0 ImageFontWidth * arg = 1 ImageFontHeight */ static int php_imagefontsize(int size, int arg) { gdFontPtr font = php_find_gd_font(size); return (arg ? font->h : font->w); } #ifdef ENABLE_GD_TTF #define TTFTEXT_DRAW 0 #define TTFTEXT_BBOX 1 #endif #ifdef ENABLE_GD_TTF static Variant php_imagettftext_common(int mode, int extended, const Variant& arg1, const Variant& arg2, const Variant& arg3, const Variant& arg4, const Variant& arg5 = uninit_variant, const Variant& arg6 = uninit_variant, const Variant& arg7 = uninit_variant, const Variant& arg8 = uninit_variant, const Variant& arg9 = uninit_variant) { gdImagePtr im=nullptr; long col = -1, x = -1, y = -1; int brect[8]; double ptsize, angle; String str; String fontname; Array extrainfo; char *error = nullptr; gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { ptsize = arg1.toDouble(); angle = arg2.toDouble(); fontname = arg3.toString(); str = arg4.toString(); extrainfo = arg5; } else { Resource image = arg1.toResource(); ptsize = arg2.toDouble(); angle = arg3.toDouble(); x = arg4.toInt64(); y = arg5.toInt64(); col = arg6.toInt64(); fontname = arg7.toString(); str = arg8.toString(); extrainfo = arg9; im = get_valid_image_resource(image); if (!im) return false; } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && !extrainfo.empty()) { /* parse extended info */ /* walk the assoc array */ for (ArrayIter iter(extrainfo); iter; ++iter) { Variant key = iter.first(); if (!key.isString()) continue; Variant item = iter.second(); if (equal(key, s_linespacing)) { strex.flags |= gdFTEX_LINESPACE; strex.linespacing = item.toDouble(); } } } FILE *fp = nullptr; if (!RuntimeOption::FontPath.empty()) { fontname = String(RuntimeOption::FontPath.c_str()) + HHVM_FN(basename)(fontname); } auto stream = php_open_plain_file(fontname, "rb", &fp); if (!stream) { raise_warning("Invalid font filename %s", fontname.c_str()); return false; } stream->close(); #ifdef USE_GD_IMGSTRTTF if (extended) { error = gdImageStringFTEx(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str(), &strex); } else { error = gdImageStringFT(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str()); } #else /* !USE_GD_IMGSTRTTF */ error = gdttf(im, brect, col, fontname.c_str(), ptsize, angle, x, y, str.c_str()); #endif if (error) { raise_warning("%s", error); return false; } /* return array with the text's bounding box */ Array ret = Array::CreateDArray(); for (int i = 0; i < 8; i++) { ret.set(i, brect[i]); } return ret; } #endif /* ENABLE_GD_TTF */ const StaticString s_GD_Version("GD Version"), s_FreeType_Support("FreeType Support"), s_FreeType_Linkage("FreeType Linkage"), s_with_freetype("with freetype"), s_with_TTF_library("with TTF library"), s_with_unknown_library("with unknown library"), s_T1Lib_Support("T1Lib_Support"), s_GIF_Read_Support("GIF Read Support"), s_GIF_Create_Support("GIF Create Support"), s_JPG_Support("JPEG Support"), s_PNG_Support("PNG Support"), s_WBMP_Support("WBMP Support"), s_XPM_Support("XPM Support"), s_XBM_Support("XBM Support"), s_JIS_mapped_Japanese_Font_Support("JIS-mapped Japanese Font Support"); Array HHVM_FUNCTION(gd_info) { Array ret = Array::CreateDArray(); ret.set(s_GD_Version, PHP_GD_VERSION_STRING); #ifdef ENABLE_GD_TTF ret.set(s_FreeType_Support, true); #if HAVE_LIBFREETYPE ret.set(s_FreeType_Linkage, s_with_freetype); #elif HAVE_LIBTTF ret.set(s_FreeType_Linkage, s_with_TTF_library); #else ret.set(s_FreeType_Linkage, s_with_unknown_library); #endif #else ret.set(s_FreeType_Support, false); #endif #ifdef HAVE_LIBT1 ret.set(s_T1Lib_Support, true); #else ret.set(s_T1Lib_Support, false); #endif ret.set(s_GIF_Read_Support, true); ret.set(s_GIF_Create_Support, true); #ifdef HAVE_GD_JPG ret.set(s_JPG_Support, true); #else ret.set(s_JPG_Support, false); #endif #ifdef HAVE_GD_PNG ret.set(s_PNG_Support, true); #else ret.set(s_PNG_Support, false); #endif ret.set(s_WBMP_Support, true); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret.set(s_XPM_Support, true); #else ret.set(s_XPM_Support, false); #endif ret.set(s_XBM_Support, true); #if defined(USE_GD_JISX0208) && defined(HAVE_GD_BUNDLED) ret.set(s_JIS_mapped_Japanese_Font_Support, true); #else ret.set(s_JIS_mapped_Japanese_Font_Support, false); #endif return ret; } #define FLIPWORD(a) (((a & 0xff000000) >> 24) | \ ((a & 0x00ff0000) >> 8) | \ ((a & 0x0000ff00) << 8) | \ ((a & 0x000000ff) << 24)) Variant HHVM_FUNCTION(imageloadfont, const String& /*file*/) { // TODO: ind = 5 + zend_list_insert(font, le_gd_font); throw_not_supported(__func__, "NYI"); #ifdef NEVER Variant stream; zval **file; int hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; stream = File::Open(file, "rb"); if (!stream) { raise_warning("failed to open file: %s", file.c_str()); return false; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) IM_MALLOC(sizeof(gdFont)); CHECK_ALLOC_R(font, sizeof(gdFont), false); b = 0; String hdr = stream->read(hdr_size); if (hdr.length() < hdr_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading header"); } else { raise_warning("Error while reading header"); } stream->close(); return false; } memcpy((void*)font, hdr.c_str(), hdr.length()); i = int64_t(f_tell(stream)); stream->seek(0, SEEK_END); body_size_check = int64_t(f_tell(stream)) - hdr_size; stream->seek(i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (font->nchars <= 0 || font->h <= 0 || font->nchars >= INT_MAX || font->h >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if ((font->nchars * font->h) <= 0 || font->w <= 0 || (font->nchars * font->h) >= INT_MAX || font->w >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if (body_size != body_size_check) { raise_warning("Error reading font"); IM_FREE(font); stream->close(); return false; } String body = stream->read(body_size); if (body.length() < body_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading body"); } else { raise_warning("Error while reading body"); } stream->close(); return false; } font->data = IM_MALLOC(body_size); CHECK_ALLOC_R(font->data, body_size, false); memcpy((void*)font->data, body.c_str(), body.length()); stream->close(); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ // ind = 5 + zend_list_insert(font, le_gd_font); return ind; #endif } bool HHVM_FUNCTION(imagesetstyle, const Resource& image, const Array& style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int *stylearr; int index; size_t malloc_size = sizeof(int) * style.size(); stylearr = (int *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(stylearr, malloc_size, false); index = 0; for (ArrayIter iter(style); iter; ++iter) { stylearr[index++] = cellToInt(tvToCell(iter.secondVal())); } gdImageSetStyle(im, stylearr, index); IM_FREE(stylearr); return true; } const StaticString s_x("x"), s_y("y"), s_width("width"), s_height("height"); Variant HHVM_FUNCTION(imagecrop, const Resource& image, const Array& rect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; gdRect gdrect; if (rect.exists(s_x)) { gdrect.x = rect[s_x].toInt64(); } else { raise_warning("imagecrop(): Missing x position"); return false; } if (rect.exists(s_y)) { gdrect.y = rect[s_y].toInt64(); } else { raise_warning("imagecrop(): Missing y position"); return false; } if (rect.exists(s_width)) { gdrect.width = rect[s_width].toInt64(); } else { raise_warning("imagecrop(): Missing width position"); return false; } if (rect.exists(s_height)) { gdrect.height = rect[s_height].toInt64(); } else { raise_warning("imagecrop(): Missing height position"); return false; } imcropped = gdImageCrop(im, &gdrect); if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecropauto, const Resource& image, int64_t mode /* = -1 */, double threshold /* = 0.5f */, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; switch (mode) { case -1: mode = GD_CROP_DEFAULT; case GD_CROP_DEFAULT: case GD_CROP_TRANSPARENT: case GD_CROP_BLACK: case GD_CROP_WHITE: case GD_CROP_SIDES: imcropped = gdImageCropAuto(im, mode); break; case GD_CROP_THRESHOLD: if (color < 0) { raise_warning("imagecropauto(): Color argument missing " "with threshold mode"); return false; } imcropped = gdImageCropThreshold(im, color, (float) threshold); break; default: raise_warning("imagecropauto(): Unknown crop mode"); return false; } if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecreatetruecolor, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreateTrueColor(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } bool f_imageistruecolor(const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return im->trueColor; } Variant HHVM_FUNCTION(imagetruecolortopalette, const Resource& image, bool dither, int64_t ncolors) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (ncolors <= 0 || ncolors >= INT_MAX) { raise_warning("Number of colors has to be greater than zero"); return false; } gdImageTrueColorToPalette(im, dither, ncolors); return true; } Variant HHVM_FUNCTION(imagecolormatch, const Resource& image1, const Resource& image2) { gdImagePtr im1 = get_valid_image_resource(image1); if (!im1) return false; gdImagePtr im2 = get_valid_image_resource(image2); if (!im2) return false; int result; result = gdImageColorMatch(im1, im2); switch (result) { case -1: raise_warning("Image1 must be TrueColor"); return false; case -2: raise_warning("Image2 must be Palette"); return false; case -3: raise_warning("Image1 and Image2 must be the same size"); return false; case -4: raise_warning("Image2 must have at least one color"); return false; } return true; } bool HHVM_FUNCTION(imagesetthickness, const Resource& image, int64_t thickness) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetThickness(im, thickness); return true; } bool HHVM_FUNCTION(imagefilledellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledEllipse(im, cx, cy, width, height, color); return true; } bool HHVM_FUNCTION(imagefilledarc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color, int64_t style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; gdImageFilledArc(im, cx, cy, width, height, start, end, color, style); return true; } Variant HHVM_FUNCTION(imageaffine, const Resource& image, const Array& affine /* = Array() */, const Array& clip /* = Array() */) { gdImagePtr src = get_valid_image_resource(image); if (!src) return false; gdImagePtr dst = nullptr; gdRect rect; gdRectPtr pRect = nullptr; int nelem = affine.size(); int i; double daffine[6]; if (nelem != 6) { raise_warning("imageaffine(): Affine array must have six elements"); return false; } for (i = 0; i < nelem; i++) { if (affine[i].isInteger()) { daffine[i] = affine[i].toInt64(); } else if (affine[i].isDouble() || affine[i].isString()) { daffine[i] = affine[i].toDouble(); } else { raise_warning("imageaffine(): Invalid type for element %i", i); return false; } } if (!clip.empty()) { if (clip.exists(s_x)) { rect.x = clip[s_x].toInt64(); } else { raise_warning("imageaffine(): Missing x position"); return false; } if (clip.exists(s_y)) { rect.y = clip[s_y].toInt64(); } else { raise_warning("imageaffine(): Missing y position"); return false; } if (clip.exists(s_width)) { rect.width = clip[s_width].toInt64(); } else { raise_warning("imageaffine(): Missing width position"); return false; } if (clip.exists(s_height)) { rect.height = clip[s_height].toInt64(); } else { raise_warning("imageaffine(): Missing height position"); return false; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = nullptr; } if (gdTransformAffineGetImage(&dst, src, pRect, daffine) != GD_TRUE) { return false; } return Variant(req::make<Image>(dst)); } Variant HHVM_FUNCTION(imageaffinematrixconcat, const Array& m1, const Array& m2) { int nelem1 = m1.size(); int nelem2 = m2.size(); int i; double dm1[6]; double dm2[6]; double dmr[6]; Array ret = Array::Create(); if (nelem1 != 6 || nelem2 != 6) { raise_warning("imageaffinematrixconcat(): Affine array must " "have six elements"); return false; } for (i = 0; i < 6; i++) { if (m1[i].isInteger()) { dm1[i] = m1[i].toInt64(); } else if (m1[i].isDouble() || m1[i].isString()) { dm1[i] = m1[i].toDouble(); } else { raise_warning("imageaffinematrixconcat(): Invalid type for " "element %i", i); return false; } if (m2[i].isInteger()) { dm2[i] = m2[i].toInt64(); } else if (m2[i].isDouble() || m2[i].isString()) { dm2[i] = m2[i].toDouble(); } else { raise_warning("imageaffinematrixconcat():Invalid type for" "element %i", i); return false; } } if (gdAffineConcat(dmr, dm1, dm2) != GD_TRUE) { return false; } for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), dmr[i]); } return ret; } Variant HHVM_FUNCTION(imageaffinematrixget, int64_t type, const Variant& options /* = Array() */) { Array ret = Array::Create(); double affine[6]; int res = GD_FALSE, i; switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; Array aoptions = options.toArray(); if (aoptions.empty()) { raise_warning("imageaffinematrixget(): Array expected as options"); return false; } if (aoptions.exists(s_x)) { x = aoptions[s_x].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (aoptions.exists(s_y)) { y = aoptions[s_y].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; double doptions = options.toDouble(); if (!doptions) { raise_warning("imageaffinematrixget(): Number is expected as option"); return false; } angle = doptions; if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: raise_warning("imageaffinematrixget():Invalid type for " "element %" PRId64, type); return false; } if (res == GD_FALSE) { return false; } else { for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), affine[i]); } } return ret; } bool HHVM_FUNCTION(imagealphablending, const Resource& image, bool blendmode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, blendmode); return true; } bool HHVM_FUNCTION(imagesavealpha, const Resource& image, bool saveflag) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSaveAlpha(im, saveflag); return true; } bool HHVM_FUNCTION(imagelayereffect, const Resource& image, int64_t effect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, effect); return true; } Variant HHVM_FUNCTION(imagecolorallocatealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagecolorresolvealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolveAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorclosestalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorexactalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExactAlpha(im, red, green, blue, alpha); } bool HHVM_FUNCTION(imagecopyresampled, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = get_valid_image_resource(src_im); if (!im_src) return false; gdImagePtr im_dst = get_valid_image_resource(dst_im); if (!im_dst) return false; gdImageCopyResampled(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagerotate, const Resource& source_image, double angle, int64_t bgd_color, int64_t /*ignore_transparent*/ /* = 0 */) { gdImagePtr im_src = get_valid_image_resource(source_image); if (!im_src) return false; gdImagePtr im_dst = gdImageRotateInterpolated(im_src, angle, bgd_color); if (!im_dst) return false; return Variant(req::make<Image>(im_dst)); } bool HHVM_FUNCTION(imagesettile, const Resource& image, const Resource& tile) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr til = get_valid_image_resource(tile); if (!til) return false; gdImageSetTile(im, til); return true; } bool HHVM_FUNCTION(imagesetbrush, const Resource& image, const Resource& brush) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr tile = get_valid_image_resource(brush); if (!tile) return false; gdImageSetBrush(im, tile); return true; } bool HHVM_FUNCTION(imagesetinterpolation, const Resource& image, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (method == -1) method = GD_BILINEAR_FIXED; return gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method); } Variant HHVM_FUNCTION(imagecreate, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreate(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } int64_t HHVM_FUNCTION(imagetypes) { int ret=0; ret = IMAGE_TYPE_GIF; #ifdef HAVE_GD_JPG ret |= IMAGE_TYPE_JPEG; #endif #ifdef HAVE_GD_PNG ret |= IMAGE_TYPE_PNG; #endif ret |= IMAGE_TYPE_WBMP; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret |= IMAGE_TYPE_XPM; #endif return ret; } Variant HHVM_FUNCTION(imagecreatefromstring, const String& data) { gdImagePtr im; int imtype; char sig[8]; if (data.length() < 8) { raise_warning("Empty string or invalid image"); return false; } memcpy(sig, data.c_str(), 8); imtype = _php_image_type(sig); switch (imtype) { case PHP_GDIMG_TYPE_JPG: #ifdef HAVE_GD_JPG im = _php_image_create_from_string(data, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpegCtx); #else raise_warning("No JPEG support"); return false; #endif break; case PHP_GDIMG_TYPE_PNG: #ifdef HAVE_GD_PNG im = _php_image_create_from_string(data, "PNG", (gdImagePtr(*)())gdImageCreateFromPngCtx); #else raise_warning("No PNG support"); return false; #endif break; case PHP_GDIMG_TYPE_WEBP: #ifdef HAVE_LIBVPX im = _php_image_create_from_string(data, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebpCtx); #else raise_warning("No webp support (libvpx is needed)"); return false; #endif break; case PHP_GDIMG_TYPE_GIF: im = _php_image_create_from_string(data, "GIF", (gdImagePtr(*)())gdImageCreateFromGifCtx); break; case PHP_GDIMG_TYPE_WBM: im = _php_image_create_from_string(data, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMPCtx); break; case PHP_GDIMG_TYPE_GD2: im = _php_image_create_from_string(data, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Ctx); break; default: raise_warning("Data is not in a recognized format"); return false; } if (!im) { raise_warning("Couldn't create GD Image Stream out of Data"); return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgif, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (gdImagePtr(*)())gdImageCreateFromGif, (gdImagePtr(*)())gdImageCreateFromGifCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #ifdef HAVE_GD_JPG Variant HHVM_FUNCTION(imagecreatefromjpeg, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpeg, (gdImagePtr(*)())gdImageCreateFromJpegCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_GD_PNG Variant HHVM_FUNCTION(imagecreatefrompng, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_PNG, "PNG", (gdImagePtr(*)())gdImageCreateFromPng, (gdImagePtr(*)())gdImageCreateFromPngCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_LIBVPX Variant HHVM_FUNCTION(imagecreatefromwebp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebp, (gdImagePtr(*)())gdImageCreateFromWebpCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromxbm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XBM, "XBM", (gdImagePtr(*)())gdImageCreateFromXbm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) Variant HHVM_FUNCTION(imagecreatefromxpm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XPM, "XPM", (gdImagePtr(*)())gdImageCreateFromXpm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromwbmp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMP, (gdImagePtr(*)())gdImageCreateFromWBMPCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (gdImagePtr(*)())gdImageCreateFromGd, (gdImagePtr(*)())gdImageCreateFromGdCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD2, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2, (gdImagePtr(*)())gdImageCreateFromGd2Ctx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2part, const String& filename, int64_t srcx, int64_t srcy, int64_t width, int64_t height) { gdImagePtr im = _php_image_create_from(filename, srcx, srcy, width, height, PHP_GDIMG_TYPE_GD2PART, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Part, (gdImagePtr(*)())gdImageCreateFromGd2PartCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } bool HHVM_FUNCTION(imagegif, const Resource& image, const String& filename /* = null_string */) { return _php_image_output_ctx(image, filename, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (void (*)())gdImageGifCtx); } #ifdef HAVE_GD_PNG bool HHVM_FUNCTION(imagepng, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */, int64_t filters /* = -1 */) { return _php_image_output_ctx(image, filename, quality, filters, PHP_GDIMG_TYPE_PNG, "PNG", (void (*)())gdImagePngCtxEx); } #endif #ifdef HAVE_LIBVPX bool HHVM_FUNCTION(imagewebp, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = 80 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (void (*)())gdImageWebpCtx); } #endif #ifdef HAVE_GD_JPG bool HHVM_FUNCTION(imagejpeg, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (void (*)())gdImageJpegCtx); } #endif bool HHVM_FUNCTION(imagewbmp, const Resource& image, const String& filename /* = null_string */, int64_t foreground /* = -1 */) { return _php_image_output_ctx(image, filename, foreground, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (void (*)())gdImageWBMPCtx); } bool HHVM_FUNCTION(imagegd, const Resource& image, const String& filename /* = null_string */) { return _php_image_output(image, filename, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (void (*)())gdImageGd); } bool HHVM_FUNCTION(imagegd2, const Resource& image, const String& filename /* = null_string */, int64_t chunk_size /* = 0 */, int64_t type /* = 0 */) { return _php_image_output(image, filename, chunk_size, type, PHP_GDIMG_TYPE_GD2, "GD2", (void (*)())gdImageGd2); } bool HHVM_FUNCTION(imagedestroy, const Resource& image) { auto img_res = cast<Image>(image); gdImagePtr im = img_res->get(); if (!im) return false; img_res->reset(); return true; } Variant HHVM_FUNCTION(imagecolorallocate, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocate(im, red, green, blue); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagepalettecopy, const Resource& dst, const Resource& src) { gdImagePtr dstim = cast<Image>(dst)->get(); gdImagePtr srcim = cast<Image>(src)->get(); if (!dstim || !srcim) return false; gdImagePaletteCopy(dstim, srcim); return true; } Variant HHVM_FUNCTION(imagecolorat, const Resource& image, int64_t x, int64_t y) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (gdImageTrueColor(im)) { if (im->tpixels && gdImageBoundsSafe(im, x, y)) { return gdImageTrueColorPixel(im, x, y); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } else { if (im->pixels && gdImageBoundsSafe(im, x, y)) { return (im->pixels[y][x]); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } } Variant HHVM_FUNCTION(imagecolorclosest, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosest(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorclosesthwb, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestHWB(im, red, green, blue); } bool HHVM_FUNCTION(imagecolordeallocate, const Resource& image, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; /* We can return right away for a truecolor image as deallocating colours is meaningless here */ if (gdImageTrueColor(im)) return true; if (color >= 0 && color < gdImageColorsTotal(im)) { gdImageColorDeallocate(im, color); return true; } else { raise_warning("Color index %" PRId64 " out of range", color); return false; } } Variant HHVM_FUNCTION(imagecolorresolve, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolve(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorexact, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExact(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorset, const Resource& image, int64_t index, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && index < gdImageColorsTotal(im)) { im->red[index] = red; im->green[index] = green; im->blue[index] = blue; return true; } else { return false; } } const StaticString s_red("red"), s_green("green"), s_blue("blue"), s_alpha("alpha"); Variant HHVM_FUNCTION(imagecolorsforindex, const Resource& image, int64_t index) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && (gdImageTrueColor(im) || index < gdImageColorsTotal(im))) { return make_map_array( s_red, gdImageRed(im,index), s_green, gdImageGreen(im,index), s_blue, gdImageBlue(im,index), s_alpha, gdImageAlpha(im,index) ); } raise_warning("Color index %" PRId64 " out of range", index); return false; } bool HHVM_FUNCTION(imagegammacorrect, const Resource& image, double inputgamma, double outputgamma) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (inputgamma <= 0.0 || outputgamma <= 0.0) { raise_warning("Gamma values should be positive"); return false; } if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColor((int)((pow((pow((gdTrueColorGetRed(c)/255.0), inputgamma)),1.0/outputgamma)*255) + .5), (int)((pow((pow((gdTrueColorGetGreen(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5), (int)((pow((pow((gdTrueColorGetBlue(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5))); } } return true; } for (int i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->green[i] = (int)((pow((pow((im->green[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); } return true; } bool HHVM_FUNCTION(imagesetpixel, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetPixel(im, x, y, color); return true; } bool HHVM_FUNCTION(imageline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagedashedline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageDashedLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagerectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagefilledrectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagearc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, start, end, color); return true; } bool HHVM_FUNCTION(imageellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, 0, 360, color); return true; } bool HHVM_FUNCTION(imagefilltoborder, const Resource& image, int64_t x, int64_t y, int64_t border, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFillToBorder(im, x, y, border, color); return true; } bool HHVM_FUNCTION(imagefill, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFill(im, x, y, color); return true; } Variant HHVM_FUNCTION(imagecolorstotal, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return (gdImageColorsTotal(im)); } Variant HHVM_FUNCTION(imagecolortransparent, const Resource& image, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (color != -1) { // has color argument gdImageColorTransparent(im, color); } return gdImageGetTransparent(im); } TypedValue HHVM_FUNCTION(imageinterlace, const Resource& image, TypedValue interlace /* = 0 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return make_tv<KindOfBoolean>(false); if (!tvIsNull(interlace)) { // has interlace argument gdImageInterlace(im, tvAssertInt(interlace)); } return make_tv<KindOfInt64>(gdImageGetInterlaced(im)); } bool HHVM_FUNCTION(imagepolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 0); } bool HHVM_FUNCTION(imagefilledpolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 1); } int64_t HHVM_FUNCTION(imagefontwidth, int64_t font) { return php_imagefontsize(font, 0); } int64_t HHVM_FUNCTION(imagefontheight, int64_t font) { return php_imagefontsize(font, 1); } bool HHVM_FUNCTION(imagechar, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 0); } bool HHVM_FUNCTION(imagecharup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 1); } bool HHVM_FUNCTION(imagestring, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 2); } bool HHVM_FUNCTION(imagestringup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 3); } bool HHVM_FUNCTION(imagecopy, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopy(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h); return true; } bool HHVM_FUNCTION(imagecopymerge, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMerge(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopymergegray, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMergeGray(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopyresized, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; if (dst_w <= 0 || dst_h <= 0 || src_w <= 0 || src_h <= 0) { raise_warning("Invalid image dimensions"); return false; } gdImageCopyResized(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagesx, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSX(im); } Variant HHVM_FUNCTION(imagesy, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSY(im); } #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE Variant HHVM_FUNCTION(imageftbbox, double size, double angle, const String& font_file, const String& text, const Array& extrainfo /*=[] */) { return php_imagettftext_common(TTFTEXT_BBOX, 1, size, angle, font_file, text, extrainfo); } Variant HHVM_FUNCTION(imagefttext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t col, const String& font_file, const String& text, const Array& extrainfo) { return php_imagettftext_common(TTFTEXT_DRAW, 1, image, size, angle, x, y, col, font_file, text, extrainfo); } #endif #ifdef ENABLE_GD_TTF Variant HHVM_FUNCTION(imagettfbbox, double size, double angle, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_BBOX, 0, size, angle, fontfile, text); } Variant HHVM_FUNCTION(imagettftext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t color, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_DRAW, 0, image, size.toDouble(), angle.toDouble(), x, y, color, fontfile, text); } #endif bool HHVM_FUNCTION(image2wbmp, const Resource& image, const String& filename /* = null_string */, int64_t threshold /* = -1 */) { return _php_image_output(image, filename, threshold, -1, PHP_GDIMG_CONVERT_WBM, "WBMP", (void (*)())_php_image_bw_convert); } bool HHVM_FUNCTION(jpeg2wbmp, const String& jpegname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(jpegname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_JPG); } bool HHVM_FUNCTION(png2wbmp, const String& pngname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(pngname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_PNG); } bool HHVM_FUNCTION(imagefilter, const Resource& res, int64_t filtertype, const Variant& arg1 /*=0*/, const Variant& arg2 /*=0*/, const Variant& arg3 /*=0*/, const Variant& arg4 /*=0*/) { gdImagePtr im = get_valid_image_resource(res); if (!im) return false; /* Exists purely to mirror PHP5's invalid arg logic for this function */ #define IMFILT_TYPECHK(n) \ if (!arg##n.isBoolean() && !arg##n.isNumeric(true)) { \ raise_warning("imagefilter() expected boolean/numeric for argument %d", \ (n+2)); \ return false; \ } IMFILT_TYPECHK(1) IMFILT_TYPECHK(2) IMFILT_TYPECHK(3) IMFILT_TYPECHK(4) #undef IMFILT_TYPECHECK using image_filter = bool (*)(gdImagePtr, int, int, int, int); image_filter filters[] = { php_image_filter_negate, php_image_filter_grayscale, php_image_filter_brightness, php_image_filter_contrast, php_image_filter_colorize, php_image_filter_edgedetect, php_image_filter_emboss, php_image_filter_gaussian_blur, php_image_filter_selective_blur, php_image_filter_mean_removal, php_image_filter_smooth, php_image_filter_pixelate, }; auto const num_filters = sizeof(filters) / sizeof(image_filter); if (filtertype >= 0 && filtertype < num_filters) { return filters[filtertype](im, arg1.toInt64(), arg2.toInt64(), arg3.toInt64(), arg4.toInt64()); } return false; } bool HHVM_FUNCTION(imageflip, const Resource& image, int64_t mode /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (mode == -1) mode = GD_FLIP_HORINZONTAL; switch (mode) { case GD_FLIP_VERTICAL: gdImageFlipVertical(im); break; case GD_FLIP_HORINZONTAL: gdImageFlipHorizontal(im); break; case GD_FLIP_BOTH: gdImageFlipBoth(im); break; default: raise_warning("imageflip(): Unknown flip mode"); return false; } return true; } // gdImageConvolution does not exist in our libgd.a, copied from // php's libgd/gd.c /* Filters function added on 2003/12 * by Pierre-Alain Joye (pajoye@pearfr.org) **/ static int hphp_gdImageConvolution(gdImagePtr src, float filter[3][3], float filter_div, float offset) { int x, y, i, j, new_a; float new_r, new_g, new_b; int new_pxl, pxl=0; gdImagePtr srcback; if (src==nullptr) { return 0; } /* We need the orinal image with each safe neoghb. pixel */ srcback = gdImageCreateTrueColor (src->sx, src->sy); gdImageCopy(srcback, src,0,0,0,0,src->sx,src->sy); if (srcback==nullptr) { return 0; } for ( y=0; y<src->sy; y++) { for(x=0; x<src->sx; x++) { new_r = new_g = new_b = 0; new_a = gdImageAlpha(srcback, pxl); for (j=0; j<3; j++) { int yv = std::min(std::max(y - 1 + j, 0), src->sy - 1); for (i=0; i<3; i++) { pxl = gdImageGetPixel(srcback, std::min(std::max(x - 1 + i, 0), src->sx - 1), yv); new_r += (float)gdImageRed(srcback, pxl) * filter[j][i]; new_g += (float)gdImageGreen(srcback, pxl) * filter[j][i]; new_b += (float)gdImageBlue(srcback, pxl) * filter[j][i]; } } new_r = (new_r/filter_div)+offset; new_g = (new_g/filter_div)+offset; new_b = (new_b/filter_div)+offset; new_r = (new_r > 255.0f)? 255.0f : ((new_r < 0.0f)? 0.0f:new_r); new_g = (new_g > 255.0f)? 255.0f : ((new_g < 0.0f)? 0.0f:new_g); new_b = (new_b > 255.0f)? 255.0f : ((new_b < 0.0f)? 0.0f:new_b); new_pxl = gdImageColorAllocateAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); if (new_pxl == -1) { new_pxl = gdImageColorClosestAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); } gdImageSetPixel (src, x, y, new_pxl); } } gdImageDestroy(srcback); return 1; } bool HHVM_FUNCTION(imageconvolution, const Resource& image, const Array& matrix, double div, double offset) { gdImagePtr im_src = cast<Image>(image)->get(); if (!im_src) return false; int nelem = matrix.size(); int i, j; float mtx[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; Variant v; Array row; if (nelem != 3) { raise_warning("You must have 3x3 array"); return false; } for (i=0; i<3; i++) { if (matrix.exists(i) && (v = matrix[i]).isArray()) { if ((row = v.toArray()).size() != 3) { raise_warning("You must have 3x3 array"); return false; } for (j=0; j<3; j++) { if (row.exists(j)) { mtx[i][j] = row[j].toDouble(); } else { raise_warning("You must have a 3x3 matrix"); return false; } } } } if (hphp_gdImageConvolution(im_src, mtx, div, offset)) { return true; } else { return false; } } bool HHVM_FUNCTION(imageantialias, const Resource& image, bool on) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; SetAntiAliased(im, on); return true; } Variant HHVM_FUNCTION(imagescale, const Resource& image, int64_t newwidth, int64_t newheight /* =-1 */, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imscaled = nullptr; gdInterpolationMethod old_method; if (method == -1) method = GD_BILINEAR_FIXED; if (newheight < 0) { /* preserve ratio */ long src_x, src_y; src_x = gdImageSX(im); src_y = gdImageSY(im); if (src_x) { newheight = newwidth * src_y / src_x; } } if (newheight <= 0 || newheight > INT_MAX || newwidth <= 0 || newwidth > INT_MAX) { return false; } old_method = im->interpolation_id; if (gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method)) { imscaled = gdImageScale(im, newwidth, newheight); } gdImageSetInterpolationMethod(im, old_method); if (imscaled == nullptr) { return false; } return Variant(req::make<Image>(imscaled)); } namespace { // PHP extension STANDARD: iptc.c inline int php_iptc_put1(req::ptr<File> /*file*/, int spool, unsigned char c, unsigned char** spoolbuf) { if (spool > 0) { g_context->write((const char *)&c, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_get1(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; char cc; c = file->getc(); if (c == EOF) return EOF; if (spool > 0) { cc = c; g_context->write((const char *)&cc, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_read_remaining(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { while (php_iptc_get1(file, spool, spoolbuf) != EOF) continue; return M_EOI; } int php_iptc_skip_variable(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { unsigned int length; int c1, c2; if ((c1 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; if ((c2 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) { if (php_iptc_get1(file, spool, spoolbuf) == EOF) return M_EOI; } return 0; } int php_iptc_next_marker(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; /* skip unimportant stuff */ c = php_iptc_get1(file, spool, spoolbuf); if (c == EOF) return M_EOI; while (c != 0xff) { if ((c = php_iptc_get1(file, spool, spoolbuf)) == EOF) { return M_EOI; /* we hit EOF */ } } /* get marker byte, swallowing possible padding */ do { c = php_iptc_get1(file, 0, 0); if (c == EOF) return M_EOI; /* we hit EOF */ else if (c == 0xff) php_iptc_put1(file, spool, (unsigned char)c, spoolbuf); } while (c == 0xff); return (unsigned int) c; } } const StaticString s_size("size"); Variant HHVM_FUNCTION(iptcembed, const String& iptcdata, const String& jpeg_file_name, int64_t spool /* = 0 */) { char psheader[] = "\xFF\xED\0\0Photoshop 3.0\08BIM\x04\x04\0\0\0"; static_assert(sizeof(psheader) == 28, "psheader must be 28 bytes"); unsigned int iptcdata_len = iptcdata.length(); unsigned int marker, inx; unsigned char *spoolbuf = nullptr, *poi = nullptr; bool done = false; bool written = false; auto file = File::Open(jpeg_file_name, "rb"); if (!file) { raise_warning("failed to open file: %s", jpeg_file_name.c_str()); return false; } if (spool < 2) { auto stat = HHVM_FN(fstat)(Resource(file)); // TODO(t7561579) until we can properly handle non-file streams here, don't // pretend we can and crash. if (!stat.isArray()) { raise_warning("unable to stat input"); return false; } auto& stat_arr = stat.toCArrRef(); auto st_size = stat_arr[s_size].toInt64(); if (st_size < 0) { raise_warning("unsupported stream type"); return false; } if (iptcdata_len >= (INT64_MAX - sizeof(psheader) - st_size - 1024 - 1)) { raise_warning("iptcdata too long"); return false; } auto malloc_size = iptcdata_len + sizeof(psheader) + st_size + 1024 + 1; poi = spoolbuf = (unsigned char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(poi, malloc_size, false); memset(poi, 0, malloc_size); } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xFF) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xD8) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } while (!done) { marker = php_iptc_next_marker(file, spool, poi?&poi:0); if (marker == M_EOI) { /* EOF */ break; } else if (marker != M_APP13) { php_iptc_put1(file, spool, (unsigned char)marker, poi?&poi:0); } switch (marker) { case M_APP13: /* we are going to write a new APP13 marker, so don't output the old one */ php_iptc_skip_variable(file, 0, 0); php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; case M_APP0: /* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */ case M_APP1: if (written) { /* don't try to write the data twice */ break; } written = true; php_iptc_skip_variable(file, spool, poi?&poi:0); if (iptcdata_len & 1) { iptcdata_len++; /* make the length even */ } psheader[2] = (iptcdata_len + sizeof(psheader)) >> 8; psheader[3] = (iptcdata_len + sizeof(psheader)) & 0xff; for (inx = 0; inx < sizeof(psheader); inx++) { php_iptc_put1(file, spool, psheader[inx], poi ? &poi : 0); } php_iptc_put1(file, spool, (unsigned char)(iptcdata_len>>8), poi?&poi:0); php_iptc_put1(file, spool, (unsigned char)(iptcdata_len&0xff), poi?&poi:0); for (inx = 0; inx < iptcdata_len; inx++) { php_iptc_put1(file, spool, iptcdata.c_str()[inx], poi?&poi:0); } break; case M_SOS: /* we hit data, no more marker-inserting can be done! */ php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; default: php_iptc_skip_variable(file, spool, poi?&poi:0); break; } } file->close(); if (spool < 2) { return String((char *)spoolbuf, poi - spoolbuf, AttachString); } return true; } Variant HHVM_FUNCTION(iptcparse, const String& iptcblock) { unsigned int inx = 0, len, tagsfound = 0; unsigned char *buffer, recnum, dataset, key[16]; unsigned int str_len = iptcblock.length(); Array ret; buffer = (unsigned char *)iptcblock.c_str(); while (inx < str_len) { /* find 1st tag */ if ((buffer[inx] == 0x1c) && ((buffer[inx+1] == 0x01) || (buffer[inx+1] == 0x02))) { break; } else { inx++; } } while (inx < str_len) { if (buffer[ inx++ ] != 0x1c) { /* we ran against some data which does not conform to IPTC - stop parsing! */ break; } if ((inx + 4) >= str_len) break; dataset = buffer[inx++]; recnum = buffer[inx++]; if (buffer[inx] & (unsigned char) 0x80) { /* long tag */ if (inx + 6 >= str_len) break; len = (((long)buffer[inx + 2]) << 24) + (((long)buffer[inx + 3]) << 16) + (((long)buffer[inx + 4]) << 8) + (((long)buffer[inx + 5])); inx += 6; } else { /* short tag */ len = (((unsigned short)buffer[inx])<<8) | (unsigned short)buffer[inx+1]; inx += 2; } snprintf((char *)key, sizeof(key), "%d#%03d", (unsigned int)dataset, (unsigned int)recnum); if ((len > str_len) || (inx + len) > str_len) { break; } String skey((const char *)key, CopyString); if (!ret.exists(skey)) { ret.set(skey, Array::CreateVArray()); } auto const lval = ret.lvalAt(skey); forceToArray(lval).append( String((const char *)(buffer+inx), len, CopyString)); inx += len; tagsfound++; } if (!tagsfound) { return false; } return ret; } // PHP extension exif.c #define NUM_FORMATS 13 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 #define TAG_FMT_IFD 13 /* Describes tag values */ #define TAG_GPS_VERSION_ID 0x0000 #define TAG_GPS_LATITUDE_REF 0x0001 #define TAG_GPS_LATITUDE 0x0002 #define TAG_GPS_LONGITUDE_REF 0x0003 #define TAG_GPS_LONGITUDE 0x0004 #define TAG_GPS_ALTITUDE_REF 0x0005 #define TAG_GPS_ALTITUDE 0x0006 #define TAG_GPS_TIME_STAMP 0x0007 #define TAG_GPS_SATELLITES 0x0008 #define TAG_GPS_STATUS 0x0009 #define TAG_GPS_MEASURE_MODE 0x000A #define TAG_GPS_DOP 0x000B #define TAG_GPS_SPEED_REF 0x000C #define TAG_GPS_SPEED 0x000D #define TAG_GPS_TRACK_REF 0x000E #define TAG_GPS_TRACK 0x000F #define TAG_GPS_IMG_DIRECTION_REF 0x0010 #define TAG_GPS_IMG_DIRECTION 0x0011 #define TAG_GPS_MAP_DATUM 0x0012 #define TAG_GPS_DEST_LATITUDE_REF 0x0013 #define TAG_GPS_DEST_LATITUDE 0x0014 #define TAG_GPS_DEST_LONGITUDE_REF 0x0015 #define TAG_GPS_DEST_LONGITUDE 0x0016 #define TAG_GPS_DEST_BEARING_REF 0x0017 #define TAG_GPS_DEST_BEARING 0x0018 #define TAG_GPS_DEST_DISTANCE_REF 0x0019 #define TAG_GPS_DEST_DISTANCE 0x001A #define TAG_GPS_PROCESSING_METHOD 0x001B #define TAG_GPS_AREA_INFORMATION 0x001C #define TAG_GPS_DATE_STAMP 0x001D #define TAG_GPS_DIFFERENTIAL 0x001E #define TAG_TIFF_COMMENT 0x00FE /* SHOUDLNT HAPPEN */ #define TAG_NEW_SUBFILE 0x00FE /* New version of subfile tag */ #define TAG_SUBFILE_TYPE 0x00FF /* Old version of subfile tag */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 #define TAG_BITS_PER_SAMPLE 0x0102 #define TAG_COMPRESSION 0x0103 #define TAG_PHOTOMETRIC_INTERPRETATION 0x0106 #define TAG_TRESHHOLDING 0x0107 #define TAG_CELL_WIDTH 0x0108 #define TAG_CELL_HEIGHT 0x0109 #define TAG_FILL_ORDER 0x010A #define TAG_DOCUMENT_NAME 0x010D #define TAG_IMAGE_DESCRIPTION 0x010E #define TAG_MAKE 0x010F #define TAG_MODEL 0x0110 #define TAG_STRIP_OFFSETS 0x0111 #define TAG_ORIENTATION 0x0112 #define TAG_SAMPLES_PER_PIXEL 0x0115 #define TAG_ROWS_PER_STRIP 0x0116 #define TAG_STRIP_BYTE_COUNTS 0x0117 #define TAG_MIN_SAMPPLE_VALUE 0x0118 #define TAG_MAX_SAMPLE_VALUE 0x0119 #define TAG_X_RESOLUTION 0x011A #define TAG_Y_RESOLUTION 0x011B #define TAG_PLANAR_CONFIGURATION 0x011C #define TAG_PAGE_NAME 0x011D #define TAG_X_POSITION 0x011E #define TAG_Y_POSITION 0x011F #define TAG_FREE_OFFSETS 0x0120 #define TAG_FREE_BYTE_COUNTS 0x0121 #define TAG_GRAY_RESPONSE_UNIT 0x0122 #define TAG_GRAY_RESPONSE_CURVE 0x0123 #define TAG_RESOLUTION_UNIT 0x0128 #define TAG_PAGE_NUMBER 0x0129 #define TAG_TRANSFER_FUNCTION 0x012D #define TAG_SOFTWARE 0x0131 #define TAG_DATETIME 0x0132 #define TAG_ARTIST 0x013B #define TAG_HOST_COMPUTER 0x013C #define TAG_PREDICTOR 0x013D #define TAG_WHITE_POINT 0x013E #define TAG_PRIMARY_CHROMATICITIES 0x013F #define TAG_COLOR_MAP 0x0140 #define TAG_HALFTONE_HINTS 0x0141 #define TAG_TILE_WIDTH 0x0142 #define TAG_TILE_LENGTH 0x0143 #define TAG_TILE_OFFSETS 0x0144 #define TAG_TILE_BYTE_COUNTS 0x0145 #define TAG_SUB_IFD 0x014A #define TAG_INK_SETMPUTER 0x014C #define TAG_INK_NAMES 0x014D #define TAG_NUMBER_OF_INKS 0x014E #define TAG_DOT_RANGE 0x0150 #define TAG_TARGET_PRINTER 0x0151 #define TAG_EXTRA_SAMPLE 0x0152 #define TAG_SAMPLE_FORMAT 0x0153 #define TAG_S_MIN_SAMPLE_VALUE 0x0154 #define TAG_S_MAX_SAMPLE_VALUE 0x0155 #define TAG_TRANSFER_RANGE 0x0156 #define TAG_JPEG_TABLES 0x015B #define TAG_JPEG_PROC 0x0200 #define TAG_JPEG_INTERCHANGE_FORMAT 0x0201 #define TAG_JPEG_INTERCHANGE_FORMAT_LEN 0x0202 #define TAG_JPEG_RESTART_INTERVAL 0x0203 #define TAG_JPEG_LOSSLESS_PREDICTOR 0x0205 #define TAG_JPEG_POINT_TRANSFORMS 0x0206 #define TAG_JPEG_Q_TABLES 0x0207 #define TAG_JPEG_DC_TABLES 0x0208 #define TAG_JPEG_AC_TABLES 0x0209 #define TAG_YCC_COEFFICIENTS 0x0211 #define TAG_YCC_SUB_SAMPLING 0x0212 #define TAG_YCC_POSITIONING 0x0213 #define TAG_REFERENCE_BLACK_WHITE 0x0214 /* 0x0301 - 0x0302 */ /* 0x0320 */ /* 0x0343 */ /* 0x5001 - 0x501B */ /* 0x5021 - 0x503B */ /* 0x5090 - 0x5091 */ /* 0x5100 - 0x5101 */ /* 0x5110 - 0x5113 */ /* 0x80E3 - 0x80E6 */ /* 0x828d - 0x828F */ #define TAG_COPYRIGHT 0x8298 #define TAG_EXPOSURETIME 0x829A #define TAG_FNUMBER 0x829D #define TAG_EXIF_IFD_POINTER 0x8769 #define TAG_ICC_PROFILE 0x8773 #define TAG_EXPOSURE_PROGRAM 0x8822 #define TAG_SPECTRAL_SENSITY 0x8824 #define TAG_GPS_IFD_POINTER 0x8825 #define TAG_ISOSPEED 0x8827 #define TAG_OPTOELECTRIC_CONVERSION_F 0x8828 /* 0x8829 - 0x882b */ #define TAG_EXIFVERSION 0x9000 #define TAG_DATE_TIME_ORIGINAL 0x9003 #define TAG_DATE_TIME_DIGITIZED 0x9004 #define TAG_COMPONENT_CONFIG 0x9101 #define TAG_COMPRESSED_BITS_PER_PIXEL 0x9102 #define TAG_SHUTTERSPEED 0x9201 #define TAG_APERTURE 0x9202 #define TAG_BRIGHTNESS_VALUE 0x9203 #define TAG_EXPOSURE_BIAS_VALUE 0x9204 #define TAG_MAX_APERTURE 0x9205 #define TAG_SUBJECT_DISTANCE 0x9206 #define TAG_METRIC_MODULE 0x9207 #define TAG_LIGHT_SOURCE 0x9208 #define TAG_FLASH 0x9209 #define TAG_FOCAL_LENGTH 0x920A /* 0x920B - 0x920D */ /* 0x9211 - 0x9216 */ #define TAG_SUBJECT_AREA 0x9214 #define TAG_MAKER_NOTE 0x927C #define TAG_USERCOMMENT 0x9286 #define TAG_SUB_SEC_TIME 0x9290 #define TAG_SUB_SEC_TIME_ORIGINAL 0x9291 #define TAG_SUB_SEC_TIME_DIGITIZED 0x9292 /* 0x923F */ /* 0x935C */ #define TAG_XP_TITLE 0x9C9B #define TAG_XP_COMMENTS 0x9C9C #define TAG_XP_AUTHOR 0x9C9D #define TAG_XP_KEYWORDS 0x9C9E #define TAG_XP_SUBJECT 0x9C9F #define TAG_FLASH_PIX_VERSION 0xA000 #define TAG_COLOR_SPACE 0xA001 #define TAG_COMP_IMAGE_WIDTH 0xA002 /* compressed images only */ #define TAG_COMP_IMAGE_HEIGHT 0xA003 #define TAG_RELATED_SOUND_FILE 0xA004 #define TAG_INTEROP_IFD_POINTER 0xA005 /* IFD pointer */ #define TAG_FLASH_ENERGY 0xA20B #define TAG_SPATIAL_FREQUENCY_RESPONSE 0xA20C #define TAG_FOCALPLANE_X_RES 0xA20E #define TAG_FOCALPLANE_Y_RES 0xA20F #define TAG_FOCALPLANE_RESOLUTION_UNIT 0xA210 #define TAG_SUBJECT_LOCATION 0xA214 #define TAG_EXPOSURE_INDEX 0xA215 #define TAG_SENSING_METHOD 0xA217 #define TAG_FILE_SOURCE 0xA300 #define TAG_SCENE_TYPE 0xA301 #define TAG_CFA_PATTERN 0xA302 #define TAG_CUSTOM_RENDERED 0xA401 #define TAG_EXPOSURE_MODE 0xA402 #define TAG_WHITE_BALANCE 0xA403 #define TAG_DIGITAL_ZOOM_RATIO 0xA404 #define TAG_FOCAL_LENGTH_IN_35_MM_FILM 0xA405 #define TAG_SCENE_CAPTURE_TYPE 0xA406 #define TAG_GAIN_CONTROL 0xA407 #define TAG_CONTRAST 0xA408 #define TAG_SATURATION 0xA409 #define TAG_SHARPNESS 0xA40A #define TAG_DEVICE_SETTING_DESCRIPTION 0xA40B #define TAG_SUBJECT_DISTANCE_RANGE 0xA40C #define TAG_IMAGE_UNIQUE_ID 0xA420 /* Olympus specific tags */ #define TAG_OLYMPUS_SPECIALMODE 0x0200 #define TAG_OLYMPUS_JPEGQUAL 0x0201 #define TAG_OLYMPUS_MACRO 0x0202 #define TAG_OLYMPUS_DIGIZOOM 0x0204 #define TAG_OLYMPUS_SOFTWARERELEASE 0x0207 #define TAG_OLYMPUS_PICTINFO 0x0208 #define TAG_OLYMPUS_CAMERAID 0x0209 /* end Olympus specific tags */ /* Internal */ #define TAG_NONE -1 /* note that -1 <> 0xFFFF */ #define TAG_COMPUTED_VALUE -2 #define TAG_END_OF_LIST 0xFFFD /* Values for TAG_PHOTOMETRIC_INTERPRETATION */ #define PMI_BLACK_IS_ZERO 0 #define PMI_WHITE_IS_ZERO 1 #define PMI_RGB 2 #define PMI_PALETTE_COLOR 3 #define PMI_TRANSPARENCY_MASK 4 #define PMI_SEPARATED 5 #define PMI_YCBCR 6 #define PMI_CIELAB 8 typedef const struct { unsigned short Tag; char *Desc; } tag_info_type; typedef tag_info_type tag_info_array[]; typedef tag_info_type *tag_table_type; #define TAG_TABLE_END \ {((unsigned short)TAG_NONE), "No tag value"},\ {((unsigned short)TAG_COMPUTED_VALUE), "Computed value"},\ {TAG_END_OF_LIST, ""} /* Important for exif_get_tagname() IF value != "" function result is != false */ static const tag_info_array tag_table_IFD = { { 0x000B, "ACDComment"}, { 0x00FE, "NewSubFile"}, /* better name it 'ImageType' ? */ { 0x00FF, "SubFile"}, { 0x0100, "ImageWidth"}, { 0x0101, "ImageLength"}, { 0x0102, "BitsPerSample"}, { 0x0103, "Compression"}, { 0x0106, "PhotometricInterpretation"}, { 0x010A, "FillOrder"}, { 0x010D, "DocumentName"}, { 0x010E, "ImageDescription"}, { 0x010F, "Make"}, { 0x0110, "Model"}, { 0x0111, "StripOffsets"}, { 0x0112, "Orientation"}, { 0x0115, "SamplesPerPixel"}, { 0x0116, "RowsPerStrip"}, { 0x0117, "StripByteCounts"}, { 0x0118, "MinSampleValue"}, { 0x0119, "MaxSampleValue"}, { 0x011A, "XResolution"}, { 0x011B, "YResolution"}, { 0x011C, "PlanarConfiguration"}, { 0x011D, "PageName"}, { 0x011E, "XPosition"}, { 0x011F, "YPosition"}, { 0x0120, "FreeOffsets"}, { 0x0121, "FreeByteCounts"}, { 0x0122, "GrayResponseUnit"}, { 0x0123, "GrayResponseCurve"}, { 0x0124, "T4Options"}, { 0x0125, "T6Options"}, { 0x0128, "ResolutionUnit"}, { 0x0129, "PageNumber"}, { 0x012D, "TransferFunction"}, { 0x0131, "Software"}, { 0x0132, "DateTime"}, { 0x013B, "Artist"}, { 0x013C, "HostComputer"}, { 0x013D, "Predictor"}, { 0x013E, "WhitePoint"}, { 0x013F, "PrimaryChromaticities"}, { 0x0140, "ColorMap"}, { 0x0141, "HalfToneHints"}, { 0x0142, "TileWidth"}, { 0x0143, "TileLength"}, { 0x0144, "TileOffsets"}, { 0x0145, "TileByteCounts"}, { 0x014A, "SubIFD"}, { 0x014C, "InkSet"}, { 0x014D, "InkNames"}, { 0x014E, "NumberOfInks"}, { 0x0150, "DotRange"}, { 0x0151, "TargetPrinter"}, { 0x0152, "ExtraSample"}, { 0x0153, "SampleFormat"}, { 0x0154, "SMinSampleValue"}, { 0x0155, "SMaxSampleValue"}, { 0x0156, "TransferRange"}, { 0x0157, "ClipPath"}, { 0x0158, "XClipPathUnits"}, { 0x0159, "YClipPathUnits"}, { 0x015A, "Indexed"}, { 0x015B, "JPEGTables"}, { 0x015F, "OPIProxy"}, { 0x0200, "JPEGProc"}, { 0x0201, "JPEGInterchangeFormat"}, { 0x0202, "JPEGInterchangeFormatLength"}, { 0x0203, "JPEGRestartInterval"}, { 0x0205, "JPEGLosslessPredictors"}, { 0x0206, "JPEGPointTransforms"}, { 0x0207, "JPEGQTables"}, { 0x0208, "JPEGDCTables"}, { 0x0209, "JPEGACTables"}, { 0x0211, "YCbCrCoefficients"}, { 0x0212, "YCbCrSubSampling"}, { 0x0213, "YCbCrPositioning"}, { 0x0214, "ReferenceBlackWhite"}, { 0x02BC, "ExtensibleMetadataPlatform"}, /* XAP: Extensible Authoring Publishing, obsoleted by XMP: Extensible Metadata Platform */ { 0x0301, "Gamma"}, { 0x0302, "ICCProfileDescriptor"}, { 0x0303, "SRGBRenderingIntent"}, { 0x0320, "ImageTitle"}, { 0x5001, "ResolutionXUnit"}, { 0x5002, "ResolutionYUnit"}, { 0x5003, "ResolutionXLengthUnit"}, { 0x5004, "ResolutionYLengthUnit"}, { 0x5005, "PrintFlags"}, { 0x5006, "PrintFlagsVersion"}, { 0x5007, "PrintFlagsCrop"}, { 0x5008, "PrintFlagsBleedWidth"}, { 0x5009, "PrintFlagsBleedWidthScale"}, { 0x500A, "HalftoneLPI"}, { 0x500B, "HalftoneLPIUnit"}, { 0x500C, "HalftoneDegree"}, { 0x500D, "HalftoneShape"}, { 0x500E, "HalftoneMisc"}, { 0x500F, "HalftoneScreen"}, { 0x5010, "JPEGQuality"}, { 0x5011, "GridSize"}, { 0x5012, "ThumbnailFormat"}, { 0x5013, "ThumbnailWidth"}, { 0x5014, "ThumbnailHeight"}, { 0x5015, "ThumbnailColorDepth"}, { 0x5016, "ThumbnailPlanes"}, { 0x5017, "ThumbnailRawBytes"}, { 0x5018, "ThumbnailSize"}, { 0x5019, "ThumbnailCompressedSize"}, { 0x501A, "ColorTransferFunction"}, { 0x501B, "ThumbnailData"}, { 0x5020, "ThumbnailImageWidth"}, { 0x5021, "ThumbnailImageHeight"}, { 0x5022, "ThumbnailBitsPerSample"}, { 0x5023, "ThumbnailCompression"}, { 0x5024, "ThumbnailPhotometricInterp"}, { 0x5025, "ThumbnailImageDescription"}, { 0x5026, "ThumbnailEquipMake"}, { 0x5027, "ThumbnailEquipModel"}, { 0x5028, "ThumbnailStripOffsets"}, { 0x5029, "ThumbnailOrientation"}, { 0x502A, "ThumbnailSamplesPerPixel"}, { 0x502B, "ThumbnailRowsPerStrip"}, { 0x502C, "ThumbnailStripBytesCount"}, { 0x502D, "ThumbnailResolutionX"}, { 0x502E, "ThumbnailResolutionY"}, { 0x502F, "ThumbnailPlanarConfig"}, { 0x5030, "ThumbnailResolutionUnit"}, { 0x5031, "ThumbnailTransferFunction"}, { 0x5032, "ThumbnailSoftwareUsed"}, { 0x5033, "ThumbnailDateTime"}, { 0x5034, "ThumbnailArtist"}, { 0x5035, "ThumbnailWhitePoint"}, { 0x5036, "ThumbnailPrimaryChromaticities"}, { 0x5037, "ThumbnailYCbCrCoefficients"}, { 0x5038, "ThumbnailYCbCrSubsampling"}, { 0x5039, "ThumbnailYCbCrPositioning"}, { 0x503A, "ThumbnailRefBlackWhite"}, { 0x503B, "ThumbnailCopyRight"}, { 0x5090, "LuminanceTable"}, { 0x5091, "ChrominanceTable"}, { 0x5100, "FrameDelay"}, { 0x5101, "LoopCount"}, { 0x5110, "PixelUnit"}, { 0x5111, "PixelPerUnitX"}, { 0x5112, "PixelPerUnitY"}, { 0x5113, "PaletteHistogram"}, { 0x1000, "RelatedImageFileFormat"}, { 0x800D, "ImageID"}, { 0x80E3, "Matteing"}, /* obsoleted by ExtraSamples */ { 0x80E4, "DataType"}, /* obsoleted by SampleFormat */ { 0x80E5, "ImageDepth"}, { 0x80E6, "TileDepth"}, { 0x828D, "CFARepeatPatternDim"}, { 0x828E, "CFAPattern"}, { 0x828F, "BatteryLevel"}, { 0x8298, "Copyright"}, { 0x829A, "ExposureTime"}, { 0x829D, "FNumber"}, { 0x83BB, "IPTC/NAA"}, { 0x84E3, "IT8RasterPadding"}, { 0x84E5, "IT8ColorTable"}, { 0x8649, "ImageResourceInformation"}, /* PhotoShop */ { 0x8769, "Exif_IFD_Pointer"}, { 0x8773, "ICC_Profile"}, { 0x8822, "ExposureProgram"}, { 0x8824, "SpectralSensity"}, { 0x8828, "OECF"}, { 0x8825, "GPS_IFD_Pointer"}, { 0x8827, "ISOSpeedRatings"}, { 0x8828, "OECF"}, { 0x9000, "ExifVersion"}, { 0x9003, "DateTimeOriginal"}, { 0x9004, "DateTimeDigitized"}, { 0x9101, "ComponentsConfiguration"}, { 0x9102, "CompressedBitsPerPixel"}, { 0x9201, "ShutterSpeedValue"}, { 0x9202, "ApertureValue"}, { 0x9203, "BrightnessValue"}, { 0x9204, "ExposureBiasValue"}, { 0x9205, "MaxApertureValue"}, { 0x9206, "SubjectDistance"}, { 0x9207, "MeteringMode"}, { 0x9208, "LightSource"}, { 0x9209, "Flash"}, { 0x920A, "FocalLength"}, { 0x920B, "FlashEnergy"}, /* 0xA20B in JPEG */ { 0x920C, "SpatialFrequencyResponse"}, /* 0xA20C - - */ { 0x920D, "Noise"}, { 0x920E, "FocalPlaneXResolution"}, /* 0xA20E - - */ { 0x920F, "FocalPlaneYResolution"}, /* 0xA20F - - */ { 0x9210, "FocalPlaneResolutionUnit"}, /* 0xA210 - - */ { 0x9211, "ImageNumber"}, { 0x9212, "SecurityClassification"}, { 0x9213, "ImageHistory"}, { 0x9214, "SubjectLocation"}, /* 0xA214 - - */ { 0x9215, "ExposureIndex"}, /* 0xA215 - - */ { 0x9216, "TIFF/EPStandardID"}, { 0x9217, "SensingMethod"}, /* 0xA217 - - */ { 0x923F, "StoNits"}, { 0x927C, "MakerNote"}, { 0x9286, "UserComment"}, { 0x9290, "SubSecTime"}, { 0x9291, "SubSecTimeOriginal"}, { 0x9292, "SubSecTimeDigitized"}, { 0x935C, "ImageSourceData"}, /* "Adobe Photoshop Document Data Block": 8BIM... */ { 0x9c9b, "Title" }, /* Win XP specific, Unicode */ { 0x9c9c, "Comments" }, /* Win XP specific, Unicode */ { 0x9c9d, "Author" }, /* Win XP specific, Unicode */ { 0x9c9e, "Keywords" }, /* Win XP specific, Unicode */ { 0x9c9f, "Subject" }, /* Win XP specific, Unicode, not to be confused with SubjectDistance and SubjectLocation */ { 0xA000, "FlashPixVersion"}, { 0xA001, "ColorSpace"}, { 0xA002, "ExifImageWidth"}, { 0xA003, "ExifImageLength"}, { 0xA004, "RelatedSoundFile"}, { 0xA005, "InteroperabilityOffset"}, { 0xA20B, "FlashEnergy"}, /* 0x920B in TIFF/EP */ { 0xA20C, "SpatialFrequencyResponse"}, /* 0x920C - - */ { 0xA20D, "Noise"}, { 0xA20E, "FocalPlaneXResolution"}, /* 0x920E - - */ { 0xA20F, "FocalPlaneYResolution"}, /* 0x920F - - */ { 0xA210, "FocalPlaneResolutionUnit"}, /* 0x9210 - - */ { 0xA211, "ImageNumber"}, { 0xA212, "SecurityClassification"}, { 0xA213, "ImageHistory"}, { 0xA214, "SubjectLocation"}, /* 0x9214 - - */ { 0xA215, "ExposureIndex"}, /* 0x9215 - - */ { 0xA216, "TIFF/EPStandardID"}, { 0xA217, "SensingMethod"}, /* 0x9217 - - */ { 0xA300, "FileSource"}, { 0xA301, "SceneType"}, { 0xA302, "CFAPattern"}, { 0xA401, "CustomRendered"}, { 0xA402, "ExposureMode"}, { 0xA403, "WhiteBalance"}, { 0xA404, "DigitalZoomRatio"}, { 0xA405, "FocalLengthIn35mmFilm"}, { 0xA406, "SceneCaptureType"}, { 0xA407, "GainControl"}, { 0xA408, "Contrast"}, { 0xA409, "Saturation"}, { 0xA40A, "Sharpness"}, { 0xA40B, "DeviceSettingDescription"}, { 0xA40C, "SubjectDistanceRange"}, { 0xA420, "ImageUniqueID"}, TAG_TABLE_END }; static const tag_info_array tag_table_GPS = { { 0x0000, "GPSVersion"}, { 0x0001, "GPSLatitudeRef"}, { 0x0002, "GPSLatitude"}, { 0x0003, "GPSLongitudeRef"}, { 0x0004, "GPSLongitude"}, { 0x0005, "GPSAltitudeRef"}, { 0x0006, "GPSAltitude"}, { 0x0007, "GPSTimeStamp"}, { 0x0008, "GPSSatellites"}, { 0x0009, "GPSStatus"}, { 0x000A, "GPSMeasureMode"}, { 0x000B, "GPSDOP"}, { 0x000C, "GPSSpeedRef"}, { 0x000D, "GPSSpeed"}, { 0x000E, "GPSTrackRef"}, { 0x000F, "GPSTrack"}, { 0x0010, "GPSImgDirectionRef"}, { 0x0011, "GPSImgDirection"}, { 0x0012, "GPSMapDatum"}, { 0x0013, "GPSDestLatitudeRef"}, { 0x0014, "GPSDestLatitude"}, { 0x0015, "GPSDestLongitudeRef"}, { 0x0016, "GPSDestLongitude"}, { 0x0017, "GPSDestBearingRef"}, { 0x0018, "GPSDestBearing"}, { 0x0019, "GPSDestDistanceRef"}, { 0x001A, "GPSDestDistance"}, { 0x001B, "GPSProcessingMode"}, { 0x001C, "GPSAreaInformation"}, { 0x001D, "GPSDateStamp"}, { 0x001E, "GPSDifferential"}, TAG_TABLE_END }; static const tag_info_array tag_table_IOP = { { 0x0001, "InterOperabilityIndex"}, /* should be 'R98' or 'THM' */ { 0x0002, "InterOperabilityVersion"}, { 0x1000, "RelatedFileFormat"}, { 0x1001, "RelatedImageWidth"}, { 0x1002, "RelatedImageHeight"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CANON = { { 0x0001, "ModeArray"}, /* guess */ { 0x0004, "ImageInfo"}, /* guess */ { 0x0006, "ImageType"}, { 0x0007, "FirmwareVersion"}, { 0x0008, "ImageNumber"}, { 0x0009, "OwnerName"}, { 0x000C, "Camera"}, { 0x000F, "CustomFunctions"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CASIO = { { 0x0001, "RecordingMode"}, { 0x0002, "Quality"}, { 0x0003, "FocusingMode"}, { 0x0004, "FlashMode"}, { 0x0005, "FlashIntensity"}, { 0x0006, "ObjectDistance"}, { 0x0007, "WhiteBalance"}, { 0x000A, "DigitalZoom"}, { 0x000B, "Sharpness"}, { 0x000C, "Contrast"}, { 0x000D, "Saturation"}, { 0x0014, "CCDSensitivity"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_FUJI = { { 0x0000, "Version"}, { 0x1000, "Quality"}, { 0x1001, "Sharpness"}, { 0x1002, "WhiteBalance"}, { 0x1003, "Color"}, { 0x1004, "Tone"}, { 0x1010, "FlashMode"}, { 0x1011, "FlashStrength"}, { 0x1020, "Macro"}, { 0x1021, "FocusMode"}, { 0x1030, "SlowSync"}, { 0x1031, "PictureMode"}, { 0x1100, "ContTake"}, { 0x1300, "BlurWarning"}, { 0x1301, "FocusWarning"}, { 0x1302, "AEWarning "}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON = { { 0x0003, "Quality"}, { 0x0004, "ColorMode"}, { 0x0005, "ImageAdjustment"}, { 0x0006, "CCDSensitivity"}, { 0x0007, "WhiteBalance"}, { 0x0008, "Focus"}, { 0x000a, "DigitalZoom"}, { 0x000b, "Converter"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON_990 = { { 0x0001, "Version"}, { 0x0002, "ISOSetting"}, { 0x0003, "ColorMode"}, { 0x0004, "Quality"}, { 0x0005, "WhiteBalance"}, { 0x0006, "ImageSharpening"}, { 0x0007, "FocusMode"}, { 0x0008, "FlashSetting"}, { 0x000F, "ISOSelection"}, { 0x0080, "ImageAdjustment"}, { 0x0082, "AuxiliaryLens"}, { 0x0085, "ManualFocusDistance"}, { 0x0086, "DigitalZoom"}, { 0x0088, "AFFocusPosition"}, { 0x0010, "DataDump"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_OLYMPUS = { { 0x0200, "SpecialMode"}, { 0x0201, "JPEGQuality"}, { 0x0202, "Macro"}, { 0x0204, "DigitalZoom"}, { 0x0207, "SoftwareRelease"}, { 0x0208, "PictureInfo"}, { 0x0209, "CameraId"}, { 0x0F00, "DataDump"}, TAG_TABLE_END }; typedef enum mn_byte_order_t { MN_ORDER_INTEL = 0, MN_ORDER_MOTOROLA = 1, MN_ORDER_NORMAL } mn_byte_order_t; typedef enum mn_offset_mode_t { MN_OFFSET_NORMAL, MN_OFFSET_MAKER, MN_OFFSET_GUESS } mn_offset_mode_t; typedef struct { tag_table_type tag_table; char *make; char *model; char *id_string; int id_string_len; int offset; mn_byte_order_t byte_order; mn_offset_mode_t offset_mode; } maker_note_type; static const maker_note_type maker_note_array[] = { { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_INTEL, MN_OFFSET_NORMAL}, /* { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL},*/ { tag_table_VND_CASIO, "CASIO", nullptr, nullptr, 0, 0, MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL}, { tag_table_VND_FUJI, "FUJIFILM", nullptr, "FUJIFILM\x0C\x00\x00\x00", 12, 12, MN_ORDER_INTEL, MN_OFFSET_MAKER}, { tag_table_VND_NIKON, "NIKON", nullptr, "Nikon\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_NIKON_990, "NIKON", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_OLYMPUS, "OLYMPUS OPTICAL CO.,LTD", nullptr, "OLYMP\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, }; /* Get headername for tag_num or nullptr if not defined */ static char * exif_get_tagname(int tag_num, char *ret, int len, tag_table_type tag_table) { int i, t; char tmp[32]; for (i = 0; (t = tag_table[i].Tag) != TAG_END_OF_LIST; i++) { if (t == tag_num) { if (ret && len) { string_copy(ret, tag_table[i].Desc, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return tag_table[i].Desc; } } if (ret && len) { snprintf(tmp, sizeof(tmp), "UndefinedTag:0x%04X", tag_num); string_copy(ret, tmp, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return ""; } #define MAX_IFD_NESTING_LEVEL 100 #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif typedef struct { int num; int den; } signed_rational; typedef struct { unsigned int num; unsigned int den; } unsigned_rational; typedef union _image_info_value { char *s; unsigned u; int i; float f; double d; signed_rational sr; unsigned_rational ur; union _image_info_value *list; } image_info_value; typedef struct { WORD tag; WORD format; DWORD length; DWORD dummy; /* value ptr of tiff directory entry */ char *name; image_info_value value; } image_info_data; typedef struct { int count; image_info_data *list; } image_info_list; #define SECTION_FILE 0 #define SECTION_COMPUTED 1 #define SECTION_ANY_TAG 2 #define SECTION_IFD0 3 #define SECTION_THUMBNAIL 4 #define SECTION_COMMENT 5 #define SECTION_APP0 6 #define SECTION_EXIF 7 #define SECTION_FPIX 8 #define SECTION_GPS 9 #define SECTION_INTEROP 10 #define SECTION_APP12 11 #define SECTION_WINXP 12 #define SECTION_MAKERNOTE 13 #define SECTION_COUNT 14 #define FOUND_FILE (1<<SECTION_FILE) #define FOUND_COMPUTED (1<<SECTION_COMPUTED) #define FOUND_ANY_TAG (1<<SECTION_ANY_TAG) #define FOUND_IFD0 (1<<SECTION_IFD0) #define FOUND_THUMBNAIL (1<<SECTION_THUMBNAIL) #define FOUND_COMMENT (1<<SECTION_COMMENT) #define FOUND_APP0 (1<<SECTION_APP0) #define FOUND_EXIF (1<<SECTION_EXIF) #define FOUND_FPIX (1<<SECTION_FPIX) #define FOUND_GPS (1<<SECTION_GPS) #define FOUND_INTEROP (1<<SECTION_INTEROP) #define FOUND_APP12 (1<<SECTION_APP12) #define FOUND_WINXP (1<<SECTION_WINXP) #define FOUND_MAKERNOTE (1<<SECTION_MAKERNOTE) const StaticString s_FILE("FILE"), s_COMPUTED("COMPUTED"), s_ANY_TAG("ANY_TAG"), s_IFD0("IFD0"), s_THUMBNAIL("THUMBNAIL"), s_COMMENT("COMMENT"), s_APP0("APP0"), s_EXIF("EXIF"), s_FPIX("FPIX"), s_GPS("GPS"), s_INTEROP("INTEROP"), s_APP12("APP12"), s_WINXP("WINXP"), s_MAKERNOTE("MAKERNOTE"); static String exif_get_sectionname(int section) { switch(section) { case SECTION_FILE: return s_FILE; case SECTION_COMPUTED: return s_COMPUTED; case SECTION_ANY_TAG: return s_ANY_TAG; case SECTION_IFD0: return s_IFD0; case SECTION_THUMBNAIL: return s_THUMBNAIL; case SECTION_COMMENT: return s_COMMENT; case SECTION_APP0: return s_APP0; case SECTION_EXIF: return s_EXIF; case SECTION_FPIX: return s_FPIX; case SECTION_GPS: return s_GPS; case SECTION_INTEROP: return s_INTEROP; case SECTION_APP12: return s_APP12; case SECTION_WINXP: return s_WINXP; case SECTION_MAKERNOTE: return s_MAKERNOTE; } return empty_string(); } static tag_table_type exif_get_tag_table(int section) { switch(section) { case SECTION_FILE: return &tag_table_IFD[0]; case SECTION_COMPUTED: return &tag_table_IFD[0]; case SECTION_ANY_TAG: return &tag_table_IFD[0]; case SECTION_IFD0: return &tag_table_IFD[0]; case SECTION_THUMBNAIL: return &tag_table_IFD[0]; case SECTION_COMMENT: return &tag_table_IFD[0]; case SECTION_APP0: return &tag_table_IFD[0]; case SECTION_EXIF: return &tag_table_IFD[0]; case SECTION_FPIX: return &tag_table_IFD[0]; case SECTION_GPS: return &tag_table_GPS[0]; case SECTION_INTEROP: return &tag_table_IOP[0]; case SECTION_APP12: return &tag_table_IFD[0]; case SECTION_WINXP: return &tag_table_IFD[0]; } return &tag_table_IFD[0]; } /* Return list of sectionnames specified by sectionlist. Return value must be freed */ static char *exif_get_sectionlist(int sectionlist) { int i, len, ml = 0; char *sections; for(i=0; i<SECTION_COUNT; i++) { ml += exif_get_sectionname(i).size() + 2; } sections = (char *)IM_MALLOC(ml + 1); CHECK_ALLOC_R(sections, ml + 1, nullptr); sections[0] = '\0'; len = 0; for(i=0; i<SECTION_COUNT; i++) { if (sectionlist&(1<<i)) { snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i).c_str()); len = strlen(sections); } } if (len>2) { sections[len-2] = '\0'; } return sections; } /* This structure stores Exif header image elements in a simple manner Used to store camera data as extracted from the various ways that it can be stored in a nexif header */ typedef struct { int type; size_t size; unsigned char *data; } file_section; typedef struct { int count; file_section *list; } file_section_list; typedef struct { image_filetype filetype; size_t width, height; size_t size; size_t offset; char *data; } thumbnail_data; typedef struct { char *value; size_t size; int tag; } xp_field_type; typedef struct { int count; xp_field_type *list; } xp_field_list; /* This structure is used to store a section of a Jpeg file. */ typedef struct { req::ptr<File> infile; String FileName; time_t FileDateTime; size_t FileSize; image_filetype FileType; int Height, Width; int IsColor; char *make; char *model; float ApertureFNumber; float ExposureTime; double FocalplaneUnits; float CCDWidth; double FocalplaneXRes; size_t ExifImageWidth; float FocalLength; float Distance; int motorola_intel; /* 1 Motorola; 0 Intel */ char *UserComment; int UserCommentLength; char *UserCommentEncoding; char *encode_unicode; char *decode_unicode_be; char *decode_unicode_le; char *encode_jis; char *decode_jis_be; char *decode_jis_le; /* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */ char *Copyright; char *CopyrightPhotographer; char *CopyrightEditor; xp_field_list xp_fields; thumbnail_data Thumbnail; /* other */ int sections_found; /* FOUND_<marker> */ image_info_list info_list[SECTION_COUNT]; /* for parsing */ bool read_thumbnail; bool read_all; int ifd_nesting_level; /* internal */ file_section_list file; } image_info_type; typedef struct { int bits_per_sample; size_t width; size_t height; int num_components; } jpeg_sof_info; /* forward declarations */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index); static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table); /* Add a file_section to image_info returns the used block or -1. if size>0 and data == nullptr buffer of size is allocated */ static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, unsigned char *data) { file_section *tmp; int count = ImageInfo->file.count; size_t realloc_size = (count+1) * sizeof(file_section); tmp = (file_section *)IM_REALLOC(ImageInfo->file.list, realloc_size); CHECK_ALLOC_R(tmp, realloc_size, -1); ImageInfo->file.list = tmp; ImageInfo->file.list[count].type = 0xFFFF; ImageInfo->file.list[count].data = nullptr; ImageInfo->file.list[count].size = 0; ImageInfo->file.count = count+1; if (!size) { data = nullptr; } else if (data == nullptr) { data = (unsigned char *)IM_MALLOC(size); if (data == nullptr) IM_FREE(tmp); CHECK_ALLOC_R(data, size, -1); } ImageInfo->file.list[count].type = type; ImageInfo->file.list[count].data = data; ImageInfo->file.list[count].size = size; return count; } /* get length of string if buffer if less than buffer size or buffer size */ static size_t php_strnlen(char* str, size_t maxlen) { size_t len = 0; if (str && maxlen && *str) { do { len++; } while (--maxlen && *(++str)); } return len; } /* Add a value to image_info */ static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data*) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; PHP_STRDUP(info_data->name, name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen((char*)value, length); // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { /* do not recompute length here */ // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = (image_info_value*)IM_CALLOC(length, sizeof(image_info_value)); CHECK_ALLOC(info_value->list, sizeof(image_info_value)); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + get_php_tiff_bytes_per_format(format)) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: info_value->f = *(float *)value; case TAG_FMT_DOUBLE: info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a tag from IFD to image_info */ static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value) { exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel); } /* Evaluate number, be it int, rational, or float from directory. */ static double exif_convert_any_format(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return (double)php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (double)php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return (signed short)php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (double)*(float *)value; case TAG_FMT_DOUBLE: return *(double *)value; } return 0; } /* Evaluate number, be it int, rational, or float from directory. */ static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den); } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (size_t)*(float *)value; case TAG_FMT_DOUBLE: return (size_t)*(double *)value; } return 0; } /* Get 16 bits motorola order (always) for jpeg header stuff. */ static int php_jpg_get16(void *value) { return (((unsigned char *)value)[0] << 8) | ((unsigned char *)value)[1]; } /* Write 16 bit unsigned value to data */ static void php_ifd_set16u(char *data, unsigned int value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF00) >> 8; data[1] = (value & 0x00FF); } else { data[1] = (value & 0xFF00) >> 8; data[0] = (value & 0x00FF); } } /* Convert a 32 bit unsigned value from file's native byte order */ static void php_ifd_set32u(char *data, size_t value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF000000) >> 24; data[1] = (value & 0x00FF0000) >> 16; data[2] = (value & 0x0000FF00) >> 8; data[3] = (value & 0x000000FF); } else { data[3] = (value & 0xFF000000) >> 24; data[2] = (value & 0x00FF0000) >> 16; data[1] = (value & 0x0000FF00) >> 8; data[0] = (value & 0x000000FF); } } /* Create a value for an ifd from an info_data pointer */ static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel) { size_t byte_count; char *value_ptr, *data_ptr; size_t i; image_info_value *info_value; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; size_t malloc_size = byte_count > 4 ? byte_count : 4; value_ptr = (char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(value_ptr, malloc_size, nullptr); memset(value_ptr, 0, 4); if (!info_data->length) { return value_ptr; } if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE))) { memmove(value_ptr, info_data->value.s, byte_count); return value_ptr; } else if (info_data->format == TAG_FMT_BYTE) { *value_ptr = info_data->value.u; return value_ptr; } else if (info_data->format == TAG_FMT_SBYTE) { *value_ptr = info_data->value.i; return value_ptr; } else { data_ptr = value_ptr; for(i=0; i<info_data->length; i++) { if (info_data->length==1) { info_value = &info_data->value; } else { info_value = &info_data->value.list[i]; } switch(info_data->format) { case TAG_FMT_USHORT: php_ifd_set16u(data_ptr, info_value->u, motorola_intel); data_ptr += 2; break; case TAG_FMT_ULONG: php_ifd_set32u(data_ptr, info_value->u, motorola_intel); data_ptr += 4; break; case TAG_FMT_SSHORT: php_ifd_set16u(data_ptr, info_value->i, motorola_intel); data_ptr += 2; break; case TAG_FMT_SLONG: php_ifd_set32u(data_ptr, info_value->i, motorola_intel); data_ptr += 4; break; case TAG_FMT_URATIONAL: php_ifd_set32u(data_ptr, info_value->sr.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SRATIONAL: php_ifd_set32u(data_ptr, info_value->ur.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SINGLE: memmove(data_ptr, &info_value->f, 4); data_ptr += 4; break; case TAG_FMT_DOUBLE: memmove(data_ptr, &info_value->d, 8); data_ptr += 8; break; } } } return value_ptr; } /* Process a COM marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ static void exif_process_COM(image_info_type *image_info, char *value, size_t length) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2); } /* Check and build thumbnail */ static void exif_thumbnail_build(image_info_type *ImageInfo) { size_t new_size, new_move, new_value; char *new_data; void *value_ptr; int i, byte_count; image_info_list *info_list; image_info_data *info_data; if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) { return; /* ignore this call */ } switch(ImageInfo->Thumbnail.filetype) { default: case IMAGE_FILETYPE_JPEG: /* done */ break; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: info_list = &ImageInfo->info_list[SECTION_THUMBNAIL]; new_size = 8 + 2 + info_list->count * 12 + 4; new_value= new_size; /* offset for ifd values outside ifd directory */ for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (byte_count > 4) { new_size += byte_count; } } new_move = new_size; new_data = (char *)IM_REALLOC(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size + new_size); CHECK_ALLOC(new_data, ImageInfo->Thumbnail.size + new_size); ImageInfo->Thumbnail.data = new_data; memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size); ImageInfo->Thumbnail.size += new_size; /* fill in data */ if (ImageInfo->motorola_intel) { memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8); } else { memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8); } new_data += 8; php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel); new_data += 2; for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, TAG_FMT_ULONG, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, 1, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 8, new_move, ImageInfo->motorola_intel); } else { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel); value_ptr = exif_ifd_make_value(info_data, ImageInfo->motorola_intel); if (byte_count <= 4) { memmove(new_data+8, value_ptr, 4); } else { php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel); memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count); new_value += byte_count; } if (value_ptr) IM_FREE(value_ptr); } new_data += 12; } memset(new_data, 0, 4); /* next ifd pointer */ break; } } /* Grab the thumbnail, corrected */ static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length) { if (ImageInfo->Thumbnail.data) { raise_warning("Multiple possible thumbnails"); return; /* Should not happen */ } if (!ImageInfo->read_thumbnail) { return; /* ignore this call */ } /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */ if (ImageInfo->Thumbnail.size >= 65536 || ImageInfo->Thumbnail.size <= 0 || ImageInfo->Thumbnail.offset <= 0) { raise_warning("Illegal thumbnail size/offset"); return; } /* Check to make sure we are not going to go past the ExifLength */ if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) { raise_warning("Thumbnail goes IFD boundary or end of file reached"); return; } PHP_STRNDUP(ImageInfo->Thumbnail.data, offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size); exif_thumbnail_build(ImageInfo); } /* Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */ static int exif_process_undefined(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ if (byte_count) { PHP_STRNDUP((*result), value, byte_count); /* NULL @ byte_count!!! */ if (*result) return byte_count+1; } return 0; } /* Copy a string in Exif header to a character string returns length of allocated buffer if any. */ #if !EXIF_USE_MBSTRING static int exif_process_string_raw(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ *result = 0; if (byte_count) { (*result) = (char*)IM_MALLOC(byte_count + 1); CHECK_ALLOC_R((*result), byte_count + 1, 0); memcpy(*result, value, byte_count); (*result)[byte_count] = '\0'; return byte_count+1; } return 0; } #endif /* * Copy a string in Exif header to a character string and return length of allocated buffer if any. In contrast to exif_process_string this function does always return a string buffer */ static int exif_process_string(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we cannot use strlen to * determin length of string and we cannot use strlcpy with len=byte_count+1 * because then we might get into an EXCEPTION if we exceed an allocated * memory page...so we use php_strnlen in conjunction with memcpy and add * the NUL char. */ if ((byte_count=php_strnlen(value, byte_count)) > 0) { return exif_process_undefined(result, value, byte_count); } PHP_STRNDUP((*result), "", 1); /* force empty string */ if (*result) return byte_count+1; return 0; } /* Process UserComment in IFD. */ static int exif_process_user_comment(image_info_type* /*ImageInfo*/, char** pszInfoPtr, char** pszEncoding, char* szValuePtr, int ByteCount) { int a; #if EXIF_USE_MBSTRING char *decode; size_t len; #endif *pszEncoding = nullptr; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, decode, &len); return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user */ PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING if (ImageInfo->motorola_intel) { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_be, &len); } else { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_le, &len); } return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ PHP_STRDUP(*pszEncoding, "UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount); return strlen(*pszInfoPtr); } /* Process unicode field in IFD. */ static int exif_process_unicode(image_info_type* /*ImageInfo*/, xp_field_type* xp_field, int tag, char* szValuePtr, int ByteCount) { xp_field->tag = tag; xp_field->value = nullptr; /* Copy the comment */ #if EXIF_USE_MBSTRING xp_field->value = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, ImageInfo->decode_unicode_le, &xp_field->size); return xp_field->size; #else xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount); return xp_field->size; #endif } /* Process nested IFDs directories in Maker Note. */ static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; char *value_end = value_ptr + value_len; for (unsigned int i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) return 0; maker_note = maker_note_array+i; if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) { continue; } if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) { continue; } if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, (maker_note->id_string_len < value_len ? maker_note->id_string_len : value_len))) { continue; } break; } if (maker_note->offset >= value_len) return 0; dir_start = value_ptr + maker_note->offset; ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } if (value_end - dir_start < 2) return 0; NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: if (value_end - (dir_start+10) < 4) return 0; offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); if (offset_diff < 0 || offset_diff >= value_len) return 0; offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { raise_warning("Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, value_end, IFDlength, displacement, section_index, 0, maker_note->tag_table)) { return 0; } } ImageInfo->motorola_intel = old_motorola_intel; return 0; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=nullptr; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { raise_warning("corrupt EXIF header: maximum directory " "nesting level reached"); return 0; } ImageInfo->ifd_nesting_level++; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ raise_warning("Process tag(x%04X=%s): Illegal format code 0x%04X, " "suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { raise_warning("Process tag(x%04X=%s): Illegal components(%d)", tag, exif_get_tagname(tag, tagname, -12, tag_table), components); return 1; } byte_count_signed = (int64_t)components * get_php_tiff_bytes_per_format(format); if (byte_count_signed < 0 || (byte_count_signed > 2147483648)) { raise_warning("Process tag(x%04X=%s): Illegal byte_count(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table), byte_count_signed); return 1; // ignore that field, but don't abort parsing } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* // It is important to check for IMAGE_FILETYPE_TIFF // JPEG does not use absolute pointers instead // its pointers are relative to the start // of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX < %04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, dir_entry-offset_base); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX + x%04lX = x%04lX > x%04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, byte_count, offset_val+byte_count, IFDlength); } return 0; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = (char *)IM_MALLOC(byte_count); CHECK_ALLOC_R(value_ptr, byte_count, 0); outside = value_ptr; } else { /* // in most cases we only access a small range so // it is faster to use a static buffer there // BUT it offers also the possibility to have // pointers read without the need to free them // explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = ImageInfo->infile->tell(); ImageInfo->infile->seek(displacement+offset_val, SEEK_SET); fgot = ImageInfo->infile->tell(); if (fgot!=displacement+offset_val) { if (outside) IM_FREE(outside); raise_warning("Wrong file pointer: 0x%08lX != 0x%08lX", fgot, displacement+offset_val); return 0; } String str = ImageInfo->infile->read(byte_count); fgot = str.length(); memcpy(value_ptr, str.c_str(), fgot); ImageInfo->infile->seek(fpos, SEEK_SET); if (fgot<byte_count) { if (outside) IM_FREE(outside); raise_warning("Unexpected end of file reached"); return 0; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ PHP_STRDUP(ImageInfo->CopyrightPhotographer, value_ptr); PHP_STRNDUP( ImageInfo->CopyrightEditor, value_ptr + length + 1, byte_count - length - 1 ); if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); php_vspprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, ImageInfo->CopyrightEditor); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { PHP_STRNDUP(ImageInfo->Copyright, value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: { size_t realloc_size = (ImageInfo->xp_fields.count+1) * sizeof(xp_field_type); tmp_xp = (xp_field_type*) IM_REALLOC(ImageInfo->xp_fields.list, realloc_size); if (!tmp_xp) { if (outside) IM_FREE(outside); } CHECK_ALLOC_R(tmp_xp, realloc_size, 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count); break; } case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ raise_notice("Skip SUB IFD"); } break; case TAG_MAKE: PHP_STRNDUP(ImageInfo->make, value_ptr, byte_count); break; case TAG_MODEL: PHP_STRNDUP(ImageInfo->model, value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } CHECK_BUFFER_R(value_ptr, end, 4, 0); Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { raise_warning("Illegal IFD Pointer"); return 0; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, end, IFDlength, displacement, sub_section_index)) { return 0; } } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table), tag, format, components, value_ptr); if (outside) IM_FREE(outside); return 1; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index) { int de; int NumDirEntries; int NextDirOffset; ImageInfo->sections_found |= FOUND_IFD0; CHECK_BUFFER_R(dir_start, end, 2, 0); NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { raise_warning("Illegal IFD size: x%04X + 2 + x%04X*12 = x%04X > x%04lX", (int)((size_t)dir_start+2-(size_t)offset_base), NumDirEntries, (int)((size_t)dir_start+2+ NumDirEntries*12-(size_t)offset_base), IFDlength); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, end, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index))) { return 0; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return true; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) * to the thumbnail */ CHECK_BUFFER_R(dir_start+2+12*de, end, 4, 0); NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ if (offset_base + NextDirOffset < offset_base || offset_base + NextDirOffset > offset_base+IFDlength) { raise_warning("Illegal IFD offset"); return 0; } /* That is the IFD for the first thumbnail */ if (exif_process_IFD_in_JPEG(ImageInfo, offset_base + NextDirOffset, offset_base, end, IFDlength, displacement, SECTION_THUMBNAIL)) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength); } return 1; } else { return 0; } } return 1; } /* Process a TIFF header in a JPEG file */ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { char *end = CharBuf + length; unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ CHECK_BUFFER(CharBuf, end, 2); if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { raise_warning("Invalid TIFF a lignment marker"); return; } /* Check the next two values for correctness. */ CHECK_BUFFER(CharBuf+4, end, 4); exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { raise_warning("Invalid TIFF start (1)"); return; } if (offset_of_ifd > length) { raise_warning("Invalid IFD start"); return; } ImageInfo->sections_found |= FOUND_IFD0; /* First directory starts at offset 8. Offsets starts at 0. */ exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, end, length/* -14*/, displacement, SECTION_IFD0); /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } /* Process an JPEG APP1 block marker Describes all the drivel that most digital cameras include... */ static void exif_process_APP1(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { /* Check the APP1 for Exif Identifier Code */ char *end = CharBuf + length; static const unsigned char ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00}; CHECK_BUFFER(CharBuf+2, end, 6); if (length <= 8 || memcmp(CharBuf+2, ExifHeader, 6)) { raise_warning("Incorrect APP1 Exif Identifier Code"); return; } exif_process_TIFF_in_JPEG(ImageInfo, CharBuf + 8, length - 8, displacement+8); } /* Process an JPEG APP12 block marker used by OLYMPUS */ static void exif_process_APP12(image_info_type *ImageInfo, char *buffer, size_t length) { size_t l1, l2=0; if ((l1 = php_strnlen(buffer+2, length-2)) > 0) { exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company", TAG_NONE, TAG_FMT_STRING, l1, buffer+2); if (length > 2+l1+1) { l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1); exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info", TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1); } } } /* Process a SOFn marker. This is useful for the image dimensions */ static void exif_process_SOFn(unsigned char* Data, int /*marker*/, jpeg_sof_info* result) { result->bits_per_sample = Data[2]; result->height = php_jpg_get16(Data+3); result->width = php_jpg_get16(Data+5); result->num_components = Data[7]; } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_JPEG_header(image_info_type *ImageInfo) { int section, sn; int marker = 0, last_marker = M_PSEUDO, comment_correction=1; int ll, lh; unsigned char *Data; size_t fpos, size, got, itemlen; jpeg_sof_info sof_info; for(section=0;;section++) { // get marker byte, swallowing possible padding // some software does not count the length bytes of COM section // one company doing so is very much envolved in JPEG... // so we accept too if (last_marker==M_COM && comment_correction) { comment_correction = 2; } do { if ((marker = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if (last_marker==M_COM && comment_correction>0) { if (marker!=0xFF) { marker = 0xff; comment_correction--; } else { last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */ } } } while (marker == 0xff); if (last_marker==M_COM && !comment_correction) { raise_notice("Image has corrupt COM section: some software set " "wrong length information"); } if (last_marker==M_COM && comment_correction) return M_EOI; /* ah illegal: char after COM section not 0xFF */ fpos = ImageInfo->infile->tell(); if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. raise_warning("To many padding bytes"); return 0; } /* Read the length of the section. */ if ((lh = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if ((ll = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } itemlen = (lh << 8) | ll; if (itemlen < 2) { raise_warning("File structure corrupted"); return 0; } sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; /* Store first two pre-read bytes. */ Data[0] = (unsigned char)lh; Data[1] = (unsigned char)ll; String str = ImageInfo->infile->read(itemlen-2); got = str.length(); if (got != itemlen-2) { raise_warning("Error reading from file: " "got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)", got, got, itemlen-2, itemlen-2); return 0; } memcpy(Data+2, str.c_str(), got); switch(marker) { case M_SOS: /* stop before hitting compressed data */ // If reading entire image is requested, read the rest of the data. if (ImageInfo->read_all) { /* Determine how much file is left. */ fpos = ImageInfo->infile->tell(); size = ImageInfo->FileSize - fpos; sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; str = ImageInfo->infile->read(size); got = str.length(); if (got != size) { raise_warning("Unexpected end of file reached"); return 0; } memcpy(Data, str.c_str(), got); } return 1; case M_EOI: /* in case it's a tables-only JPEG stream */ raise_warning("No image in jpeg!"); return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0; case M_COM: /* Comment section */ exif_process_COM(ImageInfo, (char *)Data, itemlen); break; case M_EXIF: if (!(ImageInfo->sections_found&FOUND_IFD0)) { /*ImageInfo->sections_found |= FOUND_EXIF;*/ /* Seen files from some 'U-lead' software with Vivitar scanner that uses marker 31 later in the file (no clue what for!) */ exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos); } break; case M_APP12: exif_process_APP12(ImageInfo, (char *)Data, itemlen); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if ((itemlen - 2) < 6) { return 0; } exif_process_SOFn(Data, marker, &sof_info); ImageInfo->Width = sof_info.width; ImageInfo->Height = sof_info.height; if (sof_info.num_components == 3) { ImageInfo->IsColor = 1; } else { ImageInfo->IsColor = 0; } break; default: /* skip any other marker silently. */ break; } /* keep track of last marker */ last_marker = marker; } return 1; } /* Reallocate a file section returns 0 on success and -1 on failure */ static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size) { void *tmp; /* This is not a malloc/realloc check. It is a plausibility check for the * function parameters (requirements engineering). */ if (section_index >= ImageInfo->file.count) { raise_warning("Illegal reallocating of undefined file section"); return -1; } tmp = IM_REALLOC(ImageInfo->file.list[section_index].data, size); CHECK_ALLOC_R(tmp, size, -1); ImageInfo->file.list[section_index].data = (unsigned char *)tmp; ImageInfo->file.list[section_index].size = size; return 0; } /* Parse the TIFF header; */ static int exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index) { int i, sn, num_entries, sub_section_index = 0; unsigned char *dir_entry; char tagname[64]; size_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot; int entry_tag , entry_type; tag_table_type tag_table = exif_get_tag_table(section_index); if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { return 0; } if (ImageInfo->FileSize >= dir_offset+2) { sn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, nullptr); if (sn == -1) return 0; /* we do not know the order of sections */ ImageInfo->infile->seek(dir_offset, SEEK_SET); String snData = ImageInfo->infile->read(2); memcpy(ImageInfo->file.list[sn].data, snData.c_str(), 2); num_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel); dir_size = 2/*num dir entries*/ + 12/*length of entry*/*num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; if (ImageInfo->FileSize >= dir_offset+dir_size) { if (exif_file_sections_realloc(ImageInfo, sn, dir_size)) { return 0; } snData = ImageInfo->infile->read(dir_size-2); memcpy(ImageInfo->file.list[sn].data+2, snData.c_str(), dir_size-2); next_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel); /* now we have the directory we can look how long it should be */ ifd_size = dir_size; char *end = (char*)ImageInfo->file.list[sn].data + dir_size; for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_type > NUM_FORMATS) { raise_notice("Read from TIFF: tag(0x%04X,%12s): " "Illegal format code 0x%04X, switching to BYTE", entry_tag, exif_get_tagname(entry_tag, tagname, -12, tag_table), entry_type); /* Since this is repeated in exif_process_IFD_TAG make it a notice here and make it a warning in the exif_process_IFD_TAG which is called elsewhere. */ entry_type = TAG_FMT_BYTE; } entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * get_php_tiff_bytes_per_format(entry_type); if (entry_length <= 4) { switch(entry_type) { case TAG_FMT_USHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SSHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_ULONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SLONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel); break; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Height = entry_value; break; case TAG_PHOTOMETRIC_INTERPRETATION: switch (entry_value) { case PMI_BLACK_IS_ZERO: case PMI_WHITE_IS_ZERO: case PMI_TRANSPARENCY_MASK: ImageInfo->IsColor = 0; break; case PMI_RGB: case PMI_PALETTE_COLOR: case PMI_SEPARATED: case PMI_YCBCR: case PMI_CIELAB: ImageInfo->IsColor = 1; break; } break; } } else { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* if entry needs expading ifd cache and entry is at end of current ifd cache. */ /* otherwise there may be huge holes between two entries */ if (entry_offset + entry_length > dir_offset + ifd_size && entry_offset == dir_offset + ifd_size) { ifd_size = entry_offset + entry_length - dir_offset; } } } if (ImageInfo->FileSize >= dir_offset + ImageInfo->file.list[sn].size) { if (ifd_size > dir_size) { if (dir_offset + ifd_size > ImageInfo->FileSize) { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX + x%04lX)", ImageInfo->FileSize, dir_offset, ifd_size); return 0; } if (exif_file_sections_realloc(ImageInfo, sn, ifd_size)) { return 0; } else { end = (char*)ImageInfo->file.list[sn].data + dir_size; } /* read values not stored in directory itself */ snData = ImageInfo->infile->read(ifd_size-dir_size); memcpy(ImageInfo->file.list[sn].data+dir_size, snData.c_str(), ifd_size-dir_size); } /* now process the tags */ for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+2, end, 2, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_tag == TAG_EXIF_IFD_POINTER || entry_tag == TAG_INTEROP_IFD_POINTER || entry_tag == TAG_GPS_IFD_POINTER || entry_tag == TAG_SUB_IFD) { switch(entry_tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; case TAG_SUB_IFD: ImageInfo->sections_found |= FOUND_THUMBNAIL; sub_section_index = SECTION_THUMBNAIL; break; } CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index); if (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { if (!ImageInfo->Thumbnail.data) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } } } else { if (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry, (char*)(ImageInfo->file.list[sn].data-dir_offset), (char*)(ImageInfo->file.list[sn].data + ifd_size), ifd_size, 0, section_index, 0, tag_table)) { return 0; } } } /* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */ if (next_offset && section_index != SECTION_THUMBNAIL) { /* this should be a thumbnail IFD */ /* the thumbnail itself is stored at Tag=StripOffsets */ ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL); if (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); CHECK_ALLOC_R(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size, 0); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } return 1; } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX)", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than size " "of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+dir_size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "start of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+2); return 0; } } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_FILE_header(image_info_type *ImageInfo) { unsigned char *file_header; int ret = 0; ImageInfo->FileType = IMAGE_FILETYPE_UNKNOWN; if (ImageInfo->FileSize >= 2) { ImageInfo->infile->seek(0, SEEK_SET); String fileHeader = ImageInfo->infile->read(2); if (fileHeader.length() != 2) { return 0; } file_header = (unsigned char *)fileHeader.c_str(); if ((file_header[0]==0xff) && (file_header[1]==M_SOI)) { ImageInfo->FileType = IMAGE_FILETYPE_JPEG; if (exif_scan_JPEG_header(ImageInfo)) { ret = 1; } else { raise_warning("Invalid JPEG file"); } } else if (ImageInfo->FileSize >= 8) { String str = ImageInfo->infile->read(6); if (str.length() != 6) { return 0; } fileHeader += str; file_header = (unsigned char *)fileHeader.c_str(); if (!memcmp(file_header, "II\x2A\x00", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_II; ImageInfo->motorola_intel = 0; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else if (!memcmp(file_header, "MM\x00\x2a", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_MM; ImageInfo->motorola_intel = 1; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else { raise_warning("File not supported"); return 0; } } } else { raise_warning("File too small (%lu)", ImageInfo->FileSize); } return ret; } static int exif_read_file(image_info_type *ImageInfo, String FileName, bool read_thumbnail, bool read_all) { struct stat st; /* Start with an empty image information structure. */ memset(ImageInfo, 0, sizeof(*ImageInfo)); ImageInfo->motorola_intel = -1; /* flag as unknown */ ImageInfo->infile = File::Open(FileName, "rb"); if (!ImageInfo->infile) { raise_warning("Unable to open file %s", FileName.c_str()); return 0; } auto plain_file = dyn_cast<PlainFile>(ImageInfo->infile); if (plain_file) { if (stat(FileName.c_str(), &st) >= 0) { if ((st.st_mode & S_IFMT) != S_IFREG) { raise_warning("Not a file"); return 0; } } /* Store file date/time. */ ImageInfo->FileDateTime = st.st_mtime; ImageInfo->FileSize = st.st_size; } else { if (!ImageInfo->FileSize) { ImageInfo->infile->seek(0, SEEK_END); ImageInfo->FileSize = ImageInfo->infile->tell(); ImageInfo->infile->seek(0, SEEK_SET); } } ImageInfo->FileName = HHVM_FN(basename)(FileName); ImageInfo->read_thumbnail = read_thumbnail; ImageInfo->read_all = read_all; ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_UNKNOWN; PHP_STRDUP(ImageInfo->encode_unicode, "ISO-8859-15"); PHP_STRDUP(ImageInfo->decode_unicode_be, "UCS-2BE"); PHP_STRDUP(ImageInfo->decode_unicode_le, "UCS-2LE"); PHP_STRDUP(ImageInfo->encode_jis, ""); PHP_STRDUP(ImageInfo->decode_jis_be, "JIS"); PHP_STRDUP(ImageInfo->decode_jis_le, "JIS"); ImageInfo->ifd_nesting_level = 0; /* Scan the JPEG headers. */ auto ret = exif_scan_FILE_header(ImageInfo); ImageInfo->infile->close(); return ret; } /* Free memory allocated for image_info */ static void exif_iif_free(image_info_type *image_info, int section_index) { int i; void *f; /* faster */ if (image_info->info_list[section_index].count) { for (i=0; i < image_info->info_list[section_index].count; i++) { if ((f=image_info->info_list[section_index].list[i].name) != nullptr) { IM_FREE(f); } switch(image_info->info_list[section_index].list[i].format) { case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (image_info->info_list[section_index].list[i].length<1) break; default: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: if ((f=image_info->info_list[section_index].list[i].value.s) != nullptr) { IM_FREE(f); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: /* nothing to do here */ if (image_info->info_list[section_index].list[i].length > 1) { if ((f=image_info->info_list[section_index].list[i].value.list) != nullptr) { IM_FREE(f); } } break; } } } if (image_info->info_list[section_index].list) { IM_FREE(image_info->info_list[section_index].list); } } /* Discard all file_sections in ImageInfo */ static int exif_file_sections_free(image_info_type *ImageInfo) { int i; if (ImageInfo->file.count) { for (i=0; i<ImageInfo->file.count; i++) { if (ImageInfo->file.list[i].data) { IM_FREE(ImageInfo->file.list[i].data); } } } if (ImageInfo->file.list) IM_FREE(ImageInfo->file.list); ImageInfo->file.count = 0; return 1; } /* Discard data scanned by exif_read_file. */ static int exif_discard_imageinfo(image_info_type *ImageInfo) { int i; if (ImageInfo->UserComment) IM_FREE(ImageInfo->UserComment); if (ImageInfo->UserCommentEncoding) { IM_FREE(ImageInfo->UserCommentEncoding); } if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); if (ImageInfo->CopyrightPhotographer) { IM_FREE(ImageInfo->CopyrightPhotographer); } if (ImageInfo->CopyrightEditor) IM_FREE(ImageInfo->CopyrightEditor); if (ImageInfo->Thumbnail.data) IM_FREE(ImageInfo->Thumbnail.data); if (ImageInfo->encode_unicode) IM_FREE(ImageInfo->encode_unicode); if (ImageInfo->decode_unicode_be) { IM_FREE(ImageInfo->decode_unicode_be); } if (ImageInfo->decode_unicode_le) { IM_FREE(ImageInfo->decode_unicode_le); } if (ImageInfo->encode_jis) IM_FREE(ImageInfo->encode_jis); if (ImageInfo->decode_jis_be) IM_FREE(ImageInfo->decode_jis_be); if (ImageInfo->decode_jis_le) IM_FREE(ImageInfo->decode_jis_le); if (ImageInfo->make) IM_FREE(ImageInfo->make); if (ImageInfo->model) IM_FREE(ImageInfo->model); for (i=0; i<ImageInfo->xp_fields.count; i++) { if (ImageInfo->xp_fields.list[i].value) { IM_FREE(ImageInfo->xp_fields.list[i].value); } } if (ImageInfo->xp_fields.list) IM_FREE(ImageInfo->xp_fields.list); for (i=0; i<SECTION_COUNT; i++) { exif_iif_free(ImageInfo, i); } exif_file_sections_free(ImageInfo); memset(ImageInfo, 0, sizeof(*ImageInfo)); return 1; } /* Add an int value to image_info */ static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value) { image_info_data *info_data; image_info_data *list; size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_SLONG; info_data->length = 1; PHP_STRDUP(info_data->name, name); info_data->value.i = value; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_STRING; info_data->length = 1; PHP_STRDUP(info_data->name, name); // TODO // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, strlen(value), nullptr, 0); // } else { PHP_STRDUP(info_data->value.s, value); image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* Add a format string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name, char *value, ...) { va_list arglist; va_start(arglist, value); if (value) { char *tmp = 0; php_vspprintf_ap(&tmp, 0, value, arglist); exif_iif_add_str(image_info, section_index, name, tmp); if (tmp) IM_FREE(tmp); } va_end(arglist); } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_UNDEFINED; info_data->length = length; PHP_STRDUP(info_data->name, name); // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, length, &length, 0); // info_data->length = length; // } else { info_data->value.s = (char *)IM_MALLOC(length + 1); if (!info_data->value.s) info_data->length = 0; CHECK_ALLOC(info_data->value.s, length + 1); memcpy(info_data->value.s, value, length); info_data->value.s[length] = 0; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* scan JPEG in thumbnail (memory) */ static int exif_scan_thumbnail(image_info_type *ImageInfo) { unsigned char c, *data = (unsigned char*)ImageInfo->Thumbnail.data; int n, marker; size_t length=2, pos=0; jpeg_sof_info sof_info; if (!data) { return 0; /* nothing to do here */ } if (memcmp(data, "\xFF\xD8\xFF", 3)) { if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) { raise_warning("Thumbnail is not a JPEG image"); } return 0; } for (;;) { pos += length; if (pos>=ImageInfo->Thumbnail.size) return 0; c = data[pos++]; if (pos>=ImageInfo->Thumbnail.size) return 0; if (c != 0xFF) { return 0; } n = 8; while ((c = data[pos++]) == 0xFF && n--) { if (pos+3>=ImageInfo->Thumbnail.size) return 0; /* +3 = pos++ of next check when reaching marker + 2 bytes for length */ } if (c == 0xFF) return 0; marker = c; length = php_jpg_get16(data+pos); if (pos+length>=ImageInfo->Thumbnail.size) { return 0; } switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: /* handle SOFn block */ exif_process_SOFn(data+pos, marker, &sof_info); ImageInfo->Thumbnail.height = sof_info.height; ImageInfo->Thumbnail.width = sof_info.width; return 1; case M_SOS: case M_EOI: raise_warning("Could not compute size of thumbnail"); return 0; break; default: /* just skip */ break; } } raise_warning("Could not compute size of thumbnail"); return 0; } /* Add image_info to associative array value. */ static void add_assoc_image_info(Array &value, bool sub_array, image_info_type *image_info, int section_index) { char buffer[64], *val, *name, uname[64]; int i, ap, l, b, idx=0, unknown=0; image_info_value *info_value; image_info_data *info_data; Array tmp; Array *tmpi = &tmp; Array array; if (image_info->info_list[section_index].count) { if (!sub_array) { tmpi = &value; } for(i=0; i<image_info->info_list[section_index].count; i++) { info_data = &image_info->info_list[section_index].list[i]; info_value = &info_data->value; if (!(name = info_data->name)) { snprintf(uname, sizeof(uname), "%d", unknown++); name = uname; } if (info_data->length==0) { tmpi->set(String(name, CopyString), uninit_null()); } else { switch (info_data->format) { default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ case TAG_FMT_BYTE: case TAG_FMT_SBYTE: case TAG_FMT_UNDEFINED: if (!info_value->s) { tmpi->set(String(name, CopyString), ""); } else { tmpi->set(String(name, CopyString), String(info_value->s, info_data->length, CopyString)); } break; case TAG_FMT_STRING: if (!(val = info_value->s)) { val = ""; } if (section_index==SECTION_COMMENT) { tmpi->set(idx++, String(val, CopyString)); } else { tmpi->set(String(name, CopyString), String(val, CopyString)); } break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: /*case TAG_FMT_BYTE: case TAG_FMT_SBYTE:*/ case TAG_FMT_USHORT: case TAG_FMT_SSHORT: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: case TAG_FMT_ULONG: case TAG_FMT_SLONG: /* now the rest, first see if it becomes an array */ if ((l = info_data->length) > 1) { array.clear(); } for(ap=0; ap<l; ap++) { if (l>1) { info_value = &info_data->value.list[ap]; } switch (info_data->format) { case TAG_FMT_BYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(b, (int)(info_value->s[b])); } break; } case TAG_FMT_USHORT: case TAG_FMT_ULONG: if (l==1) { tmpi->set(String(name, CopyString), (int)info_value->u); } else { array.set(ap, (int)info_value->u); } break; case TAG_FMT_URATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SBYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(ap, (int)info_value->s[b]); } break; } case TAG_FMT_SSHORT: case TAG_FMT_SLONG: if (l==1) { tmpi->set(String(name, CopyString), info_value->i); } else { array.set(ap, info_value->i); } break; case TAG_FMT_SRATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SINGLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->f); } else { array.set(ap, info_value->f); } break; case TAG_FMT_DOUBLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->d); } else { array.set(ap, info_value->d); } break; } info_value = &info_data->value.list[ap]; } if (l>1) { tmpi->set(String(name, CopyString), array); } break; } } } if (sub_array) { value.set(exif_get_sectionname(section_index), tmp); } } } Variant HHVM_FUNCTION(exif_tagname, int64_t index) { char *szTemp; szTemp = exif_get_tagname(index, nullptr, 0, tag_table_IFD); if (index <0 || !szTemp || !szTemp[0]) { return false; } else { return String(szTemp, CopyString); } } Variant HHVM_FUNCTION(exif_read_data, const String& filename, const String& sections /*="" */, bool arrays /*=false */, bool thumbnail /*=false */) { int i, ret, sections_needed=0; image_info_type ImageInfo; char tmp[64], *sections_str, *s; memset(&ImageInfo, 0, sizeof(ImageInfo)); if (!sections.empty()) { php_vspprintf(&sections_str, 0, ",%s,", sections.c_str()); /* sections_str DOES start with , and SPACES are NOT allowed in names */ s = sections_str; while(*++s) { if (*s==' ') { *s = ','; } } for (i=0; i<SECTION_COUNT; i++) { snprintf(tmp, sizeof(tmp), ",%s,", exif_get_sectionname(i).c_str()); if (strstr(sections_str, tmp)) { sections_needed |= 1<<i; } } if (sections_str) IM_FREE(sections_str); } ret = exif_read_file(&ImageInfo, filename, thumbnail, 0); sections_str = exif_get_sectionlist(ImageInfo.sections_found); /* do not inform about in debug*/ ImageInfo.sections_found |= FOUND_COMPUTED|FOUND_FILE; if (ret==0|| (sections_needed && !(sections_needed&ImageInfo.sections_found))) { exif_discard_imageinfo(&ImageInfo); if (sections_str) IM_FREE(sections_str); return false; } /* now we can add our information */ exif_iif_add_str(&ImageInfo, SECTION_FILE, "FileName", (char *)ImageInfo.FileName.c_str()); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileDateTime", ImageInfo.FileDateTime); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileSize", ImageInfo.FileSize); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileType", ImageInfo.FileType); exif_iif_add_str(&ImageInfo, SECTION_FILE, "MimeType", (char*)php_image_type_to_mime_type(ImageInfo.FileType)); exif_iif_add_str(&ImageInfo, SECTION_FILE, "SectionsFound", sections_str ? sections_str : (char *)"NONE"); if (ImageInfo.Width>0 && ImageInfo.Height>0) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "html", "width=\"%d\" height=\"%d\"", ImageInfo.Width, ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Height", ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Width", ImageInfo.Width); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "IsColor", ImageInfo.IsColor); if (ImageInfo.motorola_intel != -1) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "ByteOrderMotorola", ImageInfo.motorola_intel); } if (ImageInfo.FocalLength) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocalLength", "%4.1Fmm", ImageInfo.FocalLength); if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "35mmFocalLength", "%dmm", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5)); } } if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "CCDWidth", "%dmm", (int)ImageInfo.CCDWidth); } if (ImageInfo.ExposureTime>0) { if (ImageInfo.ExposureTime <= 0.5) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s (1/%d)", ImageInfo.ExposureTime, (int)(0.5 + 1/ImageInfo.ExposureTime)); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s", ImageInfo.ExposureTime); } } if (ImageInfo.ApertureFNumber) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ApertureFNumber", "f/%.1F", ImageInfo.ApertureFNumber); } if (ImageInfo.Distance) { if (ImageInfo.Distance<0) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "Infinite"); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "%0.2Fm", ImageInfo.Distance); } } if (ImageInfo.UserComment) { exif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, "UserComment", ImageInfo.UserCommentLength, ImageInfo.UserComment); if (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "UserCommentEncoding", ImageInfo.UserCommentEncoding); } } exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright", ImageInfo.Copyright); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Photographer", ImageInfo.CopyrightPhotographer); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Editor", ImageInfo.CopyrightEditor); for (i=0; i<ImageInfo.xp_fields.count; i++) { exif_iif_add_str(&ImageInfo, SECTION_WINXP, exif_get_tagname(ImageInfo.xp_fields.list[i].tag, nullptr, 0, exif_get_tag_table(SECTION_WINXP)), ImageInfo.xp_fields.list[i].value); } if (ImageInfo.Thumbnail.size) { if (thumbnail) { /* not exif_iif_add_str : this is a buffer */ exif_iif_add_tag(&ImageInfo, SECTION_THUMBNAIL, "THUMBNAIL", TAG_NONE, TAG_FMT_UNDEFINED, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.data); } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { /* try to evaluate if thumbnail data is present */ exif_scan_thumbnail(&ImageInfo); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.FileType", ImageInfo.Thumbnail.filetype); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Thumbnail.MimeType", (char*)php_image_type_to_mime_type(ImageInfo.Thumbnail.filetype)); } if (ImageInfo.Thumbnail.width && ImageInfo.Thumbnail.height) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Height", ImageInfo.Thumbnail.height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Width", ImageInfo.Thumbnail.width); } if (sections_str) IM_FREE(sections_str); Array retarr; add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FILE); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMPUTED); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_ANY_TAG); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_IFD0); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_THUMBNAIL); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMMENT); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_EXIF); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_GPS); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_INTEROP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FPIX); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_APP12); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_WINXP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_MAKERNOTE); exif_discard_imageinfo(&ImageInfo); return retarr; } Variant HHVM_FUNCTION(exif_thumbnail, const String& filename, VRefParam width /* = null */, VRefParam height /* = null */, VRefParam imagetype /* = null */) { image_info_type ImageInfo; memset(&ImageInfo, 0, sizeof(ImageInfo)); int ret = exif_read_file(&ImageInfo, filename.c_str(), 1, 0); if (ret==0) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.data || !ImageInfo.Thumbnail.size) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { exif_scan_thumbnail(&ImageInfo); } width.assignIfRef((int64_t)ImageInfo.Thumbnail.width); height.assignIfRef((int64_t)ImageInfo.Thumbnail.height); imagetype.assignIfRef(ImageInfo.Thumbnail.filetype); String str(ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, CopyString); exif_discard_imageinfo(&ImageInfo); return str; } Variant HHVM_FUNCTION(exif_imagetype, const String& filename) { auto stream = File::Open(filename, "rb"); if (!stream) { return false; } int itype = php_getimagetype(stream); stream->close(); if (itype == IMAGE_FILETYPE_UNKNOWN) return false; return itype; } /////////////////////////////////////////////////////////////////////////////// struct ExifExtension final : Extension { ExifExtension() : Extension("exif", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(exif_imagetype); HHVM_FE(exif_read_data); HHVM_FE(exif_tagname); HHVM_FE(exif_thumbnail); HHVM_RC_INT(EXIF_USE_MBSTRING, 0); loadSystemlib(); } } s_exif_extension; struct GdExtension final : Extension { GdExtension() : Extension("gd", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(gd_info); HHVM_FE(getimagesize); HHVM_FE(getimagesizefromstring); HHVM_FE(image_type_to_extension); HHVM_FE(image_type_to_mime_type); HHVM_FE(image2wbmp); HHVM_FE(imageaffine); HHVM_FE(imageaffinematrixconcat); HHVM_FE(imageaffinematrixget); HHVM_FE(imagealphablending); HHVM_FE(imageantialias); HHVM_FE(imagearc); HHVM_FE(imagechar); HHVM_FE(imagecharup); HHVM_FE(imagecolorallocate); HHVM_FE(imagecolorallocatealpha); HHVM_FE(imagecolorat); HHVM_FE(imagecolorclosest); HHVM_FE(imagecolorclosestalpha); HHVM_FE(imagecolorclosesthwb); HHVM_FE(imagecolordeallocate); HHVM_FE(imagecolorexact); HHVM_FE(imagecolorexactalpha); HHVM_FE(imagecolormatch); HHVM_FE(imagecolorresolve); HHVM_FE(imagecolorresolvealpha); HHVM_FE(imagecolorset); HHVM_FE(imagecolorsforindex); HHVM_FE(imagecolorstotal); HHVM_FE(imagecolortransparent); HHVM_FE(imageconvolution); HHVM_FE(imagecopy); HHVM_FE(imagecopymerge); HHVM_FE(imagecopymergegray); HHVM_FE(imagecopyresampled); HHVM_FE(imagecopyresized); HHVM_FE(imagecreate); HHVM_FE(imagecreatefromgd2part); HHVM_FE(imagecreatefromgd); HHVM_FE(imagecreatefromgd2); HHVM_FE(imagecreatefromgif); #ifdef HAVE_GD_JPG HHVM_FE(imagecreatefromjpeg); #endif #ifdef HAVE_GD_PNG HHVM_FE(imagecreatefrompng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagecreatefromwebp); #endif HHVM_FE(imagecreatefromstring); HHVM_FE(imagecreatefromwbmp); HHVM_FE(imagecreatefromxbm); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) HHVM_FE(imagecreatefromxpm); #endif HHVM_FE(imagecreatetruecolor); HHVM_FE(imagecrop); HHVM_FE(imagecropauto); HHVM_FE(imagedashedline); HHVM_FE(imagedestroy); HHVM_FE(imageellipse); HHVM_FE(imagefill); HHVM_FE(imagefilledarc); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilter); HHVM_FE(imageflip); HHVM_FE(imagefontheight); HHVM_FE(imagefontwidth); #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE HHVM_FE(imageftbbox); HHVM_FE(imagefttext); #endif HHVM_FE(imagegammacorrect); HHVM_FE(imagegd2); HHVM_FE(imagegd); HHVM_FE(imagegif); HHVM_FE(imageinterlace); HHVM_FE(imageistruecolor); #ifdef HAVE_GD_JPG HHVM_FE(imagejpeg); #endif HHVM_FE(imagelayereffect); HHVM_FE(imageline); HHVM_FE(imageloadfont); #ifdef HAVE_GD_PNG HHVM_FE(imagepng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagewebp); #endif HHVM_FE(imagepolygon); HHVM_FE(imagerectangle); HHVM_FE(imagerotate); HHVM_FE(imagesavealpha); HHVM_FE(imagescale); HHVM_FE(imagesetbrush); HHVM_FE(imagesetinterpolation); HHVM_FE(imagesetpixel); HHVM_FE(imagesetstyle); HHVM_FE(imagesetthickness); HHVM_FE(imagesettile); HHVM_FE(imagestring); HHVM_FE(imagestringup); HHVM_FE(imagesx); HHVM_FE(imagesy); HHVM_FE(imagetruecolortopalette); #ifdef ENABLE_GD_TTF HHVM_FE(imagettfbbox); HHVM_FE(imagettftext); #endif HHVM_FE(imagetypes); HHVM_FE(imagewbmp); HHVM_FE(iptcembed); HHVM_FE(iptcparse); HHVM_FE(jpeg2wbmp); HHVM_FE(png2wbmp); HHVM_FE(imagepalettecopy); HHVM_RC_INT(IMG_GIF, IMAGE_TYPE_GIF); HHVM_RC_INT(IMG_JPG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_JPEG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_PNG, IMAGE_TYPE_PNG); HHVM_RC_INT(IMG_WBMP, IMAGE_TYPE_WBMP); HHVM_RC_INT(IMG_XPM, IMAGE_TYPE_XPM); /* special colours for gd */ HHVM_RC_INT(IMG_COLOR_TILED, gdTiled); HHVM_RC_INT(IMG_COLOR_STYLED, gdStyled); HHVM_RC_INT(IMG_COLOR_BRUSHED, gdBrushed); HHVM_RC_INT(IMG_COLOR_STYLEDBRUSHED, gdStyledBrushed); HHVM_RC_INT(IMG_COLOR_TRANSPARENT, gdTransparent); /* for imagefilledarc */ HHVM_RC_INT(IMG_ARC_ROUNDED, gdArc); HHVM_RC_INT(IMG_ARC_PIE, gdPie); HHVM_RC_INT(IMG_ARC_CHORD, gdChord); HHVM_RC_INT(IMG_ARC_NOFILL, gdNoFill); HHVM_RC_INT(IMG_ARC_EDGED, gdEdged); /* GD2 image format types */ HHVM_RC_INT(IMG_GD2_RAW, GD2_FMT_RAW); HHVM_RC_INT(IMG_GD2_COMPRESSED, GD2_FMT_COMPRESSED); HHVM_RC_INT(IMG_FLIP_HORIZONTAL, GD_FLIP_HORINZONTAL); HHVM_RC_INT(IMG_FLIP_VERTICAL, GD_FLIP_VERTICAL); HHVM_RC_INT(IMG_FLIP_BOTH, GD_FLIP_BOTH); HHVM_RC_INT(IMG_EFFECT_REPLACE, gdEffectReplace); HHVM_RC_INT(IMG_EFFECT_ALPHABLEND, gdEffectAlphaBlend); HHVM_RC_INT(IMG_EFFECT_NORMAL, gdEffectNormal); HHVM_RC_INT(IMG_EFFECT_OVERLAY, gdEffectOverlay); HHVM_RC_INT(IMG_CROP_DEFAULT, GD_CROP_DEFAULT); HHVM_RC_INT(IMG_CROP_TRANSPARENT, GD_CROP_TRANSPARENT); HHVM_RC_INT(IMG_CROP_BLACK, GD_CROP_BLACK); HHVM_RC_INT(IMG_CROP_WHITE, GD_CROP_WHITE); HHVM_RC_INT(IMG_CROP_SIDES, GD_CROP_SIDES); HHVM_RC_INT(IMG_CROP_THRESHOLD, GD_CROP_THRESHOLD); HHVM_RC_INT(IMG_BELL, GD_BELL); HHVM_RC_INT(IMG_BESSEL, GD_BESSEL); HHVM_RC_INT(IMG_BILINEAR_FIXED, GD_BILINEAR_FIXED); HHVM_RC_INT(IMG_BICUBIC, GD_BICUBIC); HHVM_RC_INT(IMG_BICUBIC_FIXED, GD_BICUBIC_FIXED); HHVM_RC_INT(IMG_BLACKMAN, GD_BLACKMAN); HHVM_RC_INT(IMG_BOX, GD_BOX); HHVM_RC_INT(IMG_BSPLINE, GD_BSPLINE); HHVM_RC_INT(IMG_CATMULLROM, GD_CATMULLROM); HHVM_RC_INT(IMG_GAUSSIAN, GD_GAUSSIAN); HHVM_RC_INT(IMG_GENERALIZED_CUBIC, GD_GENERALIZED_CUBIC); HHVM_RC_INT(IMG_HERMITE, GD_HERMITE); HHVM_RC_INT(IMG_HAMMING, GD_HAMMING); HHVM_RC_INT(IMG_HANNING, GD_HANNING); HHVM_RC_INT(IMG_MITCHELL, GD_MITCHELL); HHVM_RC_INT(IMG_POWER, GD_POWER); HHVM_RC_INT(IMG_QUADRATIC, GD_QUADRATIC); HHVM_RC_INT(IMG_SINC, GD_SINC); HHVM_RC_INT(IMG_NEAREST_NEIGHBOUR, GD_NEAREST_NEIGHBOUR); HHVM_RC_INT(IMG_WEIGHTED4, GD_WEIGHTED4); HHVM_RC_INT(IMG_TRIANGLE, GD_TRIANGLE); HHVM_RC_INT(IMG_AFFINE_TRANSLATE, GD_AFFINE_TRANSLATE); HHVM_RC_INT(IMG_AFFINE_SCALE, GD_AFFINE_SCALE); HHVM_RC_INT(IMG_AFFINE_ROTATE, GD_AFFINE_ROTATE); HHVM_RC_INT(IMG_AFFINE_SHEAR_HORIZONTAL, GD_AFFINE_SHEAR_HORIZONTAL); HHVM_RC_INT(IMG_AFFINE_SHEAR_VERTICAL, GD_AFFINE_SHEAR_VERTICAL); HHVM_RC_INT(IMG_FILTER_BRIGHTNESS, IMAGE_FILTER_BRIGHTNESS); HHVM_RC_INT(IMG_FILTER_COLORIZE, IMAGE_FILTER_COLORIZE); HHVM_RC_INT(IMG_FILTER_CONTRAST, IMAGE_FILTER_CONTRAST); HHVM_RC_INT(IMG_FILTER_EDGEDETECT, IMAGE_FILTER_EDGEDETECT); HHVM_RC_INT(IMG_FILTER_EMBOSS, IMAGE_FILTER_EMBOSS); HHVM_RC_INT(IMG_FILTER_GAUSSIAN_BLUR, IMAGE_FILTER_GAUSSIAN_BLUR); HHVM_RC_INT(IMG_FILTER_GRAYSCALE, IMAGE_FILTER_GRAYSCALE); HHVM_RC_INT(IMG_FILTER_MEAN_REMOVAL, IMAGE_FILTER_MEAN_REMOVAL); HHVM_RC_INT(IMG_FILTER_NEGATE, IMAGE_FILTER_NEGATE); HHVM_RC_INT(IMG_FILTER_SELECTIVE_BLUR, IMAGE_FILTER_SELECTIVE_BLUR); HHVM_RC_INT(IMG_FILTER_SMOOTH, IMAGE_FILTER_SMOOTH); HHVM_RC_INT(IMG_FILTER_PIXELATE, IMAGE_FILTER_PIXELATE); HHVM_RC_INT(IMAGETYPE_GIF, IMAGE_FILETYPE_GIF); HHVM_RC_INT(IMAGETYPE_JPEG, IMAGE_FILETYPE_JPEG); HHVM_RC_INT(IMAGETYPE_PNG, IMAGE_FILETYPE_PNG); HHVM_RC_INT(IMAGETYPE_SWF, IMAGE_FILETYPE_SWF); HHVM_RC_INT(IMAGETYPE_PSD, IMAGE_FILETYPE_PSD); HHVM_RC_INT(IMAGETYPE_BMP, IMAGE_FILETYPE_BMP); HHVM_RC_INT(IMAGETYPE_TIFF_II, IMAGE_FILETYPE_TIFF_II); HHVM_RC_INT(IMAGETYPE_TIFF_MM, IMAGE_FILETYPE_TIFF_MM); HHVM_RC_INT(IMAGETYPE_JPC, IMAGE_FILETYPE_JPC); HHVM_RC_INT(IMAGETYPE_JP2, IMAGE_FILETYPE_JP2); HHVM_RC_INT(IMAGETYPE_JPX, IMAGE_FILETYPE_JPX); HHVM_RC_INT(IMAGETYPE_JB2, IMAGE_FILETYPE_JB2); HHVM_RC_INT(IMAGETYPE_IFF, IMAGE_FILETYPE_IFF); HHVM_RC_INT(IMAGETYPE_WBMP, IMAGE_FILETYPE_WBMP); HHVM_RC_INT(IMAGETYPE_XBM, IMAGE_FILETYPE_XBM); HHVM_RC_INT(IMAGETYPE_ICO, IMAGE_FILETYPE_ICO); HHVM_RC_INT(IMAGETYPE_UNKNOWN, IMAGE_FILETYPE_UNKNOWN); HHVM_RC_INT(IMAGETYPE_COUNT, IMAGE_FILETYPE_COUNT); HHVM_RC_INT(IMAGETYPE_SWC, IMAGE_FILETYPE_SWC); HHVM_RC_INT(IMAGETYPE_JPEG2000, IMAGE_FILETYPE_JPC); #ifdef GD_VERSION_STRING HHVM_RC_STR(GD_VERSION, GD_VERSION_STRING); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && \ defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) HHVM_RC_INT_SAME(GD_MAJOR_VERSION); HHVM_RC_INT_SAME(GD_MINOR_VERSION); HHVM_RC_INT_SAME(GD_RELEASE_VERSION); HHVM_RC_STR_SAME(GD_EXTRA_VERSION); #endif #ifdef HAVE_GD_PNG HHVM_RC_INT(PNG_NO_FILTER, 0x00); HHVM_RC_INT(PNG_FILTER_NONE, 0x08); HHVM_RC_INT(PNG_FILTER_SUB, 0x10); HHVM_RC_INT(PNG_FILTER_UP, 0x20); HHVM_RC_INT(PNG_FILTER_AVG, 0x40); HHVM_RC_INT(PNG_FILTER_PAETH, 0x80); HHVM_RC_INT(PNG_ALL_FILTERS, 0x08 | 0x10 | 0x20 | 0x40 | 0x80); #endif HHVM_RC_BOOL(GD_BUNDLED, true); loadSystemlib(); } } s_gd_extension; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_844_0
crossvul-cpp_data_bad_596_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/extension.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/execution-context.h" #include "hphp/runtime/vm/native-data.h" #include "hphp/runtime/ext/memcached/libmemcached_portability.h" #include "hphp/runtime/ext/sockets/ext_sockets.h" #include "hphp/runtime/base/rds-local.h" #include "hphp/runtime/base/ini-setting.h" #include "hphp/runtime/base/zend-string.h" #include <vector> // MMC values must match pecl-memcache for compatibility #define MMC_SERIALIZED 0x0001 #define MMC_COMPRESSED 0x0002 #define MMC_TYPE_STRING 0x0000 #define MMC_TYPE_BOOL 0x0100 #define MMC_TYPE_LONG 0x0300 #define MMC_TYPE_DOUBLE 0x0700 #define MMC_TYPE_MASK 0x0F00 namespace HPHP { const int64_t k_MEMCACHE_COMPRESSED = MMC_COMPRESSED; static bool ini_on_update_hash_strategy(const std::string& value); static bool ini_on_update_hash_function(const std::string& value); struct MEMCACHEGlobals final { std::string hash_strategy; std::string hash_function; }; static __thread MEMCACHEGlobals* s_memcache_globals; #define MEMCACHEG(name) s_memcache_globals->name const StaticString s_MemcacheData("MemcacheData"); struct MemcacheData { memcached_st m_memcache; TYPE_SCAN_IGNORE_FIELD(m_memcache); int m_compress_threshold; double m_min_compress_savings; MemcacheData(): m_memcache(), m_compress_threshold(0), m_min_compress_savings(0.2) { memcached_create(&m_memcache); if (MEMCACHEG(hash_strategy) == "consistent") { // need to hook up a global variable to set this memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_DISTRIBUTION, MEMCACHED_DISTRIBUTION_CONSISTENT_KETAMA); } else { memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_DISTRIBUTION, MEMCACHED_DISTRIBUTION_MODULA); } if (MEMCACHEG(hash_function) == "fnv") { memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_HASH, MEMCACHED_HASH_FNV1A_32); } else { memcached_behavior_set(&m_memcache, MEMCACHED_BEHAVIOR_HASH, MEMCACHED_HASH_CRC); } }; ~MemcacheData() { memcached_free(&m_memcache); }; }; static bool ini_on_update_hash_strategy(const std::string& value) { if (!strncasecmp(value.data(), "standard", sizeof("standard"))) { MEMCACHEG(hash_strategy) = "standard"; } else if (!strncasecmp(value.data(), "consistent", sizeof("consistent"))) { MEMCACHEG(hash_strategy) = "consistent"; } return false; } static bool ini_on_update_hash_function(const std::string& value) { if (!strncasecmp(value.data(), "crc32", sizeof("crc32"))) { MEMCACHEG(hash_function) = "crc32"; } else if (!strncasecmp(value.data(), "fnv", sizeof("fnv"))) { MEMCACHEG(hash_function) = "fnv"; } return false; } static bool hasAvailableServers(const MemcacheData* data) { if (memcached_server_count(&data->m_memcache) == 0) { raise_warning("Memcache: No servers added to memcache connection"); return false; } return true; } static bool isServerReachable(const String& host, int port /*= 0*/) { auto hostInfo = HHVM_FN(getaddrinfo)(host, port); if (hostInfo.isBoolean() && !hostInfo.toBoolean()) { raise_warning("Memcache: Can't connect to %s:%d", host.c_str(), port); return false; } return true; } /////////////////////////////////////////////////////////////////////////////// // methods static bool HHVM_METHOD(Memcache, connect, const String& host, int port /*= 0*/, int /*timeout*/ /*= 0*/, int /*timeoutms*/ /*= 0*/) { auto data = Native::data<MemcacheData>(this_); memcached_return_t ret; if (!host.empty() && !strncmp(host.c_str(), "unix://", sizeof("unix://") - 1)) { const char *socket_path = host.substr(sizeof("unix://") - 1).c_str(); ret = memcached_server_add_unix_socket(&data->m_memcache, socket_path); } else { if (!isServerReachable(host, port)) { return false; } ret = memcached_server_add(&data->m_memcache, host.c_str(), port); } return (ret == MEMCACHED_SUCCESS); } static uint32_t memcache_get_flag_for_type(const Variant& var) { switch (var.getType()) { case KindOfBoolean: return MMC_TYPE_BOOL; case KindOfInt64: return MMC_TYPE_LONG; case KindOfDouble: return MMC_TYPE_DOUBLE; case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfString: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfPersistentShape: case KindOfShape: case KindOfPersistentArray: case KindOfArray: case KindOfObject: case KindOfResource: case KindOfRef: case KindOfFunc: case KindOfClass: return MMC_TYPE_STRING; } not_reached(); } static void memcache_set_type_from_flag(Variant& var, uint32_t flags) { switch (flags & MMC_TYPE_MASK) { case MMC_TYPE_BOOL: var = var.toBoolean(); break; case MMC_TYPE_LONG: var = var.toInt64(); break; case MMC_TYPE_DOUBLE: var = var.toDouble(); break; } } static std::vector<char> memcache_prepare_for_storage(const MemcacheData* data, const Variant& var, int &flag) { String v; if (var.isString()) { v = var.toString(); } else if (var.isNumeric() || var.isBoolean()) { flag &= ~MMC_COMPRESSED; v = var.toString(); } else { flag |= MMC_SERIALIZED; v = f_serialize(var); } std::vector<char> payload; size_t value_len = v.length(); if (!var.isNumeric() && !var.isBoolean() && data->m_compress_threshold && value_len >= data->m_compress_threshold) { flag |= MMC_COMPRESSED; } if (flag & MMC_COMPRESSED) { size_t payload_len = compressBound(value_len); payload.resize(payload_len); if (compress((Bytef*)payload.data(), &payload_len, (const Bytef*)v.data(), value_len) == Z_OK) { payload.resize(payload_len); if (payload_len >= value_len * (1 - data->m_min_compress_savings)) { flag &= ~MMC_COMPRESSED; } } else { flag &= ~MMC_COMPRESSED; raise_warning("could not compress value"); } } if (!(flag & MMC_COMPRESSED)) { payload.resize(0); payload.insert(payload.end(), v.data(), v.data() + value_len); } flag |= memcache_get_flag_for_type(var); return payload; } static String memcache_prepare_key(const String& var) { String var_mutable(var, CopyString); auto data = var_mutable.get()->mutableData(); for (int i = 0; i < var.length(); i++) { // This is a stupid encoding since it causes collisions but it matches php5 if (data[i] <= ' ') { data[i] = '_'; } } return data; } static Variant unserialize_if_serialized(const char *payload, size_t payload_len, uint32_t flags) { Variant ret = uninit_null(); if (flags & MMC_SERIALIZED) { ret = unserialize_from_buffer( payload, payload_len, VariableUnserializer::Type::Serialize ); } else { if (payload_len == 0) { ret = empty_string(); } else { ret = String(payload, payload_len, CopyString); } } return ret; } static Variant memcache_fetch_from_storage(const char *payload, size_t payload_len, uint32_t flags) { Variant ret = uninit_null(); if (flags & MMC_COMPRESSED) { bool done = false; std::vector<char> buffer; size_t buffer_len; for (int factor = 1; !done && factor <= 16; ++factor) { if (payload_len >= std::numeric_limits<unsigned long>::max() / (1 << factor)) { break; } buffer_len = payload_len * (1 << factor) + 1; buffer.resize(buffer_len); if (uncompress((Bytef*)buffer.data(), &buffer_len, (const Bytef*)payload, (uLong)payload_len) == Z_OK) { done = true; } } if (!done) { raise_warning("could not uncompress value"); return init_null(); } ret = unserialize_if_serialized(buffer.data(), buffer_len, flags); } else { ret = unserialize_if_serialized(payload, payload_len, flags); } memcache_set_type_from_flag(ret, flags); return ret; } static bool HHVM_METHOD(Memcache, add, const String& key, const Variant& var, int flag /*= 0*/, int expire /*= 0*/) { if (key.empty()) { raise_warning("Key cannot be empty"); return false; } auto data = Native::data<MemcacheData>(this_); if (!hasAvailableServers(data)) { return false; } std::vector<char> serialized = memcache_prepare_for_storage(data, var, flag); String serializedKey = memcache_prepare_key(key); memcached_return_t ret = memcached_add(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), serialized.data(), serialized.size(), expire, flag); return (ret == MEMCACHED_SUCCESS); } static bool HHVM_METHOD(Memcache, set, const String& key, const Variant& var, int flag /*= 0*/, int expire /*= 0*/) { if (key.empty()) { raise_warning("Key cannot be empty"); return false; } auto data = Native::data<MemcacheData>(this_); if (!hasAvailableServers(data)) { return false; } String serializedKey = memcache_prepare_key(key); std::vector<char> serializedVar = memcache_prepare_for_storage(data, var, flag); memcached_return_t ret = memcached_set(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), serializedVar.data(), serializedVar.size(), expire, flag); if (ret == MEMCACHED_SUCCESS) { return true; } return false; } static bool HHVM_METHOD(Memcache, replace, const String& key, const Variant& var, int flag /*= 0*/, int expire /*= 0*/) { if (key.empty()) { raise_warning("Key cannot be empty"); return false; } auto data = Native::data<MemcacheData>(this_); if (!hasAvailableServers(data)) { return false; } String serializedKey = memcache_prepare_key(key); std::vector<char> serialized = memcache_prepare_for_storage(data, var, flag); memcached_return_t ret = memcached_replace(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), serialized.data(), serialized.size(), expire, flag); return (ret == MEMCACHED_SUCCESS); } static Variant HHVM_METHOD(Memcache, get, const Variant& key, VRefParam /*flags*/ /*= null*/) { auto data = Native::data<MemcacheData>(this_); if (!hasAvailableServers(data)) { return false; } if (key.isArray()) { std::vector<const char *> real_keys; std::vector<size_t> key_len; Array keyArr = key.toArray(); real_keys.reserve(keyArr.size()); key_len.reserve(keyArr.size()); for (ArrayIter iter(keyArr); iter; ++iter) { auto key = iter.second().toString(); String serializedKey = memcache_prepare_key(key); char *k = new char[serializedKey.length()+1]; memcpy(k, serializedKey.c_str(), serializedKey.length() + 1); real_keys.push_back(k); key_len.push_back(serializedKey.length()); } if (!real_keys.empty()) { const char *payload = nullptr; size_t payload_len = 0; uint32_t flags = 0; const char *res_key = nullptr; size_t res_key_len = 0; memcached_result_st result; memcached_return_t ret = memcached_mget(&data->m_memcache, &real_keys[0], &key_len[0], real_keys.size()); memcached_result_create(&data->m_memcache, &result); // To mimic PHP5 should return empty array at failure. Array return_val = Array::Create(); while ((memcached_fetch_result(&data->m_memcache, &result, &ret)) != nullptr) { if (ret != MEMCACHED_SUCCESS) { // should probably notify about errors continue; } payload = memcached_result_value(&result); payload_len = memcached_result_length(&result); flags = memcached_result_flags(&result); res_key = memcached_result_key_value(&result); res_key_len = memcached_result_key_length(&result); return_val.set(String(res_key, res_key_len, CopyString), memcache_fetch_from_storage(payload, payload_len, flags)); } memcached_result_free(&result); for ( size_t i = 0 ; i < real_keys.size() ; i++ ) { delete [] real_keys[i]; } return return_val; } } else { char *payload = nullptr; size_t payload_len = 0; uint32_t flags = 0; memcached_return_t ret; String serializedKey = memcache_prepare_key(key.toString()); if (serializedKey.length() == 0) { return false; } payload = memcached_get(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), &payload_len, &flags, &ret); /* This is for historical reasons from libmemcached*/ if (ret == MEMCACHED_END) { ret = MEMCACHED_NOTFOUND; } if (ret == MEMCACHED_NOTFOUND) { return false; } if (ret != MEMCACHED_SUCCESS) { return false; } Variant retval = memcache_fetch_from_storage(payload, payload_len, flags); free(payload); return retval; } return false; } static bool HHVM_METHOD(Memcache, delete, const String& key, int expire /*= 0*/) { if (key.empty()) { raise_warning("Key cannot be empty"); return false; } auto data = Native::data<MemcacheData>(this_); if (!hasAvailableServers(data)) { return false; } String serializedKey = memcache_prepare_key(key); memcached_return_t ret = memcached_delete(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), expire); return (ret == MEMCACHED_SUCCESS); } static Variant HHVM_METHOD(Memcache, increment, const String& key, int offset /*= 1*/) { if (key.empty()) { raise_warning("Key cannot be empty"); return false; } auto data = Native::data<MemcacheData>(this_); if (!hasAvailableServers(data)) { return false; } uint64_t value; String serializedKey = memcache_prepare_key(key); memcached_return_t ret = memcached_increment(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), offset, &value); if (ret == MEMCACHED_SUCCESS) { return (int64_t)value; } return false; } static Variant HHVM_METHOD(Memcache, decrement, const String& key, int offset /*= 1*/) { if (key.empty()) { raise_warning("Key cannot be empty"); return false; } auto data = Native::data<MemcacheData>(this_); if (!hasAvailableServers(data)) { return false; } uint64_t value; String serializedKey = memcache_prepare_key(key); memcached_return_t ret = memcached_decrement(&data->m_memcache, serializedKey.c_str(), serializedKey.length(), offset, &value); if (ret == MEMCACHED_SUCCESS) { return (int64_t)value; } return false; } static bool HHVM_METHOD(Memcache, close) { auto data = Native::data<MemcacheData>(this_); memcached_quit(&data->m_memcache); return true; } static Variant HHVM_METHOD(Memcache, getversion) { auto data = Native::data<MemcacheData>(this_); int server_count = memcached_server_count(&data->m_memcache); char version[16]; int version_len = 0; if (memcached_version(&data->m_memcache) != MEMCACHED_SUCCESS) { return false; } for (int x = 0; x < server_count; x++) { LMCD_SERVER_POSITION_INSTANCE_TYPE instance = memcached_server_instance_by_position(&data->m_memcache, x); uint8_t majorVersion = LMCD_SERVER_MAJOR_VERSION(instance); uint8_t minorVersion = LMCD_SERVER_MINOR_VERSION(instance); uint8_t microVersion = LMCD_SERVER_MICRO_VERSION(instance); if (!majorVersion) { continue; } version_len = snprintf(version, sizeof(version), "%" PRIu8 ".%" PRIu8 ".%" PRIu8, majorVersion, minorVersion, microVersion); return String(version, version_len, CopyString); } return false; } static bool HHVM_METHOD(Memcache, flush, int expire /*= 0*/) { auto data = Native::data<MemcacheData>(this_); return memcached_flush(&data->m_memcache, expire) == MEMCACHED_SUCCESS; } static bool HHVM_METHOD(Memcache, setcompressthreshold, int threshold, double min_savings /* = 0.2 */) { if (threshold < 0) { raise_warning("threshold must be a positive integer"); return false; } if (min_savings < 0 || min_savings > 1) { raise_warning("min_savings must be a float in the 0..1 range"); return false; } auto data = Native::data<MemcacheData>(this_); data->m_compress_threshold = threshold; data->m_min_compress_savings = min_savings; return true; } static Array memcache_build_stats(const memcached_st *ptr, memcached_stat_st *memc_stat, memcached_return_t *ret) { char **curr_key; char **stat_keys = memcached_stat_get_keys(const_cast<memcached_st*>(ptr), memc_stat, ret); if (*ret != MEMCACHED_SUCCESS) { if (stat_keys) { free(stat_keys); } return Array(); } Array return_val = Array::Create(); for (curr_key = stat_keys; *curr_key; curr_key++) { char *mc_val; mc_val = memcached_stat_get_value(ptr, memc_stat, *curr_key, ret); if (*ret != MEMCACHED_SUCCESS) { break; } return_val.set(String(*curr_key, CopyString), String(mc_val, CopyString)); free(mc_val); } free(stat_keys); return return_val; } static Array HHVM_METHOD(Memcache, getstats, const String& type /* = null_string */, int slabid /* = 0 */, int limit /* = 100 */) { auto data = Native::data<MemcacheData>(this_); if (!memcached_server_count(&data->m_memcache)) { return Array(); } char extra_args[30] = {0}; if (slabid) { snprintf(extra_args, sizeof(extra_args), "%s %d %d", type.c_str(), slabid, limit); } else if (!type.empty()) { snprintf(extra_args, sizeof(extra_args), "%s", type.c_str()); } LMCD_SERVER_POSITION_INSTANCE_TYPE instance = memcached_server_instance_by_position(&data->m_memcache, 0); const char *hostname = LMCD_SERVER_HOSTNAME(instance); in_port_t port = LMCD_SERVER_PORT(instance); memcached_stat_st stats; if (memcached_stat_servername(&stats, extra_args, hostname, port) != MEMCACHED_SUCCESS) { return Array(); } memcached_return_t ret; return memcache_build_stats(&data->m_memcache, &stats, &ret); } static Array HHVM_METHOD(Memcache, getextendedstats, const String& /*type*/ /* = null_string */, int /*slabid*/ /* = 0 */, int /*limit*/ /* = 100 */) { auto data = Native::data<MemcacheData>(this_); memcached_return_t ret; memcached_stat_st *stats; stats = memcached_stat(&data->m_memcache, nullptr, &ret); if (ret != MEMCACHED_SUCCESS) { return Array(); } int server_count = memcached_server_count(&data->m_memcache); Array return_val; for (int server_id = 0; server_id < server_count; server_id++) { memcached_stat_st *stat; char stats_key[30] = {0}; size_t key_len; LMCD_SERVER_POSITION_INSTANCE_TYPE instance = memcached_server_instance_by_position(&data->m_memcache, server_id); const char *hostname = LMCD_SERVER_HOSTNAME(instance); in_port_t port = LMCD_SERVER_PORT(instance); stat = stats + server_id; Array server_stats = memcache_build_stats(&data->m_memcache, stat, &ret); if (ret != MEMCACHED_SUCCESS) { continue; } key_len = snprintf(stats_key, sizeof(stats_key), "%s:%d", hostname, port); return_val.set(String(stats_key, key_len, CopyString), server_stats); } free(stats); return return_val; } static bool HHVM_METHOD(Memcache, addserver, const String& host, int port /* = 11211 */, bool /*persistent*/ /* = false */, int weight /* = 0 */, int /*timeout*/ /* = 0 */, int /*retry_interval*/ /* = 0 */, bool /*status*/ /* = true */, const Variant& /*failure_callback*/ /* = uninit_variant */, int /*timeoutms*/ /* = 0 */) { auto data = Native::data<MemcacheData>(this_); memcached_return_t ret; if (!host.empty() && !strncmp(host.c_str(), "unix://", sizeof("unix://") - 1)) { const char *socket_path = host.substr(sizeof("unix://") - 1).c_str(); ret = memcached_server_add_unix_socket_with_weight(&data->m_memcache, socket_path, weight); } else { ret = memcached_server_add_with_weight(&data->m_memcache, host.c_str(), port, weight); } if (ret == MEMCACHED_SUCCESS) { return true; } return false; } /////////////////////////////////////////////////////////////////////////////// struct MemcacheExtension final : Extension { MemcacheExtension() : Extension("memcache", "3.0.8") {}; void threadInit() override { assertx(!s_memcache_globals); s_memcache_globals = new MEMCACHEGlobals; IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "memcache.hash_strategy", "standard", IniSetting::SetAndGet<std::string>( ini_on_update_hash_strategy, nullptr ), &MEMCACHEG(hash_strategy)); IniSetting::Bind(this, IniSetting::PHP_INI_ALL, "memcache.hash_function", "crc32", IniSetting::SetAndGet<std::string>( ini_on_update_hash_function, nullptr ), &MEMCACHEG(hash_function)); } void threadShutdown() override { delete s_memcache_globals; s_memcache_globals = nullptr; } void moduleInit() override { HHVM_RC_INT(MEMCACHE_COMPRESSED, k_MEMCACHE_COMPRESSED); HHVM_RC_BOOL(MEMCACHE_HAVE_SESSION, true); HHVM_ME(Memcache, connect); HHVM_ME(Memcache, add); HHVM_ME(Memcache, set); HHVM_ME(Memcache, replace); HHVM_ME(Memcache, get); HHVM_ME(Memcache, delete); HHVM_ME(Memcache, increment); HHVM_ME(Memcache, decrement); HHVM_ME(Memcache, close); HHVM_ME(Memcache, getversion); HHVM_ME(Memcache, flush); HHVM_ME(Memcache, setcompressthreshold); HHVM_ME(Memcache, getstats); HHVM_ME(Memcache, getextendedstats); HHVM_ME(Memcache, addserver); Native::registerNativeDataInfo<MemcacheData>(s_MemcacheData.get()); loadSystemlib(); } } s_memcache_extension;; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_596_0
crossvul-cpp_data_bad_4256_4
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ESTreeIRGen.h" #include "llvh/ADT/StringSet.h" #include "llvh/Support/Debug.h" #include "llvh/Support/SaveAndRestore.h" namespace hermes { namespace irgen { //===----------------------------------------------------------------------===// // Free standing helpers. Instruction *emitLoad(IRBuilder &builder, Value *from, bool inhibitThrow) { if (auto *var = llvh::dyn_cast<Variable>(from)) { if (Variable::declKindNeedsTDZ(var->getDeclKind()) && var->getRelatedVariable()) { builder.createThrowIfUndefinedInst( builder.createLoadFrameInst(var->getRelatedVariable())); } return builder.createLoadFrameInst(var); } else if (auto *globalProp = llvh::dyn_cast<GlobalObjectProperty>(from)) { if (globalProp->isDeclared() || inhibitThrow) return builder.createLoadPropertyInst( builder.getGlobalObject(), globalProp->getName()); else return builder.createTryLoadGlobalPropertyInst(globalProp); } else { llvm_unreachable("unvalid value to load from"); } } Instruction * emitStore(IRBuilder &builder, Value *storedValue, Value *ptr, bool declInit) { if (auto *var = llvh::dyn_cast<Variable>(ptr)) { if (!declInit && Variable::declKindNeedsTDZ(var->getDeclKind()) && var->getRelatedVariable()) { // Must verify whether the variable is initialized. builder.createThrowIfUndefinedInst( builder.createLoadFrameInst(var->getRelatedVariable())); } auto *store = builder.createStoreFrameInst(storedValue, var); if (declInit && Variable::declKindNeedsTDZ(var->getDeclKind()) && var->getRelatedVariable()) { builder.createStoreFrameInst( builder.getLiteralBool(true), var->getRelatedVariable()); } return store; } else if (auto *globalProp = llvh::dyn_cast<GlobalObjectProperty>(ptr)) { if (globalProp->isDeclared() || !builder.getFunction()->isStrictMode()) return builder.createStorePropertyInst( storedValue, builder.getGlobalObject(), globalProp->getName()); else return builder.createTryStoreGlobalPropertyInst(storedValue, globalProp); } else { llvm_unreachable("unvalid value to load from"); } } /// \returns true if \p node is a constant expression. bool isConstantExpr(ESTree::Node *node) { // TODO: a little more agressive constant folding. switch (node->getKind()) { case ESTree::NodeKind::StringLiteral: case ESTree::NodeKind::NumericLiteral: case ESTree::NodeKind::NullLiteral: case ESTree::NodeKind::BooleanLiteral: return true; default: return false; } } //===----------------------------------------------------------------------===// // LReference IRBuilder &LReference::getBuilder() { return irgen_->Builder; } Value *LReference::emitLoad() { auto &builder = getBuilder(); IRBuilder::ScopedLocationChange slc(builder, loadLoc_); switch (kind_) { case Kind::Empty: assert(false && "empty cannot be loaded"); return builder.getLiteralUndefined(); case Kind::Member: return builder.createLoadPropertyInst(base_, property_); case Kind::VarOrGlobal: return irgen::emitLoad(builder, base_); case Kind::Destructuring: assert(false && "destructuring cannot be loaded"); return builder.getLiteralUndefined(); case Kind::Error: return builder.getLiteralUndefined(); } llvm_unreachable("invalid LReference kind"); } void LReference::emitStore(Value *value) { auto &builder = getBuilder(); switch (kind_) { case Kind::Empty: return; case Kind::Member: builder.createStorePropertyInst(value, base_, property_); return; case Kind::VarOrGlobal: irgen::emitStore(builder, value, base_, declInit_); return; case Kind::Error: return; case Kind::Destructuring: return irgen_->emitDestructuringAssignment( declInit_, destructuringTarget_, value); } llvm_unreachable("invalid LReference kind"); } bool LReference::canStoreWithoutSideEffects() const { return kind_ == Kind::VarOrGlobal && llvh::isa<Variable>(base_); } Variable *LReference::castAsVariable() const { return kind_ == Kind::VarOrGlobal ? dyn_cast_or_null<Variable>(base_) : nullptr; } GlobalObjectProperty *LReference::castAsGlobalObjectProperty() const { return kind_ == Kind::VarOrGlobal ? dyn_cast_or_null<GlobalObjectProperty>(base_) : nullptr; } //===----------------------------------------------------------------------===// // ESTreeIRGen ESTreeIRGen::ESTreeIRGen( ESTree::Node *root, const DeclarationFileListTy &declFileList, Module *M, const ScopeChain &scopeChain) : Mod(M), Builder(Mod), instrumentIR_(M, Builder), Root(root), DeclarationFileList(declFileList), lexicalScopeChain(resolveScopeIdentifiers(scopeChain)), identEval_(Builder.createIdentifier("eval")), identLet_(Builder.createIdentifier("let")), identDefaultExport_(Builder.createIdentifier("?default")) {} void ESTreeIRGen::doIt() { LLVM_DEBUG(dbgs() << "Processing top level program.\n"); ESTree::ProgramNode *Program; Program = llvh::dyn_cast<ESTree::ProgramNode>(Root); if (!Program) { Builder.getModule()->getContext().getSourceErrorManager().error( SMLoc{}, "missing 'Program' AST node"); return; } LLVM_DEBUG(dbgs() << "Found Program decl.\n"); // The function which will "execute" the module. Function *topLevelFunction; // Function context used only when compiling in an existing lexical scope // chain. It is only initialized if we have a lexical scope chain. llvh::Optional<FunctionContext> wrapperFunctionContext{}; if (!lexicalScopeChain) { topLevelFunction = Builder.createTopLevelFunction( ESTree::isStrict(Program->strictness), Program->getSourceRange()); } else { // If compiling in an existing lexical context, we need to install the // scopes in a wrapper function, which represents the "global" code. Function *wrapperFunction = Builder.createFunction( "", Function::DefinitionKind::ES5Function, ESTree::isStrict(Program->strictness), Program->getSourceRange(), true); // Initialize the wrapper context. wrapperFunctionContext.emplace(this, wrapperFunction, nullptr); // Populate it with dummy code so it doesn't crash the back-end. genDummyFunction(wrapperFunction); // Restore the previously saved parent scopes. materializeScopesInChain(wrapperFunction, lexicalScopeChain, -1); // Finally create the function which will actually be executed. topLevelFunction = Builder.createFunction( "eval", Function::DefinitionKind::ES5Function, ESTree::isStrict(Program->strictness), Program->getSourceRange(), false); } Mod->setTopLevelFunction(topLevelFunction); // Function context for topLevelFunction. FunctionContext topLevelFunctionContext{ this, topLevelFunction, Program->getSemInfo()}; // IRGen needs a pointer to the outer-most context, which is either // topLevelContext or wrapperFunctionContext, depending on whether the latter // was created. // We want to set the pointer to that outer-most context, but ensure that it // doesn't outlive the context it is pointing to. llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext( topLevelContext, !wrapperFunctionContext.hasValue() ? &topLevelFunctionContext : &wrapperFunctionContext.getValue()); // Now declare all externally supplied global properties, but only if we don't // have a lexical scope chain. if (!lexicalScopeChain) { for (auto declFile : DeclarationFileList) { processDeclarationFile(declFile); } } emitFunctionPrologue( Program, Builder.createBasicBlock(topLevelFunction), InitES5CaptureState::Yes, DoEmitParameters::Yes); Value *retVal; { // Allocate the return register, initialize it to undefined. curFunction()->globalReturnRegister = Builder.createAllocStackInst(genAnonymousLabelName("ret")); Builder.createStoreStackInst( Builder.getLiteralUndefined(), curFunction()->globalReturnRegister); genBody(Program->_body); // Terminate the top-level scope with a return statement. retVal = Builder.createLoadStackInst(curFunction()->globalReturnRegister); } emitFunctionEpilogue(retVal); } void ESTreeIRGen::doCJSModule( Function *topLevelFunction, sem::FunctionInfo *semInfo, uint32_t id, llvh::StringRef filename) { assert(Root && "no root in ESTreeIRGen"); auto *func = cast<ESTree::FunctionExpressionNode>(Root); assert(func && "doCJSModule without a module"); FunctionContext topLevelFunctionContext{this, topLevelFunction, semInfo}; llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext( topLevelContext, &topLevelFunctionContext); // Now declare all externally supplied global properties, but only if we don't // have a lexical scope chain. assert( !lexicalScopeChain && "Lexical scope chain not supported for CJS modules"); for (auto declFile : DeclarationFileList) { processDeclarationFile(declFile); } Identifier functionName = Builder.createIdentifier("cjs_module"); Function *newFunc = genES5Function(functionName, nullptr, func); Builder.getModule()->addCJSModule( id, Builder.createIdentifier(filename), newFunc); } static int getDepth(const std::shared_ptr<SerializedScope> chain) { int depth = 0; const SerializedScope *current = chain.get(); while (current) { depth += 1; current = current->parentScope.get(); } return depth; } std::pair<Function *, Function *> ESTreeIRGen::doLazyFunction( hbc::LazyCompilationData *lazyData) { // Create a top level function that will never be executed, because: // 1. IRGen assumes the first function always has global scope // 2. It serves as the root for dummy functions for lexical data Function *topLevel = Builder.createTopLevelFunction(lazyData->strictMode, {}); FunctionContext topLevelFunctionContext{this, topLevel, nullptr}; // Save the top-level context, but ensure it doesn't outlive what it is // pointing to. llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext( topLevelContext, &topLevelFunctionContext); auto *node = cast<ESTree::FunctionLikeNode>(Root); // We restore scoping information in two separate ways: // 1. By adding them to ExternalScopes for resolution here // 2. By adding dummy functions for lexical scoping debug info later // // Instruction selection determines the delta between the ExternalScope // and the dummy function chain, so we add the ExternalScopes with // positive depth. lexicalScopeChain = lazyData->parentScope; materializeScopesInChain( topLevel, lexicalScopeChain, getDepth(lexicalScopeChain) - 1); // If lazyData->closureAlias is specified, we must create an alias binding // between originalName (which must be valid) and the variable identified by // closureAlias. Variable *parentVar = nullptr; if (lazyData->closureAlias.isValid()) { assert(lazyData->originalName.isValid() && "Original name invalid"); assert( lazyData->originalName != lazyData->closureAlias && "Original name must be different from the alias"); // NOTE: the closureAlias target must exist and must be a Variable. parentVar = cast<Variable>(nameTable_.lookup(lazyData->closureAlias)); // Re-create the alias. nameTable_.insert(lazyData->originalName, parentVar); } assert( !llvh::isa<ESTree::ArrowFunctionExpressionNode>(node) && "lazy compilation not supported for arrow functions"); auto *func = genES5Function(lazyData->originalName, parentVar, node); addLexicalDebugInfo(func, topLevel, lexicalScopeChain); return {func, topLevel}; } std::pair<Value *, bool> ESTreeIRGen::declareVariableOrGlobalProperty( Function *inFunc, VarDecl::Kind declKind, Identifier name) { Value *found = nameTable_.lookup(name); // If the variable is already declared in this scope, do not create a // second instance. if (found) { if (auto *var = llvh::dyn_cast<Variable>(found)) { if (var->getParent()->getFunction() == inFunc) return {found, false}; } else { assert( llvh::isa<GlobalObjectProperty>(found) && "Invalid value found in name table"); if (inFunc->isGlobalScope()) return {found, false}; } } // Create a property if global scope, variable otherwise. Value *res; if (inFunc->isGlobalScope() && declKind == VarDecl::Kind::Var) { res = Builder.createGlobalObjectProperty(name, true); } else { Variable::DeclKind vdc; if (declKind == VarDecl::Kind::Let) vdc = Variable::DeclKind::Let; else if (declKind == VarDecl::Kind::Const) vdc = Variable::DeclKind::Const; else { assert(declKind == VarDecl::Kind::Var); vdc = Variable::DeclKind::Var; } auto *var = Builder.createVariable(inFunc->getFunctionScope(), vdc, name); // For "let" and "const" create the related TDZ flag. if (Variable::declKindNeedsTDZ(vdc) && Mod->getContext().getCodeGenerationSettings().enableTDZ) { llvh::SmallString<32> strBuf{"tdz$"}; strBuf.append(name.str()); auto *related = Builder.createVariable( var->getParent(), Variable::DeclKind::Var, genAnonymousLabelName(strBuf)); var->setRelatedVariable(related); related->setRelatedVariable(var); } res = var; } // Register the variable in the scoped hash table. nameTable_.insert(name, res); return {res, true}; } GlobalObjectProperty *ESTreeIRGen::declareAmbientGlobalProperty( Identifier name) { // Avoid redefining global properties. auto *prop = dyn_cast_or_null<GlobalObjectProperty>(nameTable_.lookup(name)); if (prop) return prop; LLVM_DEBUG( llvh::dbgs() << "declaring ambient global property " << name << " " << name.getUnderlyingPointer() << "\n"); prop = Builder.createGlobalObjectProperty(name, false); nameTable_.insertIntoScope(&topLevelContext->scope, name, prop); return prop; } namespace { /// This visitor structs collects declarations within a single closure without /// descending into child closures. struct DeclHoisting { /// The list of collected identifiers (variables and functions). llvh::SmallVector<ESTree::VariableDeclaratorNode *, 8> decls{}; /// A list of functions that need to be hoisted and materialized before we /// can generate the rest of the function. llvh::SmallVector<ESTree::FunctionDeclarationNode *, 8> closures; explicit DeclHoisting() = default; ~DeclHoisting() = default; /// Extract the variable name from the nodes that can define new variables. /// The nodes that can define a new variable in the scope are: /// VariableDeclarator and FunctionDeclaration> void collectDecls(ESTree::Node *V) { if (auto VD = llvh::dyn_cast<ESTree::VariableDeclaratorNode>(V)) { return decls.push_back(VD); } if (auto FD = llvh::dyn_cast<ESTree::FunctionDeclarationNode>(V)) { return closures.push_back(FD); } } bool shouldVisit(ESTree::Node *V) { // Collect declared names, even if we don't descend into children nodes. collectDecls(V); // Do not descend to child closures because the variables they define are // not exposed to the outside function. if (llvh::isa<ESTree::FunctionDeclarationNode>(V) || llvh::isa<ESTree::FunctionExpressionNode>(V) || llvh::isa<ESTree::ArrowFunctionExpressionNode>(V)) return false; return true; } void enter(ESTree::Node *V) {} void leave(ESTree::Node *V) {} }; } // anonymous namespace. void ESTreeIRGen::processDeclarationFile(ESTree::ProgramNode *programNode) { auto Program = dyn_cast_or_null<ESTree::ProgramNode>(programNode); if (!Program) return; DeclHoisting DH; Program->visit(DH); // Create variable declarations for each of the hoisted variables. for (auto vd : DH.decls) declareAmbientGlobalProperty(getNameFieldFromID(vd->_id)); for (auto fd : DH.closures) declareAmbientGlobalProperty(getNameFieldFromID(fd->_id)); } Value *ESTreeIRGen::ensureVariableExists(ESTree::IdentifierNode *id) { assert(id && "id must be a valid Identifier node"); Identifier name = getNameFieldFromID(id); // Check if this is a known variable. if (auto *var = nameTable_.lookup(name)) return var; if (curFunction()->function->isStrictMode()) { // Report a warning in strict mode. auto currentFunc = Builder.getInsertionBlock()->getParent(); Builder.getModule()->getContext().getSourceErrorManager().warning( Warning::UndefinedVariable, id->getSourceRange(), Twine("the variable \"") + name.str() + "\" was not declared in " + currentFunc->getDescriptiveDefinitionKindStr() + " \"" + currentFunc->getInternalNameStr() + "\""); } // Undeclared variable is an ambient global property. return declareAmbientGlobalProperty(name); } Value *ESTreeIRGen::genMemberExpressionProperty( ESTree::MemberExpressionLikeNode *Mem) { // If computed is true, the node corresponds to a computed (a[b]) member // lookup and '_property' is an Expression. Otherwise, the node // corresponds to a static (a.b) member lookup and '_property' is an // Identifier. // Details of the computed field are available here: // https://github.com/estree/estree/blob/master/spec.md#memberexpression if (getComputed(Mem)) { return genExpression(getProperty(Mem)); } // Arrays and objects may be accessed with integer indices. if (auto N = llvh::dyn_cast<ESTree::NumericLiteralNode>(getProperty(Mem))) { return Builder.getLiteralNumber(N->_value); } // ESTree encodes property access as MemberExpression -> Identifier. auto Id = cast<ESTree::IdentifierNode>(getProperty(Mem)); Identifier fieldName = getNameFieldFromID(Id); LLVM_DEBUG( dbgs() << "Emitting direct label access to field '" << fieldName << "'\n"); return Builder.getLiteralString(fieldName); } bool ESTreeIRGen::canCreateLRefWithoutSideEffects( hermes::ESTree::Node *target) { // Check for an identifier bound to an existing local variable. if (auto *iden = llvh::dyn_cast<ESTree::IdentifierNode>(target)) { return dyn_cast_or_null<Variable>( nameTable_.lookup(getNameFieldFromID(iden))); } return false; } LReference ESTreeIRGen::createLRef(ESTree::Node *node, bool declInit) { SMLoc sourceLoc = node->getDebugLoc(); IRBuilder::ScopedLocationChange slc(Builder, sourceLoc); if (llvh::isa<ESTree::EmptyNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for EmptyNode.\n"); return LReference( LReference::Kind::Empty, this, false, nullptr, nullptr, sourceLoc); } /// Create lref for member expression (ex: o.f). if (auto *ME = llvh::dyn_cast<ESTree::MemberExpressionNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for member expression.\n"); Value *obj = genExpression(ME->_object); Value *prop = genMemberExpressionProperty(ME); return LReference( LReference::Kind::Member, this, false, obj, prop, sourceLoc); } /// Create lref for identifiers (ex: a). if (auto *iden = llvh::dyn_cast<ESTree::IdentifierNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for identifier.\n"); LLVM_DEBUG( dbgs() << "Looking for identifier \"" << getNameFieldFromID(iden) << "\"\n"); auto *var = ensureVariableExists(iden); return LReference( LReference::Kind::VarOrGlobal, this, declInit, var, nullptr, sourceLoc); } /// Create lref for variable decls (ex: var a). if (auto *V = llvh::dyn_cast<ESTree::VariableDeclarationNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for variable declaration.\n"); assert(V->_declarations.size() == 1 && "Malformed variable declaration"); auto *decl = cast<ESTree::VariableDeclaratorNode>(&V->_declarations.front()); return createLRef(decl->_id, true); } // Destructuring assignment. if (auto *pat = llvh::dyn_cast<ESTree::PatternNode>(node)) { return LReference(this, declInit, pat); } Builder.getModule()->getContext().getSourceErrorManager().error( node->getSourceRange(), "unsupported assignment target"); return LReference( LReference::Kind::Error, this, false, nullptr, nullptr, sourceLoc); } Value *ESTreeIRGen::genHermesInternalCall( StringRef name, Value *thisValue, ArrayRef<Value *> args) { return Builder.createCallInst( Builder.createLoadPropertyInst( Builder.createTryLoadGlobalPropertyInst("HermesInternal"), name), thisValue, args); } Value *ESTreeIRGen::genBuiltinCall( hermes::BuiltinMethod::Enum builtinIndex, ArrayRef<Value *> args) { return Builder.createCallBuiltinInst(builtinIndex, args); } void ESTreeIRGen::emitEnsureObject(Value *value, StringRef message) { // TODO: use "thisArg" when builtins get fixed to support it. genBuiltinCall( BuiltinMethod::HermesBuiltin_ensureObject, {value, Builder.getLiteralString(message)}); } Value *ESTreeIRGen::emitIteratorSymbol() { // FIXME: use the builtin value of @@iterator. Symbol could have been // overridden. return Builder.createLoadPropertyInst( Builder.createTryLoadGlobalPropertyInst("Symbol"), "iterator"); } ESTreeIRGen::IteratorRecordSlow ESTreeIRGen::emitGetIteratorSlow(Value *obj) { auto *method = Builder.createLoadPropertyInst(obj, emitIteratorSymbol()); auto *iterator = Builder.createCallInst(method, obj, {}); emitEnsureObject(iterator, "iterator is not an object"); auto *nextMethod = Builder.createLoadPropertyInst(iterator, "next"); return {iterator, nextMethod}; } Value *ESTreeIRGen::emitIteratorNextSlow(IteratorRecordSlow iteratorRecord) { auto *nextResult = Builder.createCallInst( iteratorRecord.nextMethod, iteratorRecord.iterator, {}); emitEnsureObject(nextResult, "iterator.next() did not return an object"); return nextResult; } Value *ESTreeIRGen::emitIteratorCompleteSlow(Value *iterResult) { return Builder.createLoadPropertyInst(iterResult, "done"); } Value *ESTreeIRGen::emitIteratorValueSlow(Value *iterResult) { return Builder.createLoadPropertyInst(iterResult, "value"); } void ESTreeIRGen::emitIteratorCloseSlow( hermes::irgen::ESTreeIRGen::IteratorRecordSlow iteratorRecord, bool ignoreInnerException) { auto *haveReturn = Builder.createBasicBlock(Builder.getFunction()); auto *noReturn = Builder.createBasicBlock(Builder.getFunction()); auto *returnMethod = genBuiltinCall( BuiltinMethod::HermesBuiltin_getMethod, {iteratorRecord.iterator, Builder.getLiteralString("return")}); Builder.createCompareBranchInst( returnMethod, Builder.getLiteralUndefined(), BinaryOperatorInst::OpKind::StrictlyEqualKind, noReturn, haveReturn); Builder.setInsertionBlock(haveReturn); if (ignoreInnerException) { emitTryCatchScaffolding( noReturn, // emitBody. [this, returnMethod, &iteratorRecord]() { Builder.createCallInst(returnMethod, iteratorRecord.iterator, {}); }, // emitNormalCleanup. []() {}, // emitHandler. [this](BasicBlock *nextBlock) { // We need to catch the exception, even if we don't used it. Builder.createCatchInst(); Builder.createBranchInst(nextBlock); }); } else { auto *innerResult = Builder.createCallInst(returnMethod, iteratorRecord.iterator, {}); emitEnsureObject(innerResult, "iterator.return() did not return an object"); Builder.createBranchInst(noReturn); } Builder.setInsertionBlock(noReturn); } ESTreeIRGen::IteratorRecord ESTreeIRGen::emitGetIterator(Value *obj) { // Each of these will be modified by "next", so we use a stack storage. auto *iterStorage = Builder.createAllocStackInst(genAnonymousLabelName("iter")); auto *sourceOrNext = Builder.createAllocStackInst(genAnonymousLabelName("sourceOrNext")); Builder.createStoreStackInst(obj, sourceOrNext); auto *iter = Builder.createIteratorBeginInst(sourceOrNext); Builder.createStoreStackInst(iter, iterStorage); return IteratorRecord{iterStorage, sourceOrNext}; } void ESTreeIRGen::emitDestructuringAssignment( bool declInit, ESTree::PatternNode *target, Value *source) { if (auto *APN = llvh::dyn_cast<ESTree::ArrayPatternNode>(target)) return emitDestructuringArray(declInit, APN, source); else if (auto *OPN = llvh::dyn_cast<ESTree::ObjectPatternNode>(target)) return emitDestructuringObject(declInit, OPN, source); else { Mod->getContext().getSourceErrorManager().error( target->getSourceRange(), "unsupported destructuring target"); } } void ESTreeIRGen::emitDestructuringArray( bool declInit, ESTree::ArrayPatternNode *targetPat, Value *source) { const IteratorRecord iteratorRecord = emitGetIterator(source); /// iteratorDone = undefined. auto *iteratorDone = Builder.createAllocStackInst(genAnonymousLabelName("iterDone")); Builder.createStoreStackInst(Builder.getLiteralUndefined(), iteratorDone); auto *value = Builder.createAllocStackInst(genAnonymousLabelName("iterValue")); SharedExceptionHandler handler{}; handler.exc = Builder.createAllocStackInst(genAnonymousLabelName("exc")); // All exception handlers branch to this block. handler.exceptionBlock = Builder.createBasicBlock(Builder.getFunction()); bool first = true; bool emittedRest = false; // The LReference created in the previous iteration of the destructuring // loop. We need it because we want to put the previous store and the creation // of the next LReference under one try block. llvh::Optional<LReference> lref; /// If the previous LReference is valid and non-empty, store "value" into /// it and reset the LReference. auto storePreviousValue = [&lref, &handler, this, value]() { if (lref && !lref->isEmpty()) { if (lref->canStoreWithoutSideEffects()) { lref->emitStore(Builder.createLoadStackInst(value)); } else { // If we can't store without side effects, wrap the store in try/catch. emitTryWithSharedHandler(&handler, [this, &lref, value]() { lref->emitStore(Builder.createLoadStackInst(value)); }); } lref.reset(); } }; for (auto &elem : targetPat->_elements) { ESTree::Node *target = &elem; ESTree::Node *init = nullptr; if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(target)) { storePreviousValue(); emitRestElement(declInit, rest, iteratorRecord, iteratorDone, &handler); emittedRest = true; break; } // If we have an initializer, unwrap it. if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(target)) { target = assign->_left; init = assign->_right; } // Can we create the new LReference without side effects and avoid a // try/catch. The complexity comes from having to check whether the last // LReference also can avoid a try/catch or not. if (canCreateLRefWithoutSideEffects(target)) { // We don't need a try/catch, but last lref might. Just let the routine // do the right thing. storePreviousValue(); lref = createLRef(target, declInit); } else { // We need a try/catch, but last lref might not. If it doesn't, emit it // directly and clear it, so we won't do anything inside our try/catch. if (lref && lref->canStoreWithoutSideEffects()) { lref->emitStore(Builder.createLoadStackInst(value)); lref.reset(); } emitTryWithSharedHandler( &handler, [this, &lref, value, target, declInit]() { // Store the previous value, if we have one. if (lref && !lref->isEmpty()) lref->emitStore(Builder.createLoadStackInst(value)); lref = createLRef(target, declInit); }); } // Pseudocode of the algorithm for a step: // // value = undefined; // if (iteratorDone) goto nextBlock // notDoneBlock: // stepResult = IteratorNext(iteratorRecord) // stepDone = IteratorComplete(stepResult) // iteratorDone = stepDone // if (stepDone) goto nextBlock // newValueBlock: // value = IteratorValue(stepResult) // nextBlock: // if (value !== undefined) goto storeBlock [if initializer present] // value = initializer [if initializer present] // storeBlock: // lref.emitStore(value) auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *newValueBlock = Builder.createBasicBlock(Builder.getFunction()); auto *nextBlock = Builder.createBasicBlock(Builder.getFunction()); auto *getDefaultBlock = init ? Builder.createBasicBlock(Builder.getFunction()) : nullptr; auto *storeBlock = init ? Builder.createBasicBlock(Builder.getFunction()) : nullptr; Builder.createStoreStackInst(Builder.getLiteralUndefined(), value); // In the first iteration we know that "done" is false. if (first) { first = false; Builder.createBranchInst(notDoneBlock); } else { Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), nextBlock, notDoneBlock); } // notDoneBlock: Builder.setInsertionBlock(notDoneBlock); auto *stepValue = emitIteratorNext(iteratorRecord); auto *stepDone = emitIteratorComplete(iteratorRecord); Builder.createStoreStackInst(stepDone, iteratorDone); Builder.createCondBranchInst( stepDone, init ? getDefaultBlock : nextBlock, newValueBlock); // newValueBlock: Builder.setInsertionBlock(newValueBlock); Builder.createStoreStackInst(stepValue, value); Builder.createBranchInst(nextBlock); // nextBlock: Builder.setInsertionBlock(nextBlock); // NOTE: we can't use emitOptionalInitializationHere() because we want to // be able to jump directly to getDefaultBlock. if (init) { // if (value !== undefined) goto storeBlock [if initializer present] // value = initializer [if initializer present] // storeBlock: Builder.createCondBranchInst( Builder.createBinaryOperatorInst( Builder.createLoadStackInst(value), Builder.getLiteralUndefined(), BinaryOperatorInst::OpKind::StrictlyNotEqualKind), storeBlock, getDefaultBlock); Identifier nameHint = llvh::isa<ESTree::IdentifierNode>(target) ? getNameFieldFromID(target) : Identifier{}; // getDefaultBlock: Builder.setInsertionBlock(getDefaultBlock); Builder.createStoreStackInst(genExpression(init, nameHint), value); Builder.createBranchInst(storeBlock); // storeBlock: Builder.setInsertionBlock(storeBlock); } } storePreviousValue(); // If in the end the iterator is not done, close it. We only need to do // that if we didn't end with a rest element because it would have exhausted // the iterator. if (!emittedRest) { auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *doneBlock = Builder.createBasicBlock(Builder.getFunction()); Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock); Builder.setInsertionBlock(notDoneBlock); emitIteratorClose(iteratorRecord, false); Builder.createBranchInst(doneBlock); Builder.setInsertionBlock(doneBlock); } // If we emitted at least one try block, generate the exception handler. if (handler.emittedTry) { IRBuilder::SaveRestore saveRestore{Builder}; Builder.setInsertionBlock(handler.exceptionBlock); auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *doneBlock = Builder.createBasicBlock(Builder.getFunction()); Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock); Builder.setInsertionBlock(notDoneBlock); emitIteratorClose(iteratorRecord, true); Builder.createBranchInst(doneBlock); Builder.setInsertionBlock(doneBlock); Builder.createThrowInst(Builder.createLoadStackInst(handler.exc)); } else { // If we didn't use the exception block, we need to delete it, otherwise // it fails IR validation even though it will be never executed. handler.exceptionBlock->eraseFromParent(); // Delete the not needed exception stack allocation. It would be optimized // out later, but it is nice to produce cleaner non-optimized IR, if it is // easy to do so. assert( !handler.exc->hasUsers() && "should not have any users if no try/catch was emitted"); handler.exc->eraseFromParent(); } } void ESTreeIRGen::emitRestElement( bool declInit, ESTree::RestElementNode *rest, hermes::irgen::ESTreeIRGen::IteratorRecord iteratorRecord, hermes::AllocStackInst *iteratorDone, SharedExceptionHandler *handler) { // 13.3.3.8 BindingRestElement:...BindingIdentifier auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *newValueBlock = Builder.createBasicBlock(Builder.getFunction()); auto *doneBlock = Builder.createBasicBlock(Builder.getFunction()); llvh::Optional<LReference> lref; if (canCreateLRefWithoutSideEffects(rest->_argument)) { lref = createLRef(rest->_argument, declInit); } else { emitTryWithSharedHandler(handler, [this, &lref, rest, declInit]() { lref = createLRef(rest->_argument, declInit); }); } auto *A = Builder.createAllocArrayInst({}, 0); auto *n = Builder.createAllocStackInst(genAnonymousLabelName("n")); // n = 0. Builder.createStoreStackInst(Builder.getLiteralPositiveZero(), n); Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock); // notDoneBlock: Builder.setInsertionBlock(notDoneBlock); auto *stepValue = emitIteratorNext(iteratorRecord); auto *stepDone = emitIteratorComplete(iteratorRecord); Builder.createStoreStackInst(stepDone, iteratorDone); Builder.createCondBranchInst(stepDone, doneBlock, newValueBlock); // newValueBlock: Builder.setInsertionBlock(newValueBlock); auto *nVal = Builder.createLoadStackInst(n); nVal->setType(Type::createNumber()); // A[n] = stepValue; // Unfortunately this can throw because our arrays can have limited range. // The spec doesn't specify what to do in this case, but the reasonable thing // to do is to what we would if this was a for-of loop doing the same thing. // See section BindingRestElement:...BindingIdentifier, step f and g: // https://www.ecma-international.org/ecma-262/9.0/index.html#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization emitTryWithSharedHandler(handler, [this, stepValue, A, nVal]() { Builder.createStorePropertyInst(stepValue, A, nVal); }); // ++n; auto add = Builder.createBinaryOperatorInst( nVal, Builder.getLiteralNumber(1), BinaryOperatorInst::OpKind::AddKind); add->setType(Type::createNumber()); Builder.createStoreStackInst(add, n); Builder.createBranchInst(notDoneBlock); // doneBlock: Builder.setInsertionBlock(doneBlock); if (lref->canStoreWithoutSideEffects()) { lref->emitStore(A); } else { emitTryWithSharedHandler(handler, [&lref, A]() { lref->emitStore(A); }); } } void ESTreeIRGen::emitDestructuringObject( bool declInit, ESTree::ObjectPatternNode *target, Value *source) { // Keep track of which keys have been destructured. llvh::SmallVector<Value *, 4> excludedItems{}; if (target->_properties.empty() || llvh::isa<ESTree::RestElementNode>(target->_properties.front())) { // ES10.0 13.3.3.5 // 1. Perform ? RequireObjectCoercible(value). // The extremely unlikely case that the user is attempting to destructure // into {} or {...rest}. Any other object destructuring will fail upon // attempting to retrieve a real property from `source`. // We must check that the source can be destructured, // and the only time this will throw is if source is undefined or null. auto *throwBB = Builder.createBasicBlock(Builder.getFunction()); auto *doneBB = Builder.createBasicBlock(Builder.getFunction()); // Use == instead of === to account for both undefined and null. Builder.createCondBranchInst( Builder.createBinaryOperatorInst( source, Builder.getLiteralNull(), BinaryOperatorInst::OpKind::EqualKind), throwBB, doneBB); Builder.setInsertionBlock(throwBB); genBuiltinCall( BuiltinMethod::HermesBuiltin_throwTypeError, {source, Builder.getLiteralString( "Cannot destructure 'undefined' or 'null'.")}); // throwTypeError will always throw. // This return is here to ensure well-formed IR, and will not run. Builder.createReturnInst(Builder.getLiteralUndefined()); Builder.setInsertionBlock(doneBB); } for (auto &elem : target->_properties) { if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(&elem)) { emitRestProperty(declInit, rest, excludedItems, source); break; } auto *propNode = cast<ESTree::PropertyNode>(&elem); ESTree::Node *valueNode = propNode->_value; ESTree::Node *init = nullptr; // If we have an initializer, unwrap it. if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(valueNode)) { valueNode = assign->_left; init = assign->_right; } Identifier nameHint = llvh::isa<ESTree::IdentifierNode>(valueNode) ? getNameFieldFromID(valueNode) : Identifier{}; if (llvh::isa<ESTree::IdentifierNode>(propNode->_key) && !propNode->_computed) { Identifier key = getNameFieldFromID(propNode->_key); excludedItems.push_back(Builder.getLiteralString(key)); auto *loadedValue = Builder.createLoadPropertyInst(source, key); createLRef(valueNode, declInit) .emitStore(emitOptionalInitialization(loadedValue, init, nameHint)); } else { Value *key = genExpression(propNode->_key); excludedItems.push_back(key); auto *loadedValue = Builder.createLoadPropertyInst(source, key); createLRef(valueNode, declInit) .emitStore(emitOptionalInitialization(loadedValue, init, nameHint)); } } } void ESTreeIRGen::emitRestProperty( bool declInit, ESTree::RestElementNode *rest, const llvh::SmallVectorImpl<Value *> &excludedItems, hermes::Value *source) { auto lref = createLRef(rest->_argument, declInit); // Construct the excluded items. HBCAllocObjectFromBufferInst::ObjectPropertyMap exMap{}; llvh::SmallVector<Value *, 4> computedExcludedItems{}; // Keys need de-duping so we don't create a dummy exclusion object with // duplicate keys. llvh::DenseSet<Literal *> keyDeDupeSet; auto *zeroValue = Builder.getLiteralPositiveZero(); for (Value *key : excludedItems) { if (auto *lit = llvh::dyn_cast<Literal>(key)) { // If the key is a literal, we can place it in the // HBCAllocObjectFromBufferInst buffer. if (keyDeDupeSet.insert(lit).second) { exMap.emplace_back(std::make_pair(lit, zeroValue)); } } else { // If the key is not a literal, then we have to dynamically populate the // excluded object with it after creation from the buffer. computedExcludedItems.push_back(key); } } Value *excludedObj; if (excludedItems.empty()) { excludedObj = Builder.getLiteralUndefined(); } else { // This size is only a hint as the true size may change if there are // duplicates when computedExcludedItems is processed at run-time. auto excludedSizeHint = exMap.size() + computedExcludedItems.size(); if (exMap.empty()) { excludedObj = Builder.createAllocObjectInst(excludedSizeHint); } else { excludedObj = Builder.createHBCAllocObjectFromBufferInst(exMap, excludedSizeHint); } for (Value *key : computedExcludedItems) { Builder.createStorePropertyInst(zeroValue, excludedObj, key); } } auto *restValue = genBuiltinCall( BuiltinMethod::HermesBuiltin_copyDataProperties, {Builder.createAllocObjectInst(0), source, excludedObj}); lref.emitStore(restValue); } Value *ESTreeIRGen::emitOptionalInitialization( Value *value, ESTree::Node *init, Identifier nameHint) { if (!init) return value; auto *currentBlock = Builder.getInsertionBlock(); auto *getDefaultBlock = Builder.createBasicBlock(Builder.getFunction()); auto *storeBlock = Builder.createBasicBlock(Builder.getFunction()); // if (value !== undefined) goto storeBlock [if initializer present] // value = initializer [if initializer present] // storeBlock: Builder.createCondBranchInst( Builder.createBinaryOperatorInst( value, Builder.getLiteralUndefined(), BinaryOperatorInst::OpKind::StrictlyNotEqualKind), storeBlock, getDefaultBlock); // getDefaultBlock: Builder.setInsertionBlock(getDefaultBlock); auto *defaultValue = genExpression(init, nameHint); auto *defaultResultBlock = Builder.getInsertionBlock(); Builder.createBranchInst(storeBlock); // storeBlock: Builder.setInsertionBlock(storeBlock); return Builder.createPhiInst( {value, defaultValue}, {currentBlock, defaultResultBlock}); } std::shared_ptr<SerializedScope> ESTreeIRGen::resolveScopeIdentifiers( const ScopeChain &chain) { std::shared_ptr<SerializedScope> current{}; for (auto it = chain.functions.rbegin(), end = chain.functions.rend(); it < end; it++) { auto next = std::make_shared<SerializedScope>(); next->variables.reserve(it->variables.size()); for (auto var : it->variables) { next->variables.push_back(std::move(Builder.createIdentifier(var))); } next->parentScope = current; current = next; } return current; } void ESTreeIRGen::materializeScopesInChain( Function *wrapperFunction, const std::shared_ptr<const SerializedScope> &scope, int depth) { if (!scope) return; assert(depth < 1000 && "Excessive scope depth"); // First materialize parent scopes. materializeScopesInChain(wrapperFunction, scope->parentScope, depth - 1); // If scope->closureAlias is specified, we must create an alias binding // between originalName (which must be valid) and the variable identified by // closureAlias. // // We do this *before* inserting the other variables below to reflect that // the closure alias is conceptually in an outside scope and also avoid the // closure name incorrectly shadowing the same name inside the closure. if (scope->closureAlias.isValid()) { assert(scope->originalName.isValid() && "Original name invalid"); assert( scope->originalName != scope->closureAlias && "Original name must be different from the alias"); // NOTE: the closureAlias target must exist and must be a Variable. auto *closureVar = cast<Variable>(nameTable_.lookup(scope->closureAlias)); // Re-create the alias. nameTable_.insert(scope->originalName, closureVar); } // Create an external scope. ExternalScope *ES = Builder.createExternalScope(wrapperFunction, depth); for (auto variableId : scope->variables) { auto *variable = Builder.createVariable(ES, Variable::DeclKind::Var, variableId); nameTable_.insert(variableId, variable); } } namespace { void buildDummyLexicalParent( IRBuilder &builder, Function *parent, Function *child) { // FunctionScopeAnalysis works through CreateFunctionInsts, so we have to add // that even though these functions are never invoked. auto *block = builder.createBasicBlock(parent); builder.setInsertionBlock(block); builder.createUnreachableInst(); auto *inst = builder.createCreateFunctionInst(child); builder.createReturnInst(inst); } } // namespace /// Add dummy functions for lexical scope debug info. // They are never executed and serve no purpose other than filling in debug // info. This is currently necessary because we can't rely on parent bytecode // modules for lexical scoping data. void ESTreeIRGen::addLexicalDebugInfo( Function *child, Function *global, const std::shared_ptr<const SerializedScope> &scope) { if (!scope || !scope->parentScope) { buildDummyLexicalParent(Builder, global, child); return; } auto *current = Builder.createFunction( scope->originalName, Function::DefinitionKind::ES5Function, false, {}, false); for (auto &var : scope->variables) { Builder.createVariable( current->getFunctionScope(), Variable::DeclKind::Var, var); } buildDummyLexicalParent(Builder, current, child); addLexicalDebugInfo(current, global, scope->parentScope); } std::shared_ptr<SerializedScope> ESTreeIRGen::serializeScope( FunctionContext *ctx, bool includeGlobal) { // Serialize the global scope if and only if it's the only scope. // We serialize the global scope to avoid re-declaring variables, // and only do it once to avoid creating spurious scopes. if (!ctx || (ctx->function->isGlobalScope() && !includeGlobal)) return lexicalScopeChain; auto scope = std::make_shared<SerializedScope>(); auto *func = ctx->function; assert(func && "Missing function when saving scope"); scope->originalName = func->getOriginalOrInferredName(); if (auto *closure = func->getLazyClosureAlias()) { scope->closureAlias = closure->getName(); } for (auto *var : func->getFunctionScope()->getVariables()) { scope->variables.push_back(var->getName()); } scope->parentScope = serializeScope(ctx->getPreviousContext(), false); return scope; } } // namespace irgen } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_4256_4
crossvul-cpp_data_bad_3390_0
// validat1.cpp - originally written and placed in the public domain by Wei Dai // CryptoPP::Test namespace added by JW in February 2017 #include "pch.h" #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 #include "cryptlib.h" #include "pubkey.h" #include "gfpcrypt.h" #include "eccrypto.h" #include "filters.h" #include "files.h" #include "hex.h" #include "base32.h" #include "base64.h" #include "modes.h" #include "cbcmac.h" #include "dmac.h" #include "idea.h" #include "des.h" #include "rc2.h" #include "arc4.h" #include "rc5.h" #include "blowfish.h" #include "3way.h" #include "safer.h" #include "gost.h" #include "shark.h" #include "cast.h" #include "square.h" #include "seal.h" #include "rc6.h" #include "mars.h" #include "aes.h" #include "cpu.h" #include "rng.h" #include "rijndael.h" #include "twofish.h" #include "serpent.h" #include "skipjack.h" #include "shacal2.h" #include "camellia.h" #include "aria.h" #include "osrng.h" #include "drbg.h" #include "rdrand.h" #include "mersenne.h" #include "randpool.h" #include "zdeflate.h" #include "smartptr.h" #include "channels.h" #include "misc.h" #include <time.h> #include <memory> #include <iostream> #include <iomanip> #include "validate.h" // Aggressive stack checking with VS2005 SP1 and above. #if (CRYPTOPP_MSC_VERSION >= 1410) # pragma strict_gs_check (on) #endif NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(Test) bool ValidateAll(bool thorough) { bool pass=TestSettings(); pass=TestOS_RNG() && pass; pass=TestRandomPool() && pass; #if !defined(NO_OS_DEPENDENCE) pass=TestAutoSeededX917() && pass; #endif // pass=TestSecRandom() && pass; #if defined(CRYPTOPP_EXTENDED_VALIDATION) pass=TestMersenne() && pass; #endif #if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64) pass=TestRDRAND() && pass; pass=TestRDSEED() && pass; #endif #if defined(CRYPTOPP_EXTENDED_VALIDATION) // http://github.com/weidai11/cryptopp/issues/92 pass=TestSecBlock() && pass; // http://github.com/weidai11/cryptopp/issues/336 pass=TestIntegerBitops() && pass; // http://github.com/weidai11/cryptopp/issues/64 pass=TestPolynomialMod2() && pass; // http://github.com/weidai11/cryptopp/issues/360 pass=TestRounding() && pass; // http://github.com/weidai11/cryptopp/issues/242 pass=TestHuffmanCodes() && pass; // http://github.com/weidai11/cryptopp/issues/346 pass=TestASN1Parse() && pass; // Additional tests due to no coverage pass=ValidateBaseCode() && pass; pass=TestCompressors() && pass; pass=TestSharing() && pass; pass=TestEncryptors() && pass; #endif pass=ValidateCRC32() && pass; pass=ValidateCRC32C() && pass; pass=ValidateAdler32() && pass; pass=ValidateMD2() && pass; #if defined(CRYPTOPP_EXTENDED_VALIDATION) pass=ValidateMD4() && pass; #endif pass=ValidateMD5() && pass; pass=ValidateSHA() && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/keccak.txt") && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/sha3.txt") && pass; pass=ValidateHashDRBG() && pass; pass=ValidateHmacDRBG() && pass; pass=ValidateTiger() && pass; pass=ValidateRIPEMD() && pass; pass=ValidatePanama() && pass; pass=ValidateWhirlpool() && pass; pass=ValidateBLAKE2s() && pass; pass=ValidateBLAKE2b() && pass; pass=ValidatePoly1305() && pass; pass=ValidateSipHash() && pass; pass=ValidateHMAC() && pass; pass=ValidateTTMAC() && pass; pass=ValidatePBKDF() && pass; pass=ValidateHKDF() && pass; pass=ValidateDES() && pass; pass=ValidateCipherModes() && pass; pass=ValidateIDEA() && pass; pass=ValidateSAFER() && pass; pass=ValidateRC2() && pass; pass=ValidateARC4() && pass; pass=ValidateRC5() && pass; pass=ValidateBlowfish() && pass; pass=ValidateThreeWay() && pass; pass=ValidateGOST() && pass; pass=ValidateSHARK() && pass; pass=ValidateCAST() && pass; pass=ValidateSquare() && pass; pass=ValidateSKIPJACK() && pass; pass=ValidateSEAL() && pass; pass=ValidateRC6() && pass; pass=ValidateMARS() && pass; pass=ValidateRijndael() && pass; pass=ValidateTwofish() && pass; pass=ValidateSerpent() && pass; pass=ValidateSHACAL2() && pass; pass=ValidateARIA() && pass; pass=ValidateCamellia() && pass; pass=ValidateSalsa() && pass; pass=ValidateSosemanuk() && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/seed.txt") && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/kalyna.txt") && pass; pass=ValidateVMAC() && pass; pass=ValidateCCM() && pass; pass=ValidateGCM() && pass; pass=ValidateCMAC() && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/eax.txt") && pass; pass=ValidateBBS() && pass; pass=ValidateDH() && pass; pass=ValidateMQV() && pass; pass=ValidateHMQV() && pass; pass=ValidateFHMQV() && pass; pass=ValidateRSA() && pass; pass=ValidateElGamal() && pass; pass=ValidateDLIES() && pass; pass=ValidateNR() && pass; pass=ValidateDSA(thorough) && pass; pass=ValidateLUC() && pass; pass=ValidateLUC_DH() && pass; pass=ValidateLUC_DL() && pass; pass=ValidateXTR_DH() && pass; pass=ValidateRabin() && pass; pass=ValidateRW() && pass; // pass=ValidateBlumGoldwasser() && pass; pass=ValidateECP() && pass; pass=ValidateEC2N() && pass; pass=ValidateECDSA() && pass; pass=ValidateECGDSA() && pass; pass=ValidateESIGN() && pass; if (pass) std::cout << "\nAll tests passed!\n"; else std::cout << "\nOops! Not all tests passed.\n"; return pass; } bool TestSettings() { bool pass = true; std::cout << "\nTesting Settings...\n\n"; word32 w; const byte s[] = "\x01\x02\x03\x04"; #if (CRYPTOPP_MSC_VERSION >= 1410) std::copy(s, s+4, stdext::make_checked_array_iterator(reinterpret_cast<byte*>(&w), sizeof(w))); #else std::copy(s, s+4, reinterpret_cast<byte*>(&w)); #endif if (w == 0x04030201L) { #ifdef IS_LITTLE_ENDIAN std::cout << "passed: "; #else std::cout << "FAILED: "; pass = false; #endif std::cout << "Your machine is little endian.\n"; } else if (w == 0x01020304L) { #ifndef IS_LITTLE_ENDIAN std::cout << "passed: "; #else std::cout << "FAILED: "; pass = false; #endif std::cout << "Your machine is big endian.\n"; } else { std::cout << "FAILED: Your machine is neither big endian nor little endian.\n"; pass = false; } #if defined(CRYPTOPP_EXTENDED_VALIDATION) // App and library versions, http://github.com/weidai11/cryptopp/issues/371 const int v1 = LibraryVersion(); const int v2 = HeaderVersion(); if(v1/10 == v2/10) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "Library version (library): " << v1 << ", header version (app): " << v2 << "\n"; #endif #ifdef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS // Don't assert the alignment of testvals. That's what this test is for. byte testvals[10] = {1,2,2,3,3,3,3,2,2,1}; if (*(word32 *)(void *)(testvals+3) == 0x03030303 && *(word64 *)(void *)(testvals+1) == W64LIT(0x0202030303030202)) std::cout << "passed: Your machine allows unaligned data access.\n"; else { std::cout << "FAILED: Unaligned data access gave incorrect results.\n"; pass = false; } #else std::cout << "passed: CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS is not defined. Will restrict to aligned data access.\n"; #endif if (sizeof(byte) == 1) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(byte) == " << sizeof(byte) << std::endl; if (sizeof(word16) == 2) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word16) == " << sizeof(word16) << std::endl; if (sizeof(word32) == 4) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word32) == " << sizeof(word32) << std::endl; if (sizeof(word64) == 8) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word64) == " << sizeof(word64) << std::endl; #ifdef CRYPTOPP_WORD128_AVAILABLE if (sizeof(word128) == 16) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word128) == " << sizeof(word128) << std::endl; #endif if (sizeof(word) == 2*sizeof(hword) #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE && sizeof(dword) == 2*sizeof(word) #endif ) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(hword) == " << sizeof(hword) << ", sizeof(word) == " << sizeof(word); #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE std::cout << ", sizeof(dword) == " << sizeof(dword); #endif std::cout << std::endl; #ifdef CRYPTOPP_CPUID_AVAILABLE bool hasMMX = HasMMX(); bool hasISSE = HasISSE(); bool hasSSE2 = HasSSE2(); bool hasSSSE3 = HasSSSE3(); bool hasSSE4 = HasSSE4(); bool isP4 = IsP4(); int cacheLineSize = GetCacheLineSize(); if ((isP4 && (!hasMMX || !hasSSE2)) || (hasSSE2 && !hasMMX) || (cacheLineSize < 16 || cacheLineSize > 256 || !IsPowerOf2(cacheLineSize))) { std::cout << "FAILED: "; pass = false; } else std::cout << "passed: "; std::cout << "hasMMX == " << hasMMX << ", hasISSE == " << hasISSE << ", hasSSE2 == " << hasSSE2 << ", hasSSSE3 == " << hasSSSE3 << ", hasSSE4 == " << hasSSE4; std::cout << ", hasAESNI == " << HasAESNI() << ", hasCLMUL == " << HasCLMUL() << ", hasRDRAND == " << HasRDRAND() << ", hasRDSEED == " << HasRDSEED(); std::cout << ", hasSHA == " << HasSHA() << ", isP4 == " << isP4 << ", cacheLineSize == " << cacheLineSize << std::endl; #elif (CRYPTOPP_BOOL_ARM32 || CRYPTOPP_BOOL_ARM64) bool hasNEON = HasNEON(); bool hasPMULL = HasPMULL(); bool hasCRC32 = HasCRC32(); bool hasAES = HasAES(); bool hasSHA1 = HasSHA1(); bool hasSHA2 = HasSHA2(); std::cout << "passed: "; std::cout << "hasNEON == " << hasNEON << ", hasPMULL == " << hasPMULL << ", hasCRC32 == " << hasCRC32 << ", hasAES == " << hasAES << ", hasSHA1 == " << hasSHA1 << ", hasSHA2 == " << hasSHA2 << std::endl; #endif if (!pass) { std::cout << "Some critical setting in config.h is in error. Please fix it and recompile." << std::endl; abort(); } return pass; } bool TestOS_RNG() { bool pass = true; member_ptr<RandomNumberGenerator> rng; #ifdef BLOCKING_RNG_AVAILABLE try {rng.reset(new BlockingRng);} catch (const OS_RNG_Err &) {} #endif if (rng.get()) { std::cout << "\nTesting operating system provided blocking random number generator...\n\n"; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(*rng, UINT_MAX, false, new Deflator(new Redirector(meter))); unsigned long total=0, length=0; time_t t = time(NULLPTR), t1 = 0; CRYPTOPP_UNUSED(length); // check that it doesn't take too long to generate a reasonable amount of randomness while (total < 16 && (t1 < 10 || total*8 > (unsigned long)t1)) { test.Pump(1); total += 1; t1 = time(NULLPTR) - t; } if (total < 16) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " it took " << long(t1) << " seconds to generate " << total << " bytes" << std::endl; #if 0 // disable this part. it's causing an unpredictable pause during the validation testing if (t1 < 2) { // that was fast, are we really blocking? // first exhaust the extropy reserve t = time(NULLPTR); while (time(NULLPTR) - t < 2) { test.Pump(1); total += 1; } // if it generates too many bytes in a certain amount of time, // something's probably wrong t = time(NULLPTR); while (time(NULLPTR) - t < 2) { test.Pump(1); total += 1; length += 1; } if (length > 1024) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " it generated " << length << " bytes in " << long(time(NULLPTR) - t) << " seconds" << std::endl; } #endif test.AttachedTransformation()->MessageEnd(); if (meter.GetTotalBytes() < total) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " " << total << " generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { // Miscellaneous for code coverage RandomNumberGenerator& prng = *rng.get(); (void)prng.AlgorithmName(); word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 0); pass = true; } catch (const Exception&) { pass = false; } if (!pass) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "\nNo operating system provided blocking random number generator, skipping test." << std::endl; rng.reset(NULLPTR); #ifdef NONBLOCKING_RNG_AVAILABLE try {rng.reset(new NonblockingRng);} catch (OS_RNG_Err &) {} #endif if (rng.get()) { std::cout << "\nTesting operating system provided nonblocking random number generator...\n\n"; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(*rng, 100000, true, new Deflator(new Redirector(meter))); if (meter.GetTotalBytes() < 100000) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { // Miscellaneous for code coverage RandomNumberGenerator& prng = *rng.get(); (void)prng.AlgorithmName(); word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 0); pass = true; } catch (const Exception&) { pass = false; } if (!pass) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "\nNo operating system provided nonblocking random number generator, skipping test." << std::endl; return pass; } bool TestRandomPool() { std::cout << "\nTesting RandomPool generator...\n\n"; bool pass=true, fail; { RandomPool prng; static const unsigned int ENTROPY_SIZE = 32; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes" << std::endl; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)prng.AlgorithmName(); // "unknown" word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } #if !defined(NO_OS_DEPENDENCE) std::cout << "\nTesting AutoSeeded RandomPool generator...\n\n"; { AutoSeededRandomPool prng; static const unsigned int ENTROPY_SIZE = 32; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes" << std::endl; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage fail = false; (void)prng.AlgorithmName(); // "unknown" word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } #endif std::cout.flush(); return pass; } #if !defined(NO_OS_DEPENDENCE) bool TestAutoSeededX917() { // This tests Auto-Seeding and GenerateIntoBufferedTransformation. std::cout << "\nTesting AutoSeeded X917 generator...\n\n"; AutoSeededX917RNG<AES> prng; bool pass = true, fail; static const unsigned int ENTROPY_SIZE = 32; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes" << std::endl; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage fail = false; (void)prng.AlgorithmName(); // "unknown" word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; std::cout.flush(); return pass; } #endif #if defined(CRYPTOPP_EXTENDED_VALIDATION) bool TestMersenne() { std::cout << "\nTesting Mersenne Twister...\n\n"; static const unsigned int ENTROPY_SIZE = 32; bool pass = true, fail = false; // First 10; http://create.stephan-brumme.com/mersenne-twister/ word32 result[10], expected[10] = {0xD091BB5C, 0x22AE9EF6, 0xE7E1FAEE, 0xD5C31F79, 0x2082352C, 0xF807B7DF, 0xE9D30005, 0x3895AFE1, 0xA1E24BBA, 0x4EE4092B}; MT19937ar prng; prng.GenerateBlock(reinterpret_cast<byte*>(result), sizeof(result)); fail = (0 != ::memcmp(result, expected, sizeof(expected))); pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " Expected sequence from MT19937ar (2002 version)\n"; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes\n"; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)prng.AlgorithmName(); word32 temp = prng.GenerateWord32(); temp = prng.GenerateWord32((temp & 0xff), 0xffffffff - (temp & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 1); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 0); fail = false; } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; std::cout.flush(); return pass; } #endif #if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64) bool TestRDRAND() { std::cout << "\nTesting RDRAND generator...\n\n"; bool pass = true, fail = false; member_ptr<RandomNumberGenerator> rng; try {rng.reset(new RDRAND);} catch (const RDRAND_Err &) {} if (rng.get()) { RDRAND& rdrand = dynamic_cast<RDRAND&>(*rng.get()); static const unsigned int SIZE = 10000; MeterFilter meter(new Redirector(TheBitBucket())); Deflator deflator(new Redirector(meter)); MaurerRandomnessTest maurer; ChannelSwitch chsw; chsw.AddDefaultRoute(deflator); chsw.AddDefaultRoute(maurer); RandomNumberSource rns(rdrand, SIZE, true, new Redirector(chsw)); deflator.Flush(true); CRYPTOPP_ASSERT(0 == maurer.BytesNeeded()); const double mv = maurer.GetTestValue(); if (mv < 0.98f) fail = true; // Coverity finding, also see http://stackoverflow.com/a/34509163/608639. StreamState ss(std::cout); std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(6); pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " Maurer Randomness Test returned value " << mv << "\n"; fail = false; if (meter.GetTotalBytes() < SIZE) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " " << SIZE << " generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; rdrand.DiscardBytes(SIZE); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded " << SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)rdrand.AlgorithmName(); (void)rdrand.CanIncorporateEntropy(); rdrand.IncorporateEntropy(NULLPTR, 0); word32 result = rdrand.GenerateWord32(); result = rdrand.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 4); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 3); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 2); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 1); fail = false; } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "RDRAND generator not available, skipping test.\n"; std::cout.flush(); return pass; } #endif #if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64) bool TestRDSEED() { std::cout << "\nTesting RDSEED generator...\n\n"; bool pass = true, fail = false; member_ptr<RandomNumberGenerator> rng; try {rng.reset(new RDSEED);} catch (const RDSEED_Err &) {} if (rng.get()) { RDSEED& rdseed = dynamic_cast<RDSEED&>(*rng.get()); static const unsigned int SIZE = 10000; MeterFilter meter(new Redirector(TheBitBucket())); Deflator deflator(new Redirector(meter)); MaurerRandomnessTest maurer; ChannelSwitch chsw; chsw.AddDefaultRoute(deflator); chsw.AddDefaultRoute(maurer); RandomNumberSource rns(rdseed, SIZE, true, new Redirector(chsw)); deflator.Flush(true); CRYPTOPP_ASSERT(0 == maurer.BytesNeeded()); const double mv = maurer.GetTestValue(); if (mv < 0.98f) fail = true; // Coverity finding, also see http://stackoverflow.com/a/34509163/608639. StreamState ss(std::cout); std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(6); pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " Maurer Randomness Test returned value " << mv << "\n"; fail = false; if (meter.GetTotalBytes() < SIZE) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " " << SIZE << " generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; rdseed.DiscardBytes(SIZE); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded " << SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)rdseed.AlgorithmName(); (void)rdseed.CanIncorporateEntropy(); rdseed.IncorporateEntropy(NULLPTR, 0); word32 result = rdseed.GenerateWord32(); result = rdseed.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 4); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 3); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 2); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 1); fail = false; } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "RDSEED generator not available, skipping test.\n"; std::cout.flush(); return pass; } #endif bool ValidateHashDRBG() { std::cout << "\nTesting NIST Hash DRBGs...\n\n"; bool pass=true, fail; // # CAVS 14.3 // # DRBG800-90A information for "drbg_pr" // # Generated on Tue Apr 02 15:32:09 2013 { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x16\x10\xb8\x28\xcc\xd2\x7d\xe0\x8c\xee\xa0\x32\xa2\x0e\x92\x08"; const byte entropy2[] = "\x72\xd2\x8c\x90\x8e\xda\xf9\xa4\xd1\xe5\x26\xd8\xf2\xde\xd5\x44"; const byte nonce[] = "\x49\x2c\xf1\x70\x92\x42\xf6\xb5"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\x56\xF3\x3D\x4F\xDB\xB9\xA5\xB6\x4D\x26\x23\x44\x97\xE9\xDC\xB8\x77\x98\xC6\x8D" "\x08\xF7\xC4\x11\x99\xD4\xBD\xDF\x97\xEB\xBF\x6C\xB5\x55\x0E\x5D\x14\x9F\xF4\xD5" "\xBD\x0F\x05\xF2\x5A\x69\x88\xC1\x74\x36\x39\x62\x27\x18\x4A\xF8\x4A\x56\x43\x35" "\x65\x8E\x2F\x85\x72\xBE\xA3\x33\xEE\xE2\xAB\xFF\x22\xFF\xA6\xDE\x3E\x22\xAC\xA2"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (COUNT=0, E=16, N=8)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x55\x08\x75\xb7\x4e\xc1\x1f\x90\x67\x78\xa3\x1a\x37\xa3\x29\xfd"; const byte entropy2[] = "\x96\xc6\x39\xec\x14\x9f\x6b\x28\xe2\x79\x3b\xb9\x37\x9e\x60\x67"; const byte nonce[] = "\x08\xdd\x8c\xd3\x5b\xfa\x00\x94"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\xEE\x44\xC6\xCF\x2C\x0C\x73\xA8\xAC\x4C\xA5\x6C\x0E\x71\x2C\xA5\x50\x9A\x19\x5D" "\xE4\x5B\x8D\x2B\xC9\x40\xA7\xDB\x66\xC3\xEB\x2A\xA1\xBD\xB4\xDD\x76\x85\x12\x45" "\x80\x2E\x68\x05\x4A\xAB\xA8\x7C\xD6\x3A\xD3\xE5\xC9\x7C\x06\xE7\xA3\x9F\xF6\xF9" "\x8E\xB3\xD9\x72\xD4\x11\x35\xE5\xE7\x46\x1B\x49\x9C\x56\x45\x6A\xBE\x7F\x77\xD4"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (COUNT=1, E=16, N=8)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 128], [ReturnedBitsLen = 640] const byte entropy1[] = "\xd9\xba\xb5\xce\xdc\xa9\x6f\x61\x78\xd6\x45\x09\xa0\xdf\xdc\x5e"; const byte entropy2[] = "\xc6\xba\xd0\x74\xc5\x90\x67\x86\xf5\xe1\xf3\x20\x99\xf5\xb4\x91"; const byte nonce[] = "\xda\xd8\x98\x94\x14\x45\x0e\x01"; const byte additional1[] = "\x3e\x6b\xf4\x6f\x4d\xaa\x38\x25\xd7\x19\x4e\x69\x4e\x77\x52\xf7"; const byte additional2[] = "\x04\xfa\x28\x95\xaa\x5a\x6f\x8c\x57\x43\x34\x3b\x80\x5e\x5e\xa4"; const byte additional3[] = "\xdf\x5d\xc4\x59\xdf\xf0\x2a\xa2\xf0\x52\xd7\x21\xec\x60\x72\x30"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\xC4\x8B\x89\xF9\xDA\x3F\x74\x82\x45\x55\x5D\x5D\x03\x3B\x69\x3D\xD7\x1A\x4D\xF5" "\x69\x02\x05\xCE\xFC\xD7\x20\x11\x3C\xC2\x4E\x09\x89\x36\xFF\x5E\x77\xB5\x41\x53" "\x58\x70\xB3\x39\x46\x8C\xDD\x8D\x6F\xAF\x8C\x56\x16\x3A\x70\x0A\x75\xB2\x3E\x59" "\x9B\x5A\xEC\xF1\x6F\x3B\xAF\x6D\x5F\x24\x19\x97\x1F\x24\xF4\x46\x72\x0F\xEA\xBE"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=0, E=16, N=8, A=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 128], [ReturnedBitsLen = 640] const byte entropy1[] = "\x28\x00\x0f\xbf\xf0\x57\x22\xc8\x89\x93\x06\xc2\x9b\x50\x78\x0a"; const byte entropy2[] = "\xd9\x95\x8e\x8c\x08\xaf\x5a\x41\x0e\x91\x9b\xdf\x40\x8e\x5a\x0a"; const byte nonce[] = "\x11\x2f\x6e\x20\xc0\x29\xed\x3f"; const byte additional1[] = "\x91\x1d\x96\x5b\x6e\x77\xa9\x6c\xfe\x3f\xf2\xd2\xe3\x0e\x2a\x86"; const byte additional2[] = "\xcd\x44\xd9\x96\xab\x05\xef\xe8\x27\xd3\x65\x83\xf1\x43\x18\x2c"; const byte additional3[] = "\x9f\x6a\x31\x82\x12\x18\x4e\x70\xaf\x5d\x00\x14\x1f\x42\x82\xf6"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\x54\x61\x65\x92\x1E\x71\x4A\xD1\x39\x02\x2F\x97\xD2\x65\x3F\x0D\x47\x69\xB1\x4A" "\x3E\x6E\xEF\xA1\xA0\x16\xD6\x9E\xA9\x7F\x51\xD5\x81\xDC\xAA\xCF\x66\xF9\xB1\xE8" "\x06\x94\x41\xD6\xB5\xC5\x44\x60\x54\x07\xE8\xE7\xDC\x1C\xD8\xE4\x70\xAD\x84\x77" "\x5A\x65\x31\xBE\xE0\xFC\x81\x36\xE2\x8F\x0B\xFE\xEB\xE1\x98\x62\x7E\x98\xE0\xC1"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=1, E=16, N=8, A=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x0e\xd5\x4c\xef\x44\x5c\x61\x7d\x58\x86\xe0\x34\xc0\x97\x36\xd4"; const byte entropy2[] = "\x0b\x90\x27\xb8\x01\xe7\xf7\x2e\xe6\xec\x50\x2b\x8b\x6b\xd7\x11"; const byte nonce[] = "\x2c\x8b\x07\x13\x55\x6c\x91\x6f"; const byte personalization[] = "\xf3\x37\x8e\xa1\x45\x34\x30\x41\x12\xe0\xee\x57\xe9\xb3\x4a\x4b"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\x55\x37\x0E\xD4\xB7\xCA\xA4\xBB\x67\x3A\x0F\x58\x40\xB3\x9F\x76\x4E\xDA\xD2\x85" "\xD5\x6F\x01\x8F\x2D\xA7\x54\x4B\x0E\x66\x39\x62\x35\x96\x1D\xB7\xF6\xDA\xFB\x30" "\xB6\xC5\x68\xD8\x40\x6E\x2B\xD4\x3D\x23\xEB\x0F\x10\xBA\x5F\x24\x9C\xC9\xE9\x4A" "\xD3\xA5\xF1\xDF\xA4\xF2\xB4\x80\x40\x91\xED\x8C\xD6\x6D\xE7\xB7\x53\xB2\x09\xD5"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=0, E=16, N=8, A=0, P=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x8f\x2a\x33\x9f\x5f\x45\x21\x30\xa4\x57\xa9\x6f\xcb\xe2\xe6\x36"; const byte entropy2[] = "\x1f\xff\x9e\x4f\x4d\x66\x3a\x1f\x9e\x85\x4a\x15\x7d\xad\x97\xe0"; const byte nonce[] = "\x0e\xd0\xe9\xa5\xa4\x54\x8a\xd0"; const byte personalization[] = "\x45\xe4\xb3\xe2\x63\x87\x62\x57\x2c\x99\xe4\x03\x45\xd6\x32\x6f"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\x4F\xE8\x96\x41\xF8\xD3\x95\xC4\x43\x6E\xFB\xF8\x05\x75\xA7\x69\x74\x6E\x0C\x5F" "\x54\x14\x35\xB4\xE6\xA6\xB3\x40\x7C\xA2\xC4\x42\xA2\x2F\x66\x28\x28\xCF\x4A\xA8" "\xDC\x16\xBC\x5F\x69\xE5\xBB\x05\xD1\x43\x8F\x80\xAB\xC5\x8F\x9C\x3F\x75\x57\xEB" "\x44\x0D\xF5\x0C\xF4\x95\x23\x94\x67\x11\x55\x98\x14\x43\xFF\x13\x14\x85\x5A\xBC"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=1, E=16, N=8, A=0, P=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x48\xa1\xa9\x7c\xcc\x49\xd7\xcc\xf6\xe3\x78\xa2\xf1\x6b\x0f\xcd"; const byte entropy2[] = "\xba\x5d\xa6\x79\x12\x37\x24\x3f\xea\x60\x50\xf5\xb9\x9e\xcd\xf5"; const byte nonce[] = "\xb0\x91\xd2\xec\x12\xa8\x39\xfe"; const byte personalization[] = "\x3d\xc1\x6c\x1a\xdd\x9c\xac\x4e\xbb\xb0\xb8\x89\xe4\x3b\x9e\x12"; const byte additional1[] = "\xd1\x23\xe3\x8e\x4c\x97\xe8\x29\x94\xa9\x71\x7a\xc6\xf1\x7c\x08"; const byte additional2[] = "\x80\x0b\xed\x97\x29\xcf\xad\xe6\x68\x0d\xfe\x53\xba\x0c\x1e\x28"; const byte additional3[] = "\x25\x1e\x66\xb9\xe3\x85\xac\x1c\x17\xfb\x77\x1b\x5d\xc7\x6c\xf2"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\xA1\xB2\xEE\x86\xA0\xF1\xDA\xB7\x93\x83\x13\x3A\x62\x27\x99\x08\x95\x3A\x1C\x9A" "\x98\x77\x60\x12\x11\x19\xCC\x78\xB8\x51\x2B\xD5\x37\xA1\x9D\xB9\x73\xCA\x39\x7A" "\xDD\x92\x33\x78\x6D\x5D\x41\xFF\xFA\xE9\x80\x59\x04\x85\x21\xE2\x52\x84\xBC\x6F" "\xDB\x97\xF3\x4E\x6A\x12\x7A\xCD\x41\x0F\x50\x68\x28\x46\xBE\x56\x9E\x9A\x6B\xC8"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=0, E=16, N=8, A=16, P=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x3b\xcb\xa8\x3b\x6d\xfb\x06\x79\x80\xef\xc3\x1e\xd2\x9e\x68\x57"; const byte entropy2[] = "\x2f\xc9\x87\x49\x19\xcb\x52\x4a\x5b\xac\xf0\xcd\x96\x4e\xf8\x6e"; const byte nonce[] = "\x23\xfe\x20\x9f\xac\x70\x45\xde"; const byte personalization[] = "\xf2\x25\xf4\xd9\x6b\x9c\xab\x49\x1e\xab\x18\x14\xb2\x5e\x78\xef"; const byte additional1[] = "\x57\x5b\x9a\x11\x32\x7a\xab\x89\x08\xfe\x46\x11\x9a\xed\x14\x5d"; const byte additional2[] = "\x5d\x19\xcd\xed\xb7\xe3\x44\x66\x8e\x11\x42\x96\xa0\x38\xb1\x7f"; const byte additional3[] = "\x2b\xaf\xa0\x15\xed\xdd\x5c\x76\x32\x75\x34\x35\xd1\x37\x72\xfb"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\x1D\x12\xEB\x6D\x42\x60\xBD\xFB\xA7\x99\xB8\x53\xCC\x6F\x19\xB1\x64\xFE\x2F\x55" "\xBA\xA2\x1C\x89\xD4\xD0\xE9\xB4\xBA\xD4\xE5\xF8\xC5\x30\x06\x41\xBA\xC4\x3D\x2B" "\x73\x91\x27\xE9\x31\xC0\x55\x55\x11\xE8\xB6\x57\x02\x0D\xCE\x90\xAC\x31\xB9\x00" "\x31\xC1\xD4\x4F\xE7\x12\x3B\xCC\x85\x16\x2F\x12\x8F\xB2\xDF\x84\x4E\xF7\x06\xBE"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=1, E=16, N=8, A=16, P=16)\n"; } { // [SHA-256], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 1024] const byte entropy1[] = "\xf0\x5b\xab\x56\xc7\xac\x6e\xeb\x31\xa0\xcf\x8a\x8a\x06\x2a\x49\x17\x9a\xcf\x3c\x5b\x20\x4d\x60\xdd\x7a\x3e\xb7\x8f\x5d\x8e\x3b"; const byte entropy2[] = "\x72\xd4\x02\xa2\x59\x7b\x98\xa3\xb8\xf5\x0b\x71\x6c\x63\xc6\xdb\xa7\x3a\x07\xe6\x54\x89\x06\x3f\x02\xc5\x32\xf5\xda\xc4\xd4\x18"; const byte nonce[] = "\xa1\x45\x08\x53\x41\x68\xb6\x88\xf0\x5f\x1e\x41\x9c\x88\xcc\x30"; const byte personalization[] = "\xa0\x34\x72\xf4\x04\x59\xe2\x87\xea\xcb\x21\x32\xc0\xb6\x54\x02\x7d\xa3\xe6\x69\x25\xb4\x21\x25\x54\xc4\x48\x18\x8c\x0e\x86\x01"; const byte additional1[] = "\xb3\x0d\x28\xaf\xa4\x11\x6b\xbc\x13\x6e\x65\x09\xb5\x82\xa6\x93\xbc\x91\x71\x40\x46\xaa\x3c\x66\xb6\x77\xb3\xef\xf9\xad\xfd\x49"; const byte additional2[] = "\x77\xfd\x1d\x68\xd6\xa4\xdd\xd5\xf3\x27\x25\x2d\x3f\x6b\xdf\xee\x8c\x35\xce\xd3\x83\xbe\xaf\xc9\x32\x77\xef\xf2\x1b\x6f\xf4\x1b"; const byte additional3[] = "\x59\xa0\x1f\xf8\x6a\x58\x72\x1e\x85\xd2\xf8\x3f\x73\x99\xf1\x96\x4e\x27\xf8\x7f\xcd\x1b\xf5\xc1\xeb\xf3\x37\x10\x9b\x13\xbd\x24"; Hash_DRBG<SHA256, 128/8, 440/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(128); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\xFF\x27\x96\x38\x5C\x32\xBF\x84\x3D\xFA\xBB\xF0\x3E\x70\x5A\x39\xCB\xA3\x4C\xF1" "\x4F\xAE\xC3\x05\x63\xDF\x5A\xDD\xBD\x2D\x35\x83\xF5\x7E\x05\xF9\x40\x30\x56\x18" "\xF2\x00\x88\x14\x03\xC2\xD9\x81\x36\x39\xE6\x67\x55\xDC\xFC\x4E\x88\xEA\x71\xDD" "\xB2\x25\x2E\x09\x91\x49\x40\xEB\xE2\x3D\x63\x44\xA0\xF4\xDB\x5E\xE8\x39\xE6\x70" "\xEC\x47\x24\x3F\xA0\xFC\xF5\x13\x61\xCE\x53\x98\xAA\xBF\xB4\x19\x1B\xFE\xD5\x00" "\xE1\x03\x3A\x76\x54\xFF\xD7\x24\x70\x5E\x8C\xB2\x41\x7D\x92\x0A\x2F\x4F\x27\xB8" "\x45\x13\x7F\xFB\x87\x90\xA9\x49"; fail = !!memcmp(result, expected, 1024/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA256/128/440 (C0UNT=0, E=32, N=16, A=32, P=32)\n"; } { // [SHA-256], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 1024] const byte entropy1[] = "\xfe\x61\x50\x79\xf1\xad\x2a\x71\xea\x7f\x0f\x5a\x14\x34\xee\xc8\x46\x35\x54\x4a\x95\x6a\x4f\xbd\x64\xff\xba\xf6\x1d\x34\x61\x83"; const byte entropy2[] = "\x18\x89\x7b\xd8\x3e\xff\x38\xab\xb5\x6e\x82\xa8\x1b\x8c\x5e\x59\x3c\x3d\x85\x62\x2a\xe2\x88\xe5\xb2\xc6\xc5\xd2\xad\x7d\xc9\x45"; const byte nonce[] = "\x9d\xa7\x87\x56\xb7\x49\x17\x02\x4c\xd2\x00\x65\x11\x9b\xe8\x7e"; const byte personalization[] = "\x77\x5d\xbf\x32\xf3\x5c\xf3\x51\xf4\xb8\x1c\xd3\xfa\x7f\x65\x0b\xcf\x31\x88\xa1\x25\x57\x0c\xdd\xac\xaa\xfe\xa1\x7b\x3b\x29\xbc"; const byte additional1[] = "\xef\x96\xc7\x9c\xb1\x73\x1d\x82\x85\x0a\x6b\xca\x9b\x5c\x34\x39\xba\xd3\x4e\x4d\x82\x6f\x35\x9f\x61\x5c\xf6\xf2\xa3\x3e\x91\x05"; const byte additional2[] = "\xaf\x25\xc4\x6e\x21\xfc\xc3\xaf\x1f\xbb\xf8\x76\xb4\x57\xab\x1a\x94\x0a\x85\x16\x47\x81\xa4\xab\xda\xc8\xab\xca\xd0\x84\xda\xae"; const byte additional3[] = "\x59\x5b\x44\x94\x38\x86\x36\xff\x8e\x45\x1a\x0c\x42\xc8\xcc\x21\x06\x38\x3a\xc5\xa6\x30\x96\xb9\x14\x81\xb3\xa1\x2b\xc8\xcd\xf6"; Hash_DRBG<SHA256, 128/8, 440/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(128); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\x8B\x1C\x9C\x76\xC4\x9B\x3B\xAE\xFD\x6E\xEB\x6C\xFF\xA3\xA1\x03\x3A\x8C\xAF\x09" "\xFE\xBD\x44\x00\xFC\x0F\xD3\xA8\x26\x9C\xEE\x01\xAC\xE3\x73\x0E\xBE\xDA\x9A\xC6" "\x23\x44\x6D\xA1\x56\x94\x29\xEC\x4B\xCD\x01\x84\x32\x25\xEF\x00\x91\x0B\xCC\xF3" "\x06\x3B\x80\xF5\x46\xAC\xD2\xED\x5F\x70\x2B\x56\x2F\x21\x0A\xE9\x80\x87\x38\xAD" "\xB0\x2A\xEB\x27\xF2\xD9\x20\x2A\x66\x0E\xF5\xC9\x20\x4A\xB4\x3C\xCE\xD6\x24\x97" "\xDB\xB1\xED\x94\x12\x6A\x2F\x03\x98\x4A\xD4\xD1\x72\xF3\x7A\x66\x74\x7E\x2A\x5B" "\xDE\xEF\x43\xBC\xB9\x8C\x49\x01"; fail = !!memcmp(result, expected, 1024/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA256/128/440 (C0UNT=1, E=32, N=16, A=32, P=32)\n"; } { // [SHA-512], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 2048] const byte entropy1[] = "\x55\x4e\x8f\xfd\xc4\x9a\xd8\xf9\x9a\xe5\xd5\xf8\x1a\xf5\xda\xfb\x7f\x75\x53\xd7\xcb\x56\x8e\xa7\x3c\xc0\x82\xdd\x80\x76\x25\xc0"; const byte entropy2[] = "\x78\x07\x3e\x86\x79\x4b\x10\x95\x88\xf4\x22\xf9\xbd\x04\x7e\xc0\xce\xab\xd6\x78\x6b\xdf\xe2\x89\xb3\x16\x43\x9c\x32\x2d\xb2\x59"; const byte nonce[] = "\xf0\x89\x78\xde\x2d\xc2\xcd\xd9\xc0\xfd\x3d\x84\xd9\x8b\x8e\x8e"; const byte personalization[] = "\x3e\x52\x7a\xb5\x81\x2b\x0c\x0e\x98\x2a\x95\x78\x93\x98\xd9\xeb\xf1\xb9\xeb\xd6\x1d\x02\x05\xed\x42\x21\x2d\x24\xb8\x37\xf8\x41"; const byte additional1[] = "\xf2\x6b\xb1\xef\x30\xca\x8f\x97\xc0\x19\xd0\x79\xe5\xc6\x5e\xae\xd1\xa3\x9a\x52\xaf\x12\xe8\x28\xde\x03\x70\x79\x9a\x70\x11\x8b"; const byte additional2[] = "\xb0\x9d\xb5\xa8\x45\xec\x79\x7a\x4b\x60\x7e\xe4\xd5\x58\x56\x70\x35\x20\x9b\xd8\xe5\x01\x6c\x78\xff\x1f\x6b\x93\xbf\x7c\x34\xca"; const byte additional3[] = "\x45\x92\x2f\xb3\x5a\xd0\x6a\x84\x5f\xc9\xca\x16\x4a\x42\xbb\x59\x84\xb4\x38\x57\xa9\x16\x23\x48\xf0\x2f\x51\x61\x24\x35\xb8\x62"; Hash_DRBG<SHA512, 256/8, 888/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(256); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\x1F\x20\x83\x9E\x22\x55\x3B\x1E\x6C\xD4\xF6\x3A\x47\xC3\x99\x54\x0F\x69\xA3\xBB" "\x37\x47\xA0\x2A\x12\xAC\xC7\x00\x85\xC5\xCC\xF4\x7B\x12\x5A\x4A\xEA\xED\x2F\xE5" "\x31\x51\x0D\xC1\x8E\x50\x29\xE2\xA6\xCB\x8F\x34\xBA\xDA\x8B\x47\x32\x33\x81\xF1" "\x2D\xF6\x8B\x73\x8C\xFF\x15\xC8\x8E\x8C\x31\x48\xFA\xC3\xC4\x9F\x52\x81\x23\xC2" "\x2A\x83\xBD\xF1\x44\xEF\x15\x49\x93\x44\x83\x6B\x37\x5D\xBB\xFF\x72\xD2\x86\x96" "\x62\xF8\x4D\x12\x3B\x16\xCB\xAC\xA1\x00\x12\x1F\x94\xA8\xD5\xAE\x9A\x9E\xDA\xC8" "\xD7\x6D\x59\x33\xFD\x55\xC9\xCC\x5B\xAD\x39\x73\xB5\x13\x8B\x96\xDF\xDB\xF5\x90" "\x81\xDF\x68\x6A\x30\x72\x42\xF2\x74\xAE\x7F\x1F\x7F\xFE\x8B\x3D\x49\x38\x98\x34" "\x7C\x63\x46\x6E\xAF\xFA\xCB\x06\x06\x08\xE6\xC8\x35\x3C\x68\xB8\xCC\x9D\x5C\xDF" "\xDB\xC0\x41\x44\x48\xE6\x11\xD4\x78\x50\x81\x91\xED\x1D\x75\xF3\xBD\x79\xFF\x1E" "\x37\xAF\xC6\x5D\x49\xD6\x5C\xAC\x5B\xCB\xD6\x91\x37\x51\xFA\x98\x70\xFC\x32\xB3" "\xF2\x86\xE4\xED\x74\xF2\x5D\x8B\x6C\x4D\xB8\xDE\xD8\x4A\xD6\x5E\xD6\x6D\xAE\xB1" "\x1B\xA2\x94\x52\x54\xAD\x3C\x3D\x25\xBD\x12\x46\x3C\xA0\x45\x9D"; fail = !!memcmp(result, expected, 2048/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA512/256/888 (C0UNT=0, E=32, N=16, A=32, P=32)\n"; } { // [SHA-512], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 2048] const byte entropy1[] = "\x0c\x9f\xcd\x06\x21\x3c\xb2\xf6\x3c\xdf\x79\x76\x4b\x46\x74\xfc\xdf\x68\xb0\xff\xae\xc7\x21\x8a\xa2\xaf\x4e\x4c\xb9\xe6\x60\x78"; const byte entropy2[] = "\x75\xb8\x49\x54\xdf\x30\x10\x16\x2c\x06\x8c\x12\xeb\x6c\x1d\x03\x64\x5c\xad\x10\x5c\xc3\x17\x69\xb2\x5a\xc1\x7c\xb8\x33\x5b\x45"; const byte nonce[] = "\x43\x1c\x4d\x65\x93\x96\xad\xdc\xc1\x6d\x17\x9f\x7f\x57\x24\x4d"; const byte personalization[] = "\x7e\x54\xbd\x87\xd2\x0a\x95\xd7\xc4\x0c\x3b\x1b\x32\x15\x26\xd2\x06\x67\xa4\xac\xc1\xaa\xfb\x55\x91\x68\x2c\xb5\xc9\xcd\x66\x05"; const byte additional1[] = "\xd5\x74\x9e\x56\xfb\x5f\xf3\xf8\x2c\x73\x2b\x7a\x83\xe0\xde\x06\x85\x0b\xf0\x57\x50\xc8\x55\x60\x4a\x41\x4f\x86\xb1\x68\x14\x03"; const byte additional2[] = "\x9a\x83\xbb\x06\xdf\x4d\x53\x89\xf5\x3f\x24\xff\xf7\xcd\x0c\xcf\x4f\xbe\x46\x79\x8e\xce\x82\xa8\xc4\x6b\x5f\x8e\x58\x32\x62\x23"; const byte additional3[] = "\x48\x13\xc4\x95\x10\x99\xdd\x7f\xd4\x77\x3c\x9b\x8a\xa4\x1c\x3d\xb0\x93\x92\x50\xba\x23\x98\xef\x4b\x1b\xd2\x53\xc1\x61\xda\xc6"; Hash_DRBG<SHA512, 256/8, 888/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(256); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\xE1\x7E\x4B\xEE\xD1\x65\x4F\xB2\xFC\xC8\xE8\xD7\xC6\x72\x7D\xD2\xE3\x15\x73\xC0" "\x23\xC8\x55\x5D\x2B\xD8\x28\xD8\x31\xE4\xC9\x87\x42\x51\x87\x66\x43\x1F\x2C\xA4" "\x73\xED\x4E\x50\x12\xC4\x50\x0E\x4C\xDD\x14\x73\xA2\xFB\xB3\x07\x0C\x66\x97\x4D" "\x89\xDE\x35\x1C\x93\xE7\xE6\x8F\x20\x3D\x84\xE6\x73\x46\x0F\x7C\xF4\x3B\x6C\x02" "\x23\x7C\x79\x6C\x86\xD9\x48\x80\x9C\x34\xCB\xA1\x23\xE7\xF7\x8A\x2E\x4B\x9D\x39" "\xA5\x86\x1A\x73\x58\x28\x5A\x1D\x8D\x4A\xBD\x42\xD5\x49\x2B\xDF\x53\x1D\xE7\x4A" "\x5F\x74\x09\x7F\xDC\x29\x7D\x58\x9C\x4B\xC5\x2F\x3B\x8F\xBF\x56\xCA\x48\x0A\x74" "\xAE\xFF\xDD\x12\xE4\xF6\xAB\x83\x26\x4F\x52\x8A\x19\xBB\x91\x32\xA4\x42\xEC\x4F" "\x3C\x76\xED\x9F\x03\xAA\x5E\x53\x79\x4C\xD0\x06\xD2\x1A\x42\x9D\xB1\xA7\xEC\xF7" "\x5B\xD4\x03\x70\x1E\xF2\x47\x26\x48\xAC\x35\xEE\xD0\x58\x40\x94\x8C\x11\xD0\xEB" "\x77\x39\x5A\xA3\xD5\xD0\xD3\xC3\x68\xE1\x75\xAA\xC0\x44\xEA\xD8\xDD\x13\x3F\xF9" "\x7D\x21\x14\x34\xA5\x87\x43\xA4\x0A\x96\x77\x00\xCC\xCA\xB1\xDA\xC4\x39\xE0\x66" "\x37\x05\x6E\xAC\xF2\xE6\xC6\xC5\x4F\x79\xD3\xE5\x6A\x3D\x36\x3F"; fail = !!memcmp(result, expected, 2048/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA512/256/888 (C0UNT=1, E=32, N=16, A=32, P=32)\n"; } return pass; } bool ValidateHmacDRBG() { std::cout << "\nTesting NIST HMAC DRBGs...\n\n"; bool pass=true, fail; // # CAVS 14.3 // # DRBG800-90A information for "drbg_pr" // # Generated on Tue Apr 02 15:32:12 2013 { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x79\x34\x9b\xbf\x7c\xdd\xa5\x79\x95\x57\x86\x66\x21\xc9\x13\x83"; const byte entropy2[] = "\xc7\x21\x5b\x5b\x96\xc4\x8e\x9b\x33\x8c\x74\xe3\xe9\x9d\xfe\xdf"; const byte nonce[] = "\x11\x46\x73\x3a\xbf\x8c\x35\xc8"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\xc6\xa1\x6a\xb8\xd4\x20\x70\x6f\x0f\x34\xab\x7f\xec\x5a\xdc\xa9\xd8\xca\x3a\x13" "\x3e\x15\x9c\xa6\xac\x43\xc6\xf8\xa2\xbe\x22\x83\x4a\x4c\x0a\x0a\xff\xb1\x0d\x71" "\x94\xf1\xc1\xa5\xcf\x73\x22\xec\x1a\xe0\x96\x4e\xd4\xbf\x12\x27\x46\xe0\x87\xfd" "\xb5\xb3\xe9\x1b\x34\x93\xd5\xbb\x98\xfa\xed\x49\xe8\x5f\x13\x0f\xc8\xa4\x59\xb7"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=0, E=16, N=8)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\xee\x57\xfc\x23\x60\x0f\xb9\x02\x9a\x9e\xc6\xc8\x2e\x7b\x51\xe4"; const byte entropy2[] = "\x84\x1d\x27\x6c\xa9\x51\x90\x61\xd9\x2d\x7d\xdf\xa6\x62\x8c\xa3"; const byte nonce[] = "\x3e\x97\x21\xe4\x39\x3e\xf9\xad"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\xee\x26\xa5\xc8\xef\x08\xa1\xca\x8f\x14\x15\x4d\x67\xc8\x8f\x5e\x7e\xd8\x21\x9d" "\x93\x1b\x98\x42\xac\x00\x39\xf2\x14\x55\x39\xf2\x14\x2b\x44\x11\x7a\x99\x8c\x22" "\xf5\x90\xf6\xc9\xb3\x8b\x46\x5b\x78\x3e\xcf\xf1\x3a\x77\x50\x20\x1f\x7e\xcf\x1b" "\x8a\xb3\x93\x60\x4c\x73\xb2\x38\x93\x36\x60\x9a\xf3\x44\x0c\xde\x43\x29\x8b\x84"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=1, E=16, N=8)\n"; } // ***************************************************** { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x7d\x70\x52\xa7\x76\xfd\x2f\xb3\xd7\x19\x1f\x73\x33\x04\xee\x8b"; const byte entropy2[] = "\x49\x04\x7e\x87\x9d\x61\x09\x55\xee\xd9\x16\xe4\x06\x0e\x00\xc9"; const byte nonce[] = "\xbe\x4a\x0c\xee\xdc\xa8\x02\x07"; const byte additional1[] = "\xfd\x8b\xb3\x3a\xab\x2f\x6c\xdf\xbc\x54\x18\x11\x86\x1d\x51\x8d"; const byte additional2[] = "\x99\xaf\xe3\x47\x54\x04\x61\xdd\xf6\xab\xeb\x49\x1e\x07\x15\xb4"; const byte additional3[] = "\x02\xf7\x73\x48\x2d\xd7\xae\x66\xf7\x6e\x38\x15\x98\xa6\x4e\xf0"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\xa7\x36\x34\x38\x44\xfc\x92\x51\x13\x91\xdb\x0a\xdd\xd9\x06\x4d\xbe\xe2\x4c\x89" "\x76\xaa\x25\x9a\x9e\x3b\x63\x68\xaa\x6d\xe4\xc9\xbf\x3a\x0e\xff\xcd\xa9\xcb\x0e" "\x9d\xc3\x36\x52\xab\x58\xec\xb7\x65\x0e\xd8\x04\x67\xf7\x6a\x84\x9f\xb1\xcf\xc1" "\xed\x0a\x09\xf7\x15\x50\x86\x06\x4d\xb3\x24\xb1\xe1\x24\xf3\xfc\x9e\x61\x4f\xcb"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=0, E=16, N=8, A=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x29\xc6\x2a\xfa\x3c\x52\x20\x8a\x3f\xde\xcb\x43\xfa\x61\x3f\x15"; const byte entropy2[] = "\xbd\x87\xbe\x99\xd1\x84\x16\x54\x12\x31\x41\x40\xd4\x02\x71\x41"; const byte nonce[] = "\x6c\x9e\xb5\x9a\xc3\xc2\xd4\x8b"; const byte additional1[] = "\x43\x3d\xda\xf2\x59\xd1\x4b\xcf\x89\x76\x30\xcc\xaa\x27\x33\x8c"; const byte additional2[] = "\x14\x11\x46\xd4\x04\xf2\x84\xc2\xd0\x2b\x6a\x10\x15\x6e\x33\x82"; const byte additional3[] = "\xed\xc3\x43\xdb\xff\xe7\x1a\xb4\x11\x4a\xc3\x63\x9d\x44\x5b\x65"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\x8c\x73\x0f\x05\x26\x69\x4d\x5a\x9a\x45\xdb\xab\x05\x7a\x19\x75\x35\x7d\x65\xaf" "\xd3\xef\xf3\x03\x32\x0b\xd1\x40\x61\xf9\xad\x38\x75\x91\x02\xb6\xc6\x01\x16\xf6" "\xdb\x7a\x6e\x8e\x7a\xb9\x4c\x05\x50\x0b\x4d\x1e\x35\x7d\xf8\xe9\x57\xac\x89\x37" "\xb0\x5f\xb3\xd0\x80\xa0\xf9\x06\x74\xd4\x4d\xe1\xbd\x6f\x94\xd2\x95\xc4\x51\x9d"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=1, E=16, N=8, A=16)\n"; } return pass; } class CipherFactory { public: virtual unsigned int BlockSize() const =0; virtual unsigned int KeyLength() const =0; virtual BlockTransformation* NewEncryption(const byte *keyStr) const =0; virtual BlockTransformation* NewDecryption(const byte *keyStr) const =0; }; template <class E, class D> class FixedRoundsCipherFactory : public CipherFactory { public: FixedRoundsCipherFactory(unsigned int keylen=0) : m_keylen(keylen?keylen:E::DEFAULT_KEYLENGTH) {} unsigned int BlockSize() const {return E::BLOCKSIZE;} unsigned int KeyLength() const {return m_keylen;} BlockTransformation* NewEncryption(const byte *keyStr) const {return new E(keyStr, m_keylen);} BlockTransformation* NewDecryption(const byte *keyStr) const {return new D(keyStr, m_keylen);} unsigned int m_keylen; }; template <class E, class D> class VariableRoundsCipherFactory : public CipherFactory { public: VariableRoundsCipherFactory(unsigned int keylen=0, unsigned int rounds=0) : m_keylen(keylen ? keylen : E::DEFAULT_KEYLENGTH), m_rounds(rounds ? rounds : E::DEFAULT_ROUNDS) {} unsigned int BlockSize() const {return E::BLOCKSIZE;} unsigned int KeyLength() const {return m_keylen;} BlockTransformation* NewEncryption(const byte *keyStr) const {return new E(keyStr, m_keylen, m_rounds);} BlockTransformation* NewDecryption(const byte *keyStr) const {return new D(keyStr, m_keylen, m_rounds);} unsigned int m_keylen, m_rounds; }; bool BlockTransformationTest(const CipherFactory &cg, BufferedTransformation &valdata, unsigned int tuples = 0xffff) { HexEncoder output(new FileSink(std::cout)); SecByteBlock plain(cg.BlockSize()), cipher(cg.BlockSize()), out(cg.BlockSize()), outplain(cg.BlockSize()); SecByteBlock key(cg.KeyLength()); bool pass=true, fail; while (valdata.MaxRetrievable() && tuples--) { valdata.Get(key, cg.KeyLength()); valdata.Get(plain, cg.BlockSize()); valdata.Get(cipher, cg.BlockSize()); member_ptr<BlockTransformation> transE(cg.NewEncryption(key)); transE->ProcessBlock(plain, out); fail = memcmp(out, cipher, cg.BlockSize()) != 0; member_ptr<BlockTransformation> transD(cg.NewDecryption(key)); transD->ProcessBlock(out, outplain); fail=fail || memcmp(outplain, plain, cg.BlockSize()); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed "); output.Put(key, cg.KeyLength()); std::cout << " "; output.Put(outplain, cg.BlockSize()); std::cout << " "; output.Put(out, cg.BlockSize()); std::cout << std::endl; } return pass; } class FilterTester : public Unflushable<Sink> { public: FilterTester(const byte *validOutput, size_t outputLen) : validOutput(validOutput), outputLen(outputLen), counter(0), fail(false) {} void PutByte(byte inByte) { if (counter >= outputLen || validOutput[counter] != inByte) { std::cerr << "incorrect output " << counter << ", " << (word16)validOutput[counter] << ", " << (word16)inByte << "\n"; fail = true; CRYPTOPP_ASSERT(false); } counter++; } size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) { CRYPTOPP_UNUSED(messageEnd), CRYPTOPP_UNUSED(blocking); while (length--) FilterTester::PutByte(*inString++); if (messageEnd) if (counter != outputLen) { fail = true; CRYPTOPP_ASSERT(false); } return 0; } bool GetResult() { return !fail; } const byte *validOutput; size_t outputLen, counter; bool fail; }; bool TestFilter(BufferedTransformation &bt, const byte *in, size_t inLen, const byte *out, size_t outLen) { FilterTester *ft; bt.Attach(ft = new FilterTester(out, outLen)); while (inLen) { size_t randomLen = GlobalRNG().GenerateWord32(0, (word32)inLen); bt.Put(in, randomLen); in += randomLen; inLen -= randomLen; } bt.MessageEnd(); return ft->GetResult(); } bool ValidateDES() { std::cout << "\nDES validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/descert.dat", true, new HexDecoder); bool pass = BlockTransformationTest(FixedRoundsCipherFactory<DESEncryption, DESDecryption>(), valdata); std::cout << "\nTesting EDE2, EDE3, and XEX3 variants...\n\n"; FileSource valdata1(CRYPTOPP_DATA_DIR "TestData/3desval.dat", true, new HexDecoder); pass = BlockTransformationTest(FixedRoundsCipherFactory<DES_EDE2_Encryption, DES_EDE2_Decryption>(), valdata1, 1) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<DES_EDE3_Encryption, DES_EDE3_Decryption>(), valdata1, 1) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<DES_XEX3_Encryption, DES_XEX3_Decryption>(), valdata1, 1) && pass; return pass; } bool TestModeIV(SymmetricCipher &e, SymmetricCipher &d) { SecByteBlock lastIV, iv(e.IVSize()); StreamTransformationFilter filter(e, new StreamTransformationFilter(d)); // Enterprise Analysis finding on the stack based array const int BUF_SIZE=20480U; AlignedSecByteBlock plaintext(BUF_SIZE); for (unsigned int i=1; i<20480; i*=2) { e.GetNextIV(GlobalRNG(), iv); if (iv == lastIV) return false; else lastIV = iv; e.Resynchronize(iv); d.Resynchronize(iv); unsigned int length = STDMAX(GlobalRNG().GenerateWord32(0, i), (word32)e.MinLastBlockSize()); GlobalRNG().GenerateBlock(plaintext, length); if (!TestFilter(filter, plaintext, length, plaintext, length)) return false; } return true; } bool ValidateCipherModes() { std::cout << "\nTesting DES modes...\n\n"; const byte key[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; const byte iv[] = {0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef}; const byte plain[] = { // "Now is the time for all " without tailing 0 0x4e,0x6f,0x77,0x20,0x69,0x73,0x20,0x74, 0x68,0x65,0x20,0x74,0x69,0x6d,0x65,0x20, 0x66,0x6f,0x72,0x20,0x61,0x6c,0x6c,0x20}; DESEncryption desE(key); DESDecryption desD(key); bool pass=true, fail; { // from FIPS 81 const byte encrypted[] = { 0x3f, 0xa4, 0x0e, 0x8a, 0x98, 0x4d, 0x48, 0x15, 0x6a, 0x27, 0x17, 0x87, 0xab, 0x88, 0x83, 0xf9, 0x89, 0x3d, 0x51, 0xec, 0x4b, 0x56, 0x3b, 0x53}; ECB_Mode_ExternalCipher::Encryption modeE(desE); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "ECB encryption" << std::endl; ECB_Mode_ExternalCipher::Decryption modeD(desD); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "ECB decryption" << std::endl; } { // from FIPS 81 const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with no padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with no padding" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC mode IV generation" << std::endl; } { // generated with Crypto++, matches FIPS 81 // but has extra 8 bytes as result of padding const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6, 0x62, 0xC1, 0x6A, 0x27, 0xE4, 0xFC, 0xF2, 0x77}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with PKCS #7 padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with PKCS #7 padding" << std::endl; } { // generated with Crypto++ 5.2, matches FIPS 81 // but has extra 8 bytes as result of padding const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6, 0xcf, 0xb7, 0xc7, 0x64, 0x0e, 0x7c, 0xd9, 0xa7}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::ONE_AND_ZEROS_PADDING).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with one-and-zeros padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::ONE_AND_ZEROS_PADDING).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with one-and-zeros padding" << std::endl; } { const byte plain_1[] = {'a', 0, 0, 0, 0, 0, 0, 0}; // generated with Crypto++ const byte encrypted[] = { 0x9B, 0x47, 0x57, 0x59, 0xD6, 0x9C, 0xF6, 0xD0}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::ZEROS_PADDING).Ref(), plain_1, 1, encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with zeros padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::ZEROS_PADDING).Ref(), encrypted, sizeof(encrypted), plain_1, sizeof(plain_1)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with zeros padding" << std::endl; } { // generated with Crypto++, matches FIPS 81 // but with last two blocks swapped as result of CTS const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F}; CBC_CTS_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with ciphertext stealing (CTS)" << std::endl; CBC_CTS_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with ciphertext stealing (CTS)" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC CTS IV generation" << std::endl; } { // generated with Crypto++ const byte decryptionIV[] = {0x4D, 0xD0, 0xAC, 0x8F, 0x47, 0xCF, 0x79, 0xCE}; const byte encrypted[] = {0x12, 0x34, 0x56}; byte stolenIV[8]; CBC_CTS_Mode_ExternalCipher::Encryption modeE(desE, iv); modeE.SetStolenIV(stolenIV); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, 3, encrypted, sizeof(encrypted)); fail = memcmp(stolenIV, decryptionIV, 8) != 0 || fail; pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with ciphertext and IV stealing" << std::endl; CBC_CTS_Mode_ExternalCipher::Decryption modeD(desD, stolenIV); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, 3); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with ciphertext and IV stealing" << std::endl; } { const byte encrypted[] = { // from FIPS 81 0xF3,0x09,0x62,0x49,0xC7,0xF4,0x6E,0x51, 0xA6,0x9E,0x83,0x9B,0x1A,0x92,0xF7,0x84, 0x03,0x46,0x71,0x33,0x89,0x8E,0xA6,0x22}; CFB_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB encryption" << std::endl; CFB_Mode_ExternalCipher::Decryption modeD(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB mode IV generation" << std::endl; } { const byte plain_2[] = { // "Now is the." without tailing 0 0x4e,0x6f,0x77,0x20,0x69,0x73,0x20,0x74,0x68,0x65}; const byte encrypted[] = { // from FIPS 81 0xf3,0x1f,0xda,0x07,0x01,0x14,0x62,0xee,0x18,0x7f}; CFB_Mode_ExternalCipher::Encryption modeE(desE, iv, 1); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain_2, sizeof(plain_2), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB (8-bit feedback) encryption" << std::endl; CFB_Mode_ExternalCipher::Decryption modeD(desE, iv, 1); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain_2, sizeof(plain_2)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB (8-bit feedback) decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB (8-bit feedback) IV generation" << std::endl; } { const byte encrypted[] = { // from Eric Young's libdes 0xf3,0x09,0x62,0x49,0xc7,0xf4,0x6e,0x51, 0x35,0xf2,0x4a,0x24,0x2e,0xeb,0x3d,0x3f, 0x3d,0x6d,0x5b,0xe3,0x25,0x5a,0xf8,0xc3}; OFB_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "OFB encryption" << std::endl; OFB_Mode_ExternalCipher::Decryption modeD(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "OFB decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "OFB IV generation" << std::endl; } { const byte encrypted[] = { // generated with Crypto++ 0xF3, 0x09, 0x62, 0x49, 0xC7, 0xF4, 0x6E, 0x51, 0x16, 0x3A, 0x8C, 0xA0, 0xFF, 0xC9, 0x4C, 0x27, 0xFA, 0x2F, 0x80, 0xF4, 0x80, 0xB8, 0x6F, 0x75}; CTR_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "Counter Mode encryption" << std::endl; CTR_Mode_ExternalCipher::Decryption modeD(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "Counter Mode decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "Counter Mode IV generation" << std::endl; } { const byte plain_3[] = { // "7654321 Now is the time for " 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x20, 0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20}; const byte mac1[] = { // from FIPS 113 0xf1, 0xd3, 0x0f, 0x68, 0x49, 0x31, 0x2c, 0xa4}; const byte mac2[] = { // generated with Crypto++ 0x35, 0x80, 0xC5, 0xC4, 0x6B, 0x81, 0x24, 0xE2}; CBC_MAC<DES> cbcmac(key); HashFilter cbcmacFilter(cbcmac); fail = !TestFilter(cbcmacFilter, plain_3, sizeof(plain_3), mac1, sizeof(mac1)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC MAC" << std::endl; DMAC<DES> dmac(key); HashFilter dmacFilter(dmac); fail = !TestFilter(dmacFilter, plain_3, sizeof(plain_3), mac2, sizeof(mac2)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "DMAC" << std::endl; } { CTR_Mode<AES>::Encryption modeE(plain, 16, plain); CTR_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES CTR Mode" << std::endl; } { OFB_Mode<AES>::Encryption modeE(plain, 16, plain); OFB_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES OFB Mode" << std::endl; } { CFB_Mode<AES>::Encryption modeE(plain, 16, plain); CFB_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES CFB Mode" << std::endl; } { CBC_Mode<AES>::Encryption modeE(plain, 16, plain); CBC_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES CBC Mode" << std::endl; } return pass; } bool ValidateIDEA() { std::cout << "\nIDEA validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/ideaval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<IDEAEncryption, IDEADecryption>(), valdata); } bool ValidateSAFER() { std::cout << "\nSAFER validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/saferval.dat", true, new HexDecoder); bool pass = true; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_K_Encryption, SAFER_K_Decryption>(8,6), valdata, 4) && pass; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_K_Encryption, SAFER_K_Decryption>(16,12), valdata, 4) && pass; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_SK_Encryption, SAFER_SK_Decryption>(8,6), valdata, 4) && pass; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_SK_Encryption, SAFER_SK_Decryption>(16,10), valdata, 4) && pass; return pass; } bool ValidateRC2() { std::cout << "\nRC2 validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rc2val.dat", true, new HexDecoder); HexEncoder output(new FileSink(std::cout)); SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE); SecByteBlock key(128); bool pass=true, fail; while (valdata.MaxRetrievable()) { byte keyLen, effectiveLen; valdata.Get(keyLen); valdata.Get(effectiveLen); valdata.Get(key, keyLen); valdata.Get(plain, RC2Encryption::BLOCKSIZE); valdata.Get(cipher, RC2Encryption::BLOCKSIZE); member_ptr<BlockTransformation> transE(new RC2Encryption(key, keyLen, effectiveLen)); transE->ProcessBlock(plain, out); fail = memcmp(out, cipher, RC2Encryption::BLOCKSIZE) != 0; member_ptr<BlockTransformation> transD(new RC2Decryption(key, keyLen, effectiveLen)); transD->ProcessBlock(out, outplain); fail=fail || memcmp(outplain, plain, RC2Encryption::BLOCKSIZE); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed "); output.Put(key, keyLen); std::cout << " "; output.Put(outplain, RC2Encryption::BLOCKSIZE); std::cout << " "; output.Put(out, RC2Encryption::BLOCKSIZE); std::cout << std::endl; } return pass; } bool ValidateARC4() { unsigned char Key0[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef }; unsigned char Input0[]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; unsigned char Output0[] = {0x75,0xb7,0x87,0x80,0x99,0xe0,0xc5,0x96}; unsigned char Key1[]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; unsigned char Input1[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Output1[]={0x74,0x94,0xc2,0xe7,0x10,0x4b,0x08,0x79}; unsigned char Key2[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Input2[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Output2[]={0xde,0x18,0x89,0x41,0xa3,0x37,0x5d,0x3a}; unsigned char Key3[]={0xef,0x01,0x23,0x45}; unsigned char Input3[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Output3[]={0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,0xbd,0x61}; unsigned char Key4[]={ 0x01,0x23,0x45,0x67,0x89,0xab, 0xcd,0xef }; unsigned char Input4[] = {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01}; unsigned char Output4[]= { 0x75,0x95,0xc3,0xe6,0x11,0x4a,0x09,0x78,0x0c,0x4a,0xd4, 0x52,0x33,0x8e,0x1f,0xfd,0x9a,0x1b,0xe9,0x49,0x8f, 0x81,0x3d,0x76,0x53,0x34,0x49,0xb6,0x77,0x8d,0xca, 0xd8,0xc7,0x8a,0x8d,0x2b,0xa9,0xac,0x66,0x08,0x5d, 0x0e,0x53,0xd5,0x9c,0x26,0xc2,0xd1,0xc4,0x90,0xc1, 0xeb,0xbe,0x0c,0xe6,0x6d,0x1b,0x6b,0x1b,0x13,0xb6, 0xb9,0x19,0xb8,0x47,0xc2,0x5a,0x91,0x44,0x7a,0x95, 0xe7,0x5e,0x4e,0xf1,0x67,0x79,0xcd,0xe8,0xbf,0x0a, 0x95,0x85,0x0e,0x32,0xaf,0x96,0x89,0x44,0x4f,0xd3, 0x77,0x10,0x8f,0x98,0xfd,0xcb,0xd4,0xe7,0x26,0x56, 0x75,0x00,0x99,0x0b,0xcc,0x7e,0x0c,0xa3,0xc4,0xaa, 0xa3,0x04,0xa3,0x87,0xd2,0x0f,0x3b,0x8f,0xbb,0xcd, 0x42,0xa1,0xbd,0x31,0x1d,0x7a,0x43,0x03,0xdd,0xa5, 0xab,0x07,0x88,0x96,0xae,0x80,0xc1,0x8b,0x0a,0xf6, 0x6d,0xff,0x31,0x96,0x16,0xeb,0x78,0x4e,0x49,0x5a, 0xd2,0xce,0x90,0xd7,0xf7,0x72,0xa8,0x17,0x47,0xb6, 0x5f,0x62,0x09,0x3b,0x1e,0x0d,0xb9,0xe5,0xba,0x53, 0x2f,0xaf,0xec,0x47,0x50,0x83,0x23,0xe6,0x71,0x32, 0x7d,0xf9,0x44,0x44,0x32,0xcb,0x73,0x67,0xce,0xc8, 0x2f,0x5d,0x44,0xc0,0xd0,0x0b,0x67,0xd6,0x50,0xa0, 0x75,0xcd,0x4b,0x70,0xde,0xdd,0x77,0xeb,0x9b,0x10, 0x23,0x1b,0x6b,0x5b,0x74,0x13,0x47,0x39,0x6d,0x62, 0x89,0x74,0x21,0xd4,0x3d,0xf9,0xb4,0x2e,0x44,0x6e, 0x35,0x8e,0x9c,0x11,0xa9,0xb2,0x18,0x4e,0xcb,0xef, 0x0c,0xd8,0xe7,0xa8,0x77,0xef,0x96,0x8f,0x13,0x90, 0xec,0x9b,0x3d,0x35,0xa5,0x58,0x5c,0xb0,0x09,0x29, 0x0e,0x2f,0xcd,0xe7,0xb5,0xec,0x66,0xd9,0x08,0x4b, 0xe4,0x40,0x55,0xa6,0x19,0xd9,0xdd,0x7f,0xc3,0x16, 0x6f,0x94,0x87,0xf7,0xcb,0x27,0x29,0x12,0x42,0x64, 0x45,0x99,0x85,0x14,0xc1,0x5d,0x53,0xa1,0x8c,0x86, 0x4c,0xe3,0xa2,0xb7,0x55,0x57,0x93,0x98,0x81,0x26, 0x52,0x0e,0xac,0xf2,0xe3,0x06,0x6e,0x23,0x0c,0x91, 0xbe,0xe4,0xdd,0x53,0x04,0xf5,0xfd,0x04,0x05,0xb3, 0x5b,0xd9,0x9c,0x73,0x13,0x5d,0x3d,0x9b,0xc3,0x35, 0xee,0x04,0x9e,0xf6,0x9b,0x38,0x67,0xbf,0x2d,0x7b, 0xd1,0xea,0xa5,0x95,0xd8,0xbf,0xc0,0x06,0x6f,0xf8, 0xd3,0x15,0x09,0xeb,0x0c,0x6c,0xaa,0x00,0x6c,0x80, 0x7a,0x62,0x3e,0xf8,0x4c,0x3d,0x33,0xc1,0x95,0xd2, 0x3e,0xe3,0x20,0xc4,0x0d,0xe0,0x55,0x81,0x57,0xc8, 0x22,0xd4,0xb8,0xc5,0x69,0xd8,0x49,0xae,0xd5,0x9d, 0x4e,0x0f,0xd7,0xf3,0x79,0x58,0x6b,0x4b,0x7f,0xf6, 0x84,0xed,0x6a,0x18,0x9f,0x74,0x86,0xd4,0x9b,0x9c, 0x4b,0xad,0x9b,0xa2,0x4b,0x96,0xab,0xf9,0x24,0x37, 0x2c,0x8a,0x8f,0xff,0xb1,0x0d,0x55,0x35,0x49,0x00, 0xa7,0x7a,0x3d,0xb5,0xf2,0x05,0xe1,0xb9,0x9f,0xcd, 0x86,0x60,0x86,0x3a,0x15,0x9a,0xd4,0xab,0xe4,0x0f, 0xa4,0x89,0x34,0x16,0x3d,0xdd,0xe5,0x42,0xa6,0x58, 0x55,0x40,0xfd,0x68,0x3c,0xbf,0xd8,0xc0,0x0f,0x12, 0x12,0x9a,0x28,0x4d,0xea,0xcc,0x4c,0xde,0xfe,0x58, 0xbe,0x71,0x37,0x54,0x1c,0x04,0x71,0x26,0xc8,0xd4, 0x9e,0x27,0x55,0xab,0x18,0x1a,0xb7,0xe9,0x40,0xb0, 0xc0}; member_ptr<Weak::ARC4> arc4; bool pass=true, fail; unsigned int i; std::cout << "\nARC4 validation suite running...\n\n"; arc4.reset(new Weak::ARC4(Key0, sizeof(Key0))); arc4->ProcessString(Input0, sizeof(Input0)); fail = memcmp(Input0, Output0, sizeof(Input0)) != 0; std::cout << (fail ? "FAILED" : "passed") << " Test 0" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key1, sizeof(Key1))); arc4->ProcessString(Key1, Input1, sizeof(Key1)); fail = memcmp(Output1, Key1, sizeof(Key1)) != 0; std::cout << (fail ? "FAILED" : "passed") << " Test 1" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key2, sizeof(Key2))); for (i=0, fail=false; i<sizeof(Input2); i++) if (arc4->ProcessByte(Input2[i]) != Output2[i]) fail = true; std::cout << (fail ? "FAILED" : "passed") << " Test 2" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key3, sizeof(Key3))); for (i=0, fail=false; i<sizeof(Input3); i++) if (arc4->ProcessByte(Input3[i]) != Output3[i]) fail = true; std::cout << (fail ? "FAILED" : "passed") << " Test 3" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key4, sizeof(Key4))); for (i=0, fail=false; i<sizeof(Input4); i++) if (arc4->ProcessByte(Input4[i]) != Output4[i]) fail = true; std::cout << (fail ? "FAILED" : "passed") << " Test 4" << std::endl; pass = pass && !fail; return pass; } bool ValidateRC5() { std::cout << "\nRC5 validation suite running...\n\n"; bool pass1 = true, pass2 = true; RC5Encryption enc; // 0 to 2040-bits (255-bytes) pass1 = RC5Encryption::DEFAULT_KEYLENGTH == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == 0 && pass1; pass1 = enc.StaticGetValidKeyLength(254) == 254 && pass1; pass1 = enc.StaticGetValidKeyLength(255) == 255 && pass1; pass1 = enc.StaticGetValidKeyLength(256) == 255 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; RC5Decryption dec; pass2 = RC5Decryption::DEFAULT_KEYLENGTH == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == 0 && pass2; pass2 = dec.StaticGetValidKeyLength(254) == 254 && pass2; pass2 = dec.StaticGetValidKeyLength(255) == 255 && pass2; pass2 = dec.StaticGetValidKeyLength(256) == 255 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rc5val.dat", true, new HexDecoder); return BlockTransformationTest(VariableRoundsCipherFactory<RC5Encryption, RC5Decryption>(16, 12), valdata) && pass1 && pass2; } bool ValidateRC6() { std::cout << "\nRC6 validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; RC6Encryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; RC6Decryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rc6val.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RC6Encryption, RC6Decryption>(16), valdata, 2) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RC6Encryption, RC6Decryption>(24), valdata, 2) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RC6Encryption, RC6Decryption>(32), valdata, 2) && pass3; return pass1 && pass2 && pass3; } bool ValidateMARS() { std::cout << "\nMARS validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; MARSEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 56 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 56 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; MARSDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 56 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 56 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/marsval.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<MARSEncryption, MARSDecryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<MARSEncryption, MARSDecryption>(24), valdata, 3) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<MARSEncryption, MARSDecryption>(32), valdata, 2) && pass3; return pass1 && pass2 && pass3; } bool ValidateRijndael() { std::cout << "\nRijndael (AES) validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; RijndaelEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; RijndaelDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rijndael.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RijndaelEncryption, RijndaelDecryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RijndaelEncryption, RijndaelDecryption>(24), valdata, 3) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RijndaelEncryption, RijndaelDecryption>(32), valdata, 2) && pass3; pass3 = RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/aes.txt") && pass3; return pass1 && pass2 && pass3; } bool ValidateTwofish() { std::cout << "\nTwofish validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; TwofishEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; TwofishDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/twofishv.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<TwofishEncryption, TwofishDecryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<TwofishEncryption, TwofishDecryption>(24), valdata, 3) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<TwofishEncryption, TwofishDecryption>(32), valdata, 2) && pass3; return pass1 && pass2 && pass3; } bool ValidateSerpent() { std::cout << "\nSerpent validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; SerpentEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; SerpentDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/serpentv.dat", true, new HexDecoder); bool pass = true; pass = BlockTransformationTest(FixedRoundsCipherFactory<SerpentEncryption, SerpentDecryption>(16), valdata, 5) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<SerpentEncryption, SerpentDecryption>(24), valdata, 4) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<SerpentEncryption, SerpentDecryption>(32), valdata, 3) && pass; return pass1 && pass2 && pass3; } bool ValidateBlowfish() { std::cout << "\nBlowfish validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true, fail; BlowfishEncryption enc1; // 32 to 448-bits (4 to 56-bytes) pass1 = enc1.StaticGetValidKeyLength(3) == 4 && pass1; pass1 = enc1.StaticGetValidKeyLength(4) == 4 && pass1; pass1 = enc1.StaticGetValidKeyLength(5) == 5 && pass1; pass1 = enc1.StaticGetValidKeyLength(8) == 8 && pass1; pass1 = enc1.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc1.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc1.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc1.StaticGetValidKeyLength(56) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(57) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(60) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(64) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(128) == 56 && pass1; BlowfishDecryption dec1; // 32 to 448-bits (4 to 56-bytes) pass2 = dec1.StaticGetValidKeyLength(3) == 4 && pass2; pass2 = dec1.StaticGetValidKeyLength(4) == 4 && pass2; pass2 = dec1.StaticGetValidKeyLength(5) == 5 && pass2; pass2 = dec1.StaticGetValidKeyLength(8) == 8 && pass2; pass2 = dec1.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec1.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec1.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec1.StaticGetValidKeyLength(56) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(57) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(60) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(64) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(128) == 56 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; HexEncoder output(new FileSink(std::cout)); const char *key[]={"abcdefghijklmnopqrstuvwxyz", "Who is John Galt?"}; byte *plain[]={(byte *)"BLOWFISH", (byte *)"\xfe\xdc\xba\x98\x76\x54\x32\x10"}; byte *cipher[]={(byte *)"\x32\x4e\xd0\xfe\xf4\x13\xa2\x03", (byte *)"\xcc\x91\x73\x2b\x80\x22\xf6\x84"}; byte out[8], outplain[8]; for (int i=0; i<2; i++) { ECB_Mode<Blowfish>::Encryption enc2((byte *)key[i], strlen(key[i])); enc2.ProcessData(out, plain[i], 8); fail = memcmp(out, cipher[i], 8) != 0; ECB_Mode<Blowfish>::Decryption dec2((byte *)key[i], strlen(key[i])); dec2.ProcessData(outplain, cipher[i], 8); fail = fail || memcmp(outplain, plain[i], 8); pass3 = pass3 && !fail; std::cout << (fail ? "FAILED " : "passed "); std::cout << '\"' << key[i] << '\"'; for (int j=0; j<(signed int)(30-strlen(key[i])); j++) std::cout << ' '; output.Put(outplain, 8); std::cout << " "; output.Put(out, 8); std::cout << std::endl; } return pass1 && pass2 && pass3; } bool ValidateThreeWay() { std::cout << "\n3-WAY validation suite running...\n\n"; bool pass1 = true, pass2 = true; ThreeWayEncryption enc; // 96-bit only pass1 = ThreeWayEncryption::KEYLENGTH == 12 && pass1; pass1 = enc.StaticGetValidKeyLength(8) == 12 && pass1; pass1 = enc.StaticGetValidKeyLength(12) == 12 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 12 && pass1; ThreeWayDecryption dec; // 96-bit only pass2 = ThreeWayDecryption::KEYLENGTH == 12 && pass2; pass2 = dec.StaticGetValidKeyLength(8) == 12 && pass2; pass2 = dec.StaticGetValidKeyLength(12) == 12 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 12 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/3wayval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<ThreeWayEncryption, ThreeWayDecryption>(), valdata) && pass1 && pass2; } bool ValidateGOST() { std::cout << "\nGOST validation suite running...\n\n"; bool pass1 = true, pass2 = true; GOSTEncryption enc; // 256-bit only pass1 = GOSTEncryption::KEYLENGTH == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(40) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; GOSTDecryption dec; // 256-bit only pass2 = GOSTDecryption::KEYLENGTH == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(40) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/gostval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<GOSTEncryption, GOSTDecryption>(), valdata) && pass1 && pass2; } bool ValidateSHARK() { std::cout << "\nSHARK validation suite running...\n\n"; bool pass1 = true, pass2 = true; SHARKEncryption enc; // 128-bit only pass1 = SHARKEncryption::KEYLENGTH == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(15) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(17) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 16 && pass1; SHARKDecryption dec; // 128-bit only pass2 = SHARKDecryption::KEYLENGTH == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(15) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(17) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 16 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/sharkval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<SHARKEncryption, SHARKDecryption>(), valdata) && pass1 && pass2; } bool ValidateCAST() { std::cout << "\nCAST-128 validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; CAST128Encryption enc1; // 40 to 128-bits (5 to 16-bytes) pass1 = CAST128Encryption::DEFAULT_KEYLENGTH == 16 && pass1; pass1 = enc1.StaticGetValidKeyLength(4) == 5 && pass1; pass1 = enc1.StaticGetValidKeyLength(5) == 5 && pass1; pass1 = enc1.StaticGetValidKeyLength(15) == 15 && pass1; pass1 = enc1.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc1.StaticGetValidKeyLength(17) == 16 && pass1; CAST128Decryption dec1; // 40 to 128-bits (5 to 16-bytes) pass2 = CAST128Decryption::DEFAULT_KEYLENGTH == 16 && pass2; pass2 = dec1.StaticGetValidKeyLength(4) == 5 && pass2; pass2 = dec1.StaticGetValidKeyLength(5) == 5 && pass2; pass2 = dec1.StaticGetValidKeyLength(15) == 15 && pass2; pass2 = dec1.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec1.StaticGetValidKeyLength(17) == 16 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource val128(CRYPTOPP_DATA_DIR "TestData/cast128v.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CAST128Encryption, CAST128Decryption>(16), val128, 1) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CAST128Encryption, CAST128Decryption>(10), val128, 1) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CAST128Encryption, CAST128Decryption>(5), val128, 1) && pass3; std::cout << "\nCAST-256 validation suite running...\n\n"; bool pass4 = true, pass5 = true, pass6 = true; CAST256Encryption enc2; // 128, 160, 192, 224, or 256-bits (16 to 32-bytes, step 4) pass1 = CAST128Encryption::DEFAULT_KEYLENGTH == 16 && pass1; pass4 = enc2.StaticGetValidKeyLength(15) == 16 && pass4; pass4 = enc2.StaticGetValidKeyLength(16) == 16 && pass4; pass4 = enc2.StaticGetValidKeyLength(17) == 20 && pass4; pass4 = enc2.StaticGetValidKeyLength(20) == 20 && pass4; pass4 = enc2.StaticGetValidKeyLength(24) == 24 && pass4; pass4 = enc2.StaticGetValidKeyLength(28) == 28 && pass4; pass4 = enc2.StaticGetValidKeyLength(31) == 32 && pass4; pass4 = enc2.StaticGetValidKeyLength(32) == 32 && pass4; pass4 = enc2.StaticGetValidKeyLength(33) == 32 && pass4; CAST256Decryption dec2; // 128, 160, 192, 224, or 256-bits (16 to 32-bytes, step 4) pass2 = CAST256Decryption::DEFAULT_KEYLENGTH == 16 && pass2; pass5 = dec2.StaticGetValidKeyLength(15) == 16 && pass5; pass5 = dec2.StaticGetValidKeyLength(16) == 16 && pass5; pass5 = dec2.StaticGetValidKeyLength(17) == 20 && pass5; pass5 = dec2.StaticGetValidKeyLength(20) == 20 && pass5; pass5 = dec2.StaticGetValidKeyLength(24) == 24 && pass5; pass5 = dec2.StaticGetValidKeyLength(28) == 28 && pass5; pass5 = dec2.StaticGetValidKeyLength(31) == 32 && pass5; pass5 = dec2.StaticGetValidKeyLength(32) == 32 && pass5; pass5 = dec2.StaticGetValidKeyLength(33) == 32 && pass5; std::cout << (pass4 && pass5 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource val256(CRYPTOPP_DATA_DIR "TestData/cast256v.dat", true, new HexDecoder); pass6 = BlockTransformationTest(FixedRoundsCipherFactory<CAST256Encryption, CAST256Decryption>(16), val256, 1) && pass6; pass6 = BlockTransformationTest(FixedRoundsCipherFactory<CAST256Encryption, CAST256Decryption>(24), val256, 1) && pass6; pass6 = BlockTransformationTest(FixedRoundsCipherFactory<CAST256Encryption, CAST256Decryption>(32), val256, 1) && pass6; return pass1 && pass2 && pass3 && pass4 && pass5 && pass6; } bool ValidateSquare() { std::cout << "\nSquare validation suite running...\n\n"; bool pass1 = true, pass2 = true; SquareEncryption enc; // 128-bits only pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(15) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(17) == 16 && pass1; SquareDecryption dec; // 128-bits only pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(15) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(17) == 16 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/squareva.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<SquareEncryption, SquareDecryption>(), valdata) && pass1 && pass2; } bool ValidateSKIPJACK() { std::cout << "\nSKIPJACK validation suite running...\n\n"; bool pass1 = true, pass2 = true; SKIPJACKEncryption enc; // 80-bits only pass1 = enc.StaticGetValidKeyLength(8) == 10 && pass1; pass1 = enc.StaticGetValidKeyLength(9) == 10 && pass1; pass1 = enc.StaticGetValidKeyLength(10) == 10 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 10 && pass1; SKIPJACKDecryption dec; // 80-bits only pass2 = dec.StaticGetValidKeyLength(8) == 10 && pass2; pass2 = dec.StaticGetValidKeyLength(9) == 10 && pass2; pass2 = dec.StaticGetValidKeyLength(10) == 10 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 10 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/skipjack.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<SKIPJACKEncryption, SKIPJACKDecryption>(), valdata) && pass1 && pass2; } bool ValidateSEAL() { const byte input[] = {0x37,0xa0,0x05,0x95,0x9b,0x84,0xc4,0x9c,0xa4,0xbe,0x1e,0x05,0x06,0x73,0x53,0x0f,0x5f,0xb0,0x97,0xfd,0xf6,0xa1,0x3f,0xbd,0x6c,0x2c,0xde,0xcd,0x81,0xfd,0xee,0x7c}; const byte key[] = {0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, 0x89, 0x98, 0xba, 0xdc, 0xfe, 0x10, 0x32, 0x54, 0x76, 0xc3, 0xd2, 0xe1, 0xf0}; const byte iv[] = {0x01, 0x35, 0x77, 0xaf}; byte output[32]; std::cout << "\nSEAL validation suite running...\n\n"; SEAL<>::Encryption seal(key, sizeof(key), iv); unsigned int size = sizeof(input); bool pass = true; memset(output, 1, size); seal.ProcessString(output, input, size); for (unsigned int i=0; i<size; i++) if (output[i] != 0) pass = false; seal.Seek(1); output[1] = seal.ProcessByte(output[1]); seal.ProcessString(output+2, size-2); pass = pass && memcmp(output+1, input+1, size-1) == 0; std::cout << (pass ? "passed" : "FAILED") << std::endl; return pass; } bool ValidateBaseCode() { bool pass = true, fail; byte data[255]; for (unsigned int i=0; i<255; i++) data[i] = byte(i); const char hexEncoded[] = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627" "28292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F" "505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F7071727374757677" "78797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F" "A0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7" "C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFE"; const char base32Encoded[] = "AAASEA2EAWDAQCAJBIFS2DIQB6IBCESVCSKTNF22DEPBYHA7D2RUAIJCENUCKJTHFAWUWK3NFWZC8NBT" "GI3VIPJYG66DUQT5HS8V6R4AIFBEGTCFI3DWSUKKJPGE4VURKBIXEW4WKXMFQYC3MJPX2ZK8M7SGC2VD" "NTUYN35IPFXGY5DPP3ZZA6MUQP4HK7VZRB6ZW856RX9H9AEBSKB2JBNGS8EIVCWMTUG27D6SUGJJHFEX" "U4M3TGN4VQQJ5HW9WCS4FI7EWYVKRKFJXKX43MPQX82MDNXVYU45PP72ZG7MZRF7Z496BSQC2RCNMTYH" "3DE6XU8N3ZHN9WGT4MJ7JXQY49NPVYY55VQ77Z9A6HTQH3HF65V8T4RK7RYQ55ZR8D29F69W8Z5RR8H3" "9M7939R8"; const char base64AndHexEncoded[] = "41414543417751464267634943516F4C4441304F4478415245684D554652595847426B6147787764" "486838674953496A4A43556D4A7967704B6973734C5334764D4445794D7A51310A4E6A63344F546F" "375044302B50304242516B4E4552555A4853456C4B5330784E546B395155564A5456465657563168" "5A576C746358563566594746695932526C5A6D646F615770720A6247317562334278636E4E306458" "5A3365486C3665337839666E2B4167594B44684957476834694A696F754D6A5936506B4A47536B35" "53566C7065596D5A71626E4A32656E3643680A6F714F6B7061616E714B6D717136797472712B7773" "624B7A744C573274376935757275387662362F774D484377385446787366497963724C7A4D334F7A" "39445230745055316462580A324E6E6132397A6433742F6734654C6A354F586D352B6A7036757673" "3765377638504879382F5431397666342B6672372F50332B0A"; const char base64URLAndHexEncoded[] = "41414543417751464267634943516F4C4441304F4478415245684D554652595847426B6147787764" "486838674953496A4A43556D4A7967704B6973734C5334764D4445794D7A51314E6A63344F546F37" "5044302D50304242516B4E4552555A4853456C4B5330784E546B395155564A54564656575631685A" "576C746358563566594746695932526C5A6D646F615770726247317562334278636E4E3064585A33" "65486C3665337839666E2D4167594B44684957476834694A696F754D6A5936506B4A47536B355356" "6C7065596D5A71626E4A32656E3643686F714F6B7061616E714B6D717136797472712D7773624B7A" "744C573274376935757275387662365F774D484377385446787366497963724C7A4D334F7A394452" "3074505531646258324E6E6132397A6433745F6734654C6A354F586D352D6A703675767337653776" "38504879385F5431397666342D6672375F50332D"; std::cout << "\nBase64, Base64URL, Base32 and Base16 coding validation suite running...\n\n"; fail = !TestFilter(HexEncoder().Ref(), data, 255, (const byte *)hexEncoded, strlen(hexEncoded)); try {HexEncoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Hex Encoding\n"; pass = pass && !fail; fail = !TestFilter(HexDecoder().Ref(), (const byte *)hexEncoded, strlen(hexEncoded), data, 255); try {HexDecoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Hex Decoding\n"; pass = pass && !fail; fail = !TestFilter(Base32Encoder().Ref(), data, 255, (const byte *)base32Encoded, strlen(base32Encoded)); try {Base32Encoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base32 Encoding\n"; pass = pass && !fail; fail = !TestFilter(Base32Decoder().Ref(), (const byte *)base32Encoded, strlen(base32Encoded), data, 255); try {Base32Decoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base32 Decoding\n"; pass = pass && !fail; fail = !TestFilter(Base64Encoder(new HexEncoder).Ref(), data, 255, (const byte *)base64AndHexEncoded, strlen(base64AndHexEncoded)); try {Base64Encoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 Encoding\n"; pass = pass && !fail; fail = !TestFilter(HexDecoder(new Base64Decoder).Ref(), (const byte *)base64AndHexEncoded, strlen(base64AndHexEncoded), data, 255); try {Base64Decoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 Decoding\n"; pass = pass && !fail; fail = !TestFilter(Base64URLEncoder(new HexEncoder).Ref(), data, 255, (const byte *)base64URLAndHexEncoded, strlen(base64URLAndHexEncoded)); try {Base64URLEncoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 URL Encoding\n"; pass = pass && !fail; fail = !TestFilter(HexDecoder(new Base64URLDecoder).Ref(), (const byte *)base64URLAndHexEncoded, strlen(base64URLAndHexEncoded), data, 255); try {Base64URLDecoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 URL Decoding\n"; pass = pass && !fail; return pass; } bool ValidateSHACAL2() { std::cout << "\nSHACAL-2 validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; SHACAL2Encryption enc; // 128 to 512-bits (16 to 64-bytes) pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(15) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 64 && pass1; pass1 = enc.StaticGetValidKeyLength(65) == 64 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 64 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; SHACAL2Decryption dec; // 128 to 512-bits (16 to 64-bytes) pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(15) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 64 && pass2; pass2 = dec.StaticGetValidKeyLength(65) == 64 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 64 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/shacal2v.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<SHACAL2Encryption, SHACAL2Decryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<SHACAL2Encryption, SHACAL2Decryption>(64), valdata, 10) && pass3; return pass1 && pass2 && pass3; } bool ValidateARIA() { std::cout << "\nARIA validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; ARIAEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; ARIADecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/aria.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<ARIAEncryption, ARIADecryption>(16), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<ARIAEncryption, ARIADecryption>(24), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<ARIAEncryption, ARIADecryption>(32), valdata, 15) && pass3; return pass1 && pass2 && pass3; } bool ValidateCamellia() { std::cout << "\nCamellia validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; CamelliaEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; CamelliaDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/camellia.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CamelliaEncryption, CamelliaDecryption>(16), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CamelliaEncryption, CamelliaDecryption>(24), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CamelliaEncryption, CamelliaDecryption>(32), valdata, 15) && pass3; return pass1 && pass2 && pass3; } bool ValidateSalsa() { std::cout << "\nSalsa validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/salsa.txt"); } bool ValidateSosemanuk() { std::cout << "\nSosemanuk validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/sosemanuk.txt"); } bool ValidateVMAC() { std::cout << "\nVMAC validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/vmac.txt"); } bool ValidateCCM() { std::cout << "\nAES/CCM validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/ccm.txt"); } bool ValidateGCM() { std::cout << "\nAES/GCM validation suite running...\n"; std::cout << "\n2K tables:"; bool pass = RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)2048)); std::cout << "\n64K tables:"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)64*1024)) && pass; } bool ValidateCMAC() { std::cout << "\nCMAC validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/cmac.txt"); } NAMESPACE_END // Test NAMESPACE_END // CryptoPP
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_3390_0
crossvul-cpp_data_good_65_0
/* * Snd_fx.cpp * ----------- * Purpose: Processing of pattern commands, song length calculation... * Notes : This needs some heavy refactoring. * I thought of actually adding an effect interface class. Every pattern effect * could then be moved into its own class that inherits from the effect interface. * If effect handling differs severly between module formats, every format would have * its own class for that effect. Then, a call chain of effect classes could be set up * for each format, since effects cannot be processed in the same order in all formats. * Authors: Olivier Lapicque * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "Sndfile.h" #include "mod_specifications.h" #ifdef MODPLUG_TRACKER #include "../mptrack/Moddoc.h" #endif // MODPLUG_TRACKER #include "tuning.h" #include "Tables.h" #include "modsmp_ctrl.h" // For updating the loop wraparound data with the invert loop effect #include "plugins/PlugInterface.h" OPENMPT_NAMESPACE_BEGIN // Formats which have 7-bit (0...128) instead of 6-bit (0...64) global volume commands, or which are imported to this range (mostly formats which are converted to IT internally) #ifdef MODPLUG_TRACKER #define GLOBALVOL_7BIT_FORMATS_EXT (MOD_TYPE_MT2) #else #define GLOBALVOL_7BIT_FORMATS_EXT Enum<MODTYPE>::value_type() #endif // MODPLUG_TRACKER #define GLOBALVOL_7BIT_FORMATS (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM | MOD_TYPE_PTM | MOD_TYPE_MDL | MOD_TYPE_DTM | GLOBALVOL_7BIT_FORMATS_EXT) // Compensate frequency slide LUTs depending on whether we are handling periods or frequency - "up" and "down" in function name are seen from frequency perspective. static uint32 GetLinearSlideDownTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(LinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? LinearSlideDownTable[i] : LinearSlideUpTable[i]; } static uint32 GetLinearSlideUpTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(LinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? LinearSlideUpTable[i] : LinearSlideDownTable[i]; } static uint32 GetFineLinearSlideDownTable(const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(FineLinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? FineLinearSlideDownTable[i] : FineLinearSlideUpTable[i]; } static uint32 GetFineLinearSlideUpTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(FineLinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? FineLinearSlideUpTable[i] : FineLinearSlideDownTable[i]; } //////////////////////////////////////////////////////////// // Length // Memory class for GetLength() code class GetLengthMemory { protected: const CSoundFile &sndFile; public: std::unique_ptr<CSoundFile::PlayState> state; struct ChnSettings { double patLoop = 0.0; CSoundFile::samplecount_t patLoopSmp = 0; ROWINDEX patLoopStart = 0; uint32 ticksToRender = 0; // When using sample sync, we still need to render this many ticks bool incChanged = false; // When using sample sync, note frequency has changed uint8 vol = 0xFF; }; #ifndef NO_PLUGINS typedef std::map<std::pair<ModCommand::INSTR, uint16>, uint16> PlugParamMap; PlugParamMap plugParams; #endif std::vector<ChnSettings> chnSettings; double elapsedTime; static const uint32 IGNORE_CHANNEL = uint32_max; GetLengthMemory(const CSoundFile &sf) : sndFile(sf) , state(mpt::make_unique<CSoundFile::PlayState>(sf.m_PlayState)) { Reset(); } void Reset() { plugParams.clear(); elapsedTime = 0.0; state->m_lTotalSampleCount = 0; state->m_nMusicSpeed = sndFile.m_nDefaultSpeed; state->m_nMusicTempo = sndFile.m_nDefaultTempo; state->m_nGlobalVolume = sndFile.m_nDefaultGlobalVolume; chnSettings.assign(sndFile.GetNumChannels(), ChnSettings()); for(CHANNELINDEX chn = 0; chn < sndFile.GetNumChannels(); chn++) { state->Chn[chn].Reset(ModChannel::resetTotal, sndFile, chn); state->Chn[chn].nOldGlobalVolSlide = 0; state->Chn[chn].nOldChnVolSlide = 0; state->Chn[chn].nNote = state->Chn[chn].nNewNote = state->Chn[chn].nLastNote = NOTE_NONE; } } // Increment playback position of sample and envelopes on a channel void RenderChannel(CHANNELINDEX channel, uint32 tickDuration, uint32 portaStart = uint32_max) { ModChannel &chn = state->Chn[channel]; uint32 numTicks = chnSettings[channel].ticksToRender; if(numTicks == IGNORE_CHANNEL || numTicks == 0 || (!chn.IsSamplePlaying() && !chnSettings[channel].incChanged) || chn.pModSample == nullptr) { return; } const SmpLength sampleEnd = chn.dwFlags[CHN_LOOP] ? chn.nLoopEnd : chn.nLength; const SmpLength loopLength = chn.nLoopEnd - chn.nLoopStart; const bool itEnvMode = sndFile.m_playBehaviour[kITEnvelopePositionHandling]; const bool updatePitchEnv = (chn.PitchEnv.flags & (ENV_ENABLED | ENV_FILTER)) == ENV_ENABLED; bool stopNote = false; SamplePosition inc = chn.increment * tickDuration; if(chn.dwFlags[CHN_PINGPONGFLAG]) inc.Negate(); for(uint32 i = 0; i < numTicks; i++) { bool updateInc = (chn.PitchEnv.flags & (ENV_ENABLED | ENV_FILTER)) == ENV_ENABLED; if(i >= portaStart) { chn.isFirstTick = false; const ModCommand &p = *sndFile.Patterns[state->m_nPattern].GetpModCommand(state->m_nRow, channel); if(p.command == CMD_TONEPORTAMENTO) sndFile.TonePortamento(&chn, p.param); else if(p.command == CMD_TONEPORTAVOL) sndFile.TonePortamento(&chn, 0); if(p.volcmd == VOLCMD_TONEPORTAMENTO) { uint32 param = p.vol; if(sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DMF | MOD_TYPE_DBM | MOD_TYPE_IMF | MOD_TYPE_PSM | MOD_TYPE_J2B | MOD_TYPE_ULT | MOD_TYPE_OKT | MOD_TYPE_MT2 | MOD_TYPE_MDL)) { param = ImpulseTrackerPortaVolCmd[param & 0x0F]; } else { // Close enough. Do not bother with idiosyncratic FT2 behaviour here. param <<= 4; } sndFile.TonePortamento(&chn, param); } updateInc = true; } int period = chn.nPeriod; if(itEnvMode) sndFile.IncrementEnvelopePositions(&chn); if(updatePitchEnv) { sndFile.ProcessPitchFilterEnvelope(&chn, period); updateInc = true; } if(!itEnvMode) sndFile.IncrementEnvelopePositions(&chn); int vol = 0; sndFile.ProcessInstrumentFade(&chn, vol); if(updateInc || chnSettings[channel].incChanged) { chn.increment = sndFile.GetChannelIncrement(&chn, period, 0); chnSettings[channel].incChanged = false; inc = chn.increment * tickDuration; if(chn.dwFlags[CHN_PINGPONGFLAG]) inc.Negate(); } chn.position += inc; if(chn.position.GetUInt() >= sampleEnd) { if(chn.dwFlags[CHN_LOOP]) { // We exceeded the sample loop, go back to loop start. if(chn.dwFlags[CHN_PINGPONGLOOP]) { if(chn.position < SamplePosition(chn.nLoopStart, 0)) { chn.position = SamplePosition(chn.nLoopStart + chn.nLoopStart, 0) - chn.position; chn.dwFlags.flip(CHN_PINGPONGFLAG); inc.Negate(); } SmpLength posInt = chn.position.GetUInt() - chn.nLoopStart; SmpLength pingpongLength = loopLength * 2; if(sndFile.m_playBehaviour[kITPingPongMode]) pingpongLength--; posInt %= pingpongLength; bool forward = (posInt < loopLength); if(forward) chn.position.SetInt(chn.nLoopStart + posInt); else chn.position.SetInt(chn.nLoopEnd - (posInt - loopLength)); if(forward == chn.dwFlags[CHN_PINGPONGFLAG]) { chn.dwFlags.flip(CHN_PINGPONGFLAG); inc.Negate(); } } else { SmpLength posInt = chn.position.GetUInt(); if(posInt >= chn.nLoopEnd + loopLength) { const SmpLength overshoot = posInt - chn.nLoopEnd; posInt -= (overshoot / loopLength) * loopLength; } while(posInt >= chn.nLoopEnd) { posInt -= loopLength; } chn.position.SetInt(posInt); } } else { // Past sample end. stopNote = true; break; } } } if(stopNote) { chn.Stop(); chn.nPortamentoDest = 0; } chnSettings[channel].ticksToRender = 0; } }; // Get mod length in various cases. Parameters: // [in] adjustMode: See enmGetLengthResetMode for possible adjust modes. // [in] target: Time or position target which should be reached, or no target to get length of the first sub song. Use GetLengthTarget::StartPos to also specify a position from where the seeking should begin. // [out] See definition of type GetLengthType for the returned values. std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target) { std::vector<GetLengthType> results; GetLengthType retval; retval.startOrder = target.startOrder; retval.startRow = target.startRow; // Are we trying to reach a certain pattern position? const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget; const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions; SEQUENCEINDEX sequence = target.sequence; if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex(); const ModSequence &orderList = Order(sequence); GetLengthMemory memory(*this); CSoundFile::PlayState &playState = *memory.state; // Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time) RowVisitor visitedRows(*this, sequence); playState.m_nNextRow = playState.m_nRow = target.startRow; playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder; // Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode. std::bitset<MAX_EFFECTS> forbiddenCommands; std::bitset<MAX_VOLCMDS> forbiddenVolCommands; if(adjustSamplePos) { forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP); forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN); forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG); forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG); forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN); // Optimize away channels for which it's pointless to adjust sample positions for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size()) { // If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start. const PATTERNINDEX seekPat = orderList[target.pos.order]; if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row)) { const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++) { if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments()) || (m->IsNote() && !m->IsPortamento())) { memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } } } } } // If samples are being synced, force them to resync if tick duration changes uint32 oldTickDuration = 0; for (;;) { // Time target reached. if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time) { retval.targetReached = true; break; } uint32 rowDelay = 0, tickDelay = 0; playState.m_nRow = playState.m_nNextRow; playState.m_nCurrentOrder = playState.m_nNextOrder; if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows()) { playState.m_nRow = 0; if(m_playBehaviour[kFT2LoopE60Restart]) { playState.m_nRow = playState.m_nNextPatStartRow; playState.m_nNextPatStartRow = 0; } playState.m_nCurrentOrder = ++playState.m_nNextOrder; } // Check if pattern is valid playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); bool positionJumpOnThisRow = false; bool patternBreakOnThisRow = false; bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false; if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order) { // Early test: Target is inside +++ or non-existing pattern retval.targetReached = true; break; } while(playState.m_nPattern >= Patterns.Size()) { // End of song? if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size())) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) break; else playState.m_nCurrentOrder = orderList.GetRestartPos(); } else { playState.m_nCurrentOrder++; } playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); playState.m_nNextOrder = playState.m_nCurrentOrder; if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nCurrentOrder = playState.m_nNextOrder; playState.m_nPattern = orderList[playState.m_nCurrentOrder]; playState.m_nNextRow = playState.m_nRow; break; } } } if(playState.m_nNextOrder == ORDERINDEX_INVALID) { // GetFirstUnvisitedRow failed, so there is nothing more to play break; } // Skip non-existing patterns if(!Patterns.IsValidPat(playState.m_nPattern)) { // If there isn't even a tune, we should probably stop here. if(playState.m_nCurrentOrder == orderList.GetRestartPos()) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } playState.m_nNextOrder = playState.m_nCurrentOrder + 1; continue; } // Should never happen if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) playState.m_nRow = 0; // Check whether target was reached. if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row) { retval.targetReached = true; break; } if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } retval.endOrder = playState.m_nCurrentOrder; retval.endRow = playState.m_nRow; // Update next position playState.m_nNextRow = playState.m_nRow + 1; // Jumped to invalid pattern row? if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) { playState.m_nRow = 0; } // New pattern? if(!playState.m_nRow) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { memory.chnSettings[chn].patLoop = memory.elapsedTime; memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount; } } ModChannel *pChn = playState.Chn; // For various effects, we need to know first how many ticks there are in this row. const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; if(p->IsPcNote()) { #ifndef NO_PLUGINS if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS) { memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol(); } #endif // NO_PLUGINS pChn[nChn].rowCommand.Clear(); continue; } pChn[nChn].rowCommand = *p; switch(p->command) { case CMD_SPEED: SetSpeed(playState, p->param); break; case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(p->param != 0) SetSpeed(playState, p->param); } break; case CMD_S3MCMDEX: if((p->param & 0xF0) == 0x60) { // Fine Pattern Delay tickDelay += (p->param & 0x0F); } else if((p->param & 0xF0) == 0xE0 && !rowDelay) { // Pattern Delay if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. rowDelay = 1 + (p->param & 0x0F); } } break; case CMD_MODCMDEX: if((p->param & 0xF0) == 0xE0) { // Pattern Delay rowDelay = 1 + (p->param & 0x0F); } break; } } if(rowDelay == 0) rowDelay = 1; const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay; const uint32 nonRowTicks = numTicks - rowDelay; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty()) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; ModCommand::NOTE note = pChn->rowCommand.note; if (pChn->rowCommand.instr) { pChn->nNewIns = pChn->rowCommand.instr; pChn->nLastNote = NOTE_NONE; memory.chnSettings[nChn].vol = 0xFF; } if (pChn->rowCommand.IsNote()) pChn->nLastNote = note; // Update channel panning if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr) { SAMPLEINDEX smp = 0; if(GetNumInstruments()) { ModInstrument *pIns; if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr) { if(pIns->dwFlags[INS_SETPANNING]) pChn->nPan = pIns->nPan; if(ModCommand::IsNote(note)) smp = pIns->Keyboard[note - NOTE_MIN]; } } else { smp = pChn->nNewIns; } if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING]) { pChn->nPan = Samples[smp].nPan; } } switch(pChn->rowCommand.volcmd) { case VOLCMD_VOLUME: memory.chnSettings[nChn].vol = pChn->rowCommand.vol; break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: if(pChn->rowCommand.vol != 0) pChn->nOldVolParam = pChn->rowCommand.vol; break; } switch(command) { // Position Jump case CMD_POSITIONJUMP: positionJumpOnThisRow = true; playState.m_nNextOrder = static_cast<ORDERINDEX>(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn)); playState.m_nNextPatStartRow = 0; // FT2 E60 bug // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) playState.m_nNextRow = 0; if (adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(playState, nChn, param); if(row != ROWINDEX_INVALID) { patternBreakOnThisRow = true; playState.m_nNextRow = row; if(!positionJumpOnThisRow) { playState.m_nNextOrder = playState.m_nCurrentOrder + 1; } if(adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } } } break; // Set Tempo case CMD_TEMPO: if(!m_playBehaviour[kMODVBlankTiming]) { TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0); if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { if (tempo.GetInt()) pChn->nOldTempo = static_cast<uint8>(tempo.GetInt()); else tempo.Set(pChn->nOldTempo); } if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo; else { // Tempo Slide TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0); if ((tempo.GetInt() & 0xF0) == 0x10) { playState.m_nMusicTempo += tempoDiff; } else { if(tempoDiff < playState.m_nMusicTempo) playState.m_nMusicTempo -= tempoDiff; else playState.m_nMusicTempo.Set(0); } } TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(playState.m_nMusicTempo, tempoMin, tempoMax); } break; case CMD_S3MCMDEX: switch(param & 0xF0) { case 0x90: if(param <= 0x91) { pChn->dwFlags.set(CHN_SURROUND, param == 0x91); } break; case 0xA0: // High sample offset pChn->nOldHiOffset = param & 0x0F; break; case 0xB0: // Pattern Loop if (param & 0x0F) { patternLoopEndedOnThisRow = true; } else { CHANNELINDEX firstChn = nChn, lastChn = nChn; if(GetType() == MOD_TYPE_S3M) { // ST3 has only one global loop memory. firstChn = 0; lastChn = GetNumChannels() - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { memory.chnSettings[c].patLoop = memory.elapsedTime; memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[c].patLoopStart = playState.m_nRow; } patternLoopStartedOnThisRow = true; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_MODCMDEX: switch(param & 0xF0) { case 0x60: // Pattern Loop if (param & 0x0F) { playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug patternLoopEndedOnThisRow = true; } else { patternLoopStartedOnThisRow = true; memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_XFINEPORTAUPDOWN: // ignore high offset in compatible mode if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F; break; } // The following calculations are not interesting if we just want to get the song length. if (!(adjustMode & eAdjust)) continue; switch(command) { // Portamento Up/Down case CMD_PORTAMENTOUP: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } break; case CMD_PORTAMENTODOWN: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } break; // Tone-Portamento case CMD_TONEPORTAMENTO: if (param) pChn->nPortamentoSlide = param << 2; break; // Offset case CMD_OFFSET: if (param) pChn->oldOffset = param << 8; break; // Volume Slide case CMD_VOLUMESLIDE: case CMD_TONEPORTAVOL: if (param) pChn->nOldVolumeSlide = param; break; // Set Volume case CMD_VOLUME: memory.chnSettings[nChn].vol = param; break; // Global Volume case CMD_GLOBALVOLUME: if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values if(param <= 128) { playState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { playState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: if(m_playBehaviour[kPerChannelGlobalVolSlide]) { // IT compatibility 16. Global volume slide params are stored per channel (FT2/IT) if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide; } else { if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide; } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { param >>= 4; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param << 1; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param; } else if (param & 0xF0) { param >>= 4; param <<= 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param * nonRowTicks; } else { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param * nonRowTicks; } Limit(playState.m_nGlobalVolume, 0, 256); break; case CMD_CHANNELVOLUME: if (param <= 64) pChn->nGlobalVol = param; break; case CMD_CHANNELVOLSLIDE: { if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; int32 volume = pChn->nGlobalVol; if((param & 0x0F) == 0x0F && (param & 0xF0)) volume += (param >> 4); // Fine Up else if((param & 0xF0) == 0xF0 && (param & 0x0F)) volume -= (param & 0x0F); // Fine Down else if(param & 0x0F) // Down volume -= (param & 0x0F) * nonRowTicks; else // Up volume += ((param & 0xF0) >> 4) * nonRowTicks; Limit(volume, 0, 64); pChn->nGlobalVol = volume; } break; case CMD_PANNING8: Panning(pChn, param, Pan8bit); break; case CMD_MODCMDEX: if(param < 0x10) { // LED filter for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } } MPT_FALLTHROUGH; case CMD_S3MCMDEX: if((param & 0xF0) == 0x80) { Panning(pChn, (param & 0x0F), Pan4bit); } break; case CMD_VIBRATOVOL: if (param) pChn->nOldVolumeSlide = param; param = 0; MPT_FALLTHROUGH; case CMD_VIBRATO: Vibrato(pChn, param); break; case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; case CMD_TREMOLO: Tremolo(pChn, param); break; case CMD_PANBRELLO: Panbrello(pChn, param); break; } switch(pChn->rowCommand.volcmd) { case VOLCMD_PANNING: Panning(pChn, pChn->rowCommand.vol, Pan6bit); break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the "set vibrato speed" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F; else Vibrato(pChn, pChn->rowCommand.vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, pChn->rowCommand.vol); break; } // Process vibrato / tremolo / panbrello switch(pChn->rowCommand.command) { case CMD_VIBRATO: case CMD_FINEVIBRATO: case CMD_VIBRATOVOL: if(adjustMode & eAdjust) { uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nVibratoSpeed * vibTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nVibratoPos += static_cast<uint8>(inc); } break; case CMD_TREMOLO: if(adjustMode & eAdjust) { uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nTremoloSpeed * tremTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nTremoloPos += static_cast<uint8>(inc); } break; case CMD_PANBRELLO: if(adjustMode & eAdjust) { // Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row pChn->nPanbrelloPos += static_cast<uint8>(pChn->nPanbrelloSpeed * (numTicks - 1)); ProcessPanbrello(pChn); } break; } } // Interpret F00 effect in XM files as "stop song" if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max) { break; } playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; if(Patterns[playState.m_nPattern].GetOverrideSignature()) { playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat(); } const uint32 tickDuration = GetTickDuration(playState); const uint32 rowDuration = tickDuration * numTicks; memory.elapsedTime += static_cast<double>(rowDuration) / static_cast<double>(m_MixerSettings.gdwMixingFreq); playState.m_lTotalSampleCount += rowDuration; if(adjustSamplePos) { // Super experimental and dirty sample seeking pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) { if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL) continue; uint32 startTick = 0; const ModCommand &m = pChn->rowCommand; uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F; bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO; bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync... if(m.instr) pChn->proTrackerOffset = 0; if(m.IsNote()) { if(porta && memory.chnSettings[nChn].incChanged) { // If there's a portamento, the current channel increment mustn't be 0 in NoteChange() pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0); } int32 setPan = pChn->nPan; pChn->nNewNote = pChn->nLastNote; if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta); NoteChange(pChn, m.note, porta); memory.chnSettings[nChn].incChanged = true; if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks) { startTick = paramLo; } else if(m.command == CMD_DELAYCUT && paramHi < numTicks) { startTick = paramHi; } if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1); } if(!porta) memory.chnSettings[nChn].ticksToRender = 0; // Panning commands have to be re-applied after a note change with potential pan change. if(m.command == CMD_PANNING8 || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8) || m.volcmd == VOLCMD_PANNING) { pChn->nPan = setPan; } if(m.command == CMD_OFFSET) { bool isExtended = false; SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended); if(!isExtended) { offset <<= 8; if(offset == 0) offset = pChn->oldOffset; offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } else if(m.command == CMD_OFFSETPERCENTAGE) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255)); } else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far ReverseSampleOffset(*pChn, m.param); startTick = playState.m_nMusicSpeed - 1; } else if(m.volcmd == VOLCMD_OFFSET) { if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr) { SmpLength offset; if(m.vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1]; SampleOffset(*pChn, offset); } } } if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments()) || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks) || (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks)) { stopNote = true; } if(m.command == CMD_VOLUME) { pChn->nVolume = m.param * 4; } else if(m.volcmd == VOLCMD_VOLUME) { pChn->nVolume = m.vol * 4; } if(pChn->pModSample && !stopNote) { // Check if we don't want to emulate some effect and thus stop processing. if(m.command < MAX_EFFECTS) { if(forbiddenCommands[m.command]) { stopNote = true; } else if(m.command == CMD_MODCMDEX) { // Special case: Slides using extended commands switch(m.param & 0xF0) { case 0x10: case 0x20: stopNote = true; } } } if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd]) { stopNote = true; } } if(stopNote) { pChn->Stop(); memory.chnSettings[nChn].ticksToRender = 0; } else { if(oldTickDuration != tickDuration && oldTickDuration != 0) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far } switch(m.command) { case CMD_TONEPORTAVOL: case CMD_VOLUMESLIDE: case CMD_VIBRATOVOL: if(m.param || (GetType() != MOD_TYPE_MOD)) { for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, m.param); } } break; case CMD_MODCMDEX: if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { pChn->isFirstTick = true; switch(m.param & 0xF0) { case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break; case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break; } } break; case CMD_S3MCMDEX: if(m.param == 0x9E) { // Play forward memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.reset(CHN_PINGPONGFLAG); } else if(m.param == 0x9F) { // Reverse memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.set(CHN_PINGPONGFLAG); if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } } else if((m.param & 0xF0) == 0x70) { // TODO //ExtendedS3MCommands(nChn, param); } break; } pChn->isFirstTick = true; switch(m.volcmd) { case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it ModCommand::VOL vol = m.vol; if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } if(m.volcmd == VOLCMD_VOLSLIDEUP) vol <<= 4; for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, vol); } } break; } if(porta) { // Portamento needs immediate syncing, as the pitch changes on each tick uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1; memory.chnSettings[nChn].ticksToRender += numTicks; memory.RenderChannel(nChn, tickDuration, portaTick); } else { memory.chnSettings[nChn].ticksToRender += (numTicks - startTick); } } } } oldTickDuration = tickDuration; // Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row. // Pattern loop is not executed in IT if there are any position jump commands on the same row. // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if(patternLoopEndedOnThisRow && (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow)) && (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow)) { std::map<double, int> startTimes; // This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row. // If one of them starts or ends "in between", it will most likely calculate a wrong duration. // For S3M files, it's also way off. pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF) || (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F)) { const double start = memory.chnSettings[nChn].patLoop; if(!startTimes[start]) startTimes[start] = 1; startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F)); } } for(const auto &i : startTimes) { memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if(memory.chnSettings[nChn].patLoop == i.first) { playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1); if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1; } break; } } } if(GetType() == MOD_TYPE_IT) { // IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0) pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; } } } } } // Now advance the sample positions for sample seeking on channels that are still playing if(adjustSamplePos) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL) { memory.RenderChannel(nChn, oldTickDuration); } } } if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { retval.lastOrder = playState.m_nCurrentOrder; retval.lastRow = playState.m_nRow; } retval.duration = memory.elapsedTime; results.push_back(retval); // Store final variables if(adjustMode & eAdjust) { if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { // Target found, or there is no target (i.e. play whole song)... m_PlayState = std::move(playState); m_PlayState.m_nNextRow = m_PlayState.m_nRow; m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0; m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1; m_PlayState.m_bPositionChanged = true; for(CHANNELINDEX n = 0; n < GetNumChannels(); n++) { if(m_PlayState.Chn[n].nLastNote != NOTE_NONE) { m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote; } if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos) { m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4; } } #ifndef NO_PLUGINS // If there were any PC events, update plugin parameters to their latest value. std::bitset<MAX_MIXPLUGINS> plugSetProgram; for(const auto &param : memory.plugParams) { PLUGINDEX plug = param.first.first - 1; IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin; if(plugin != nullptr) { if(!plugSetProgram[plug]) { // Used for bridged plugins to avoid sending out individual messages for each parameter. plugSetProgram.set(plug); plugin->BeginSetProgram(); } plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue)); } } if(plugSetProgram.any()) { for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++) { if(plugSetProgram[i]) { m_MixPlugins[i].pMixPlugin->EndSetProgram(); } } } #endif // NO_PLUGINS } else if(adjustMode != eAdjustOnSuccess) { // Target not found (e.g. when jumping to a hidden sub song), reset global variables... m_PlayState.m_nMusicSpeed = m_nDefaultSpeed; m_PlayState.m_nMusicTempo = m_nDefaultTempo; m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume; } // When adjusting the playback status, we will also want to update the visited rows vector according to the current position. if(sequence != Order.GetCurrentSequenceIndex()) { Order.SetSequence(sequence); } visitedSongRows.Set(visitedRows); } return results; } ////////////////////////////////////////////////////////////////////////////////////////////////// // Effects // Change sample or instrument number. void CSoundFile::InstrumentChange(ModChannel *pChn, uint32 instr, bool bPorta, bool bUpdVol, bool bResetEnv) const { const ModInstrument *pIns = instr <= GetNumInstruments() ? Instruments[instr] : nullptr; const ModSample *pSmp = &Samples[instr]; ModCommand::NOTE note = pChn->nNewNote; if(note == NOTE_NONE && m_playBehaviour[kITInstrWithoutNote]) return; if(pIns != nullptr && ModCommand::IsNote(note)) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it if(pIns->Keyboard[note - NOTE_MIN] == 0 && m_playBehaviour[kITEmptyNoteMapSlot] && !pIns->HasValidMIDIChannel()) { pChn->pModInstrument = pIns; return; } if(pIns->NoteMap[note - NOTE_MIN] > NOTE_MAX) return; uint32 n = pIns->Keyboard[note - NOTE_MIN]; pSmp = ((n) && (n < MAX_SAMPLES)) ? &Samples[n] : nullptr; } else if(GetNumInstruments()) { // No valid instrument, or not a valid note. if (note >= NOTE_MIN_SPECIAL) return; if(m_playBehaviour[kITEmptyNoteMapSlot] && (pIns == nullptr || !pIns->HasValidMIDIChannel())) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it pChn->pModInstrument = nullptr; pChn->nNewIns = 0; return; } pSmp = nullptr; } bool returnAfterVolumeAdjust = false; // instrumentChanged is used for IT carry-on env option bool instrumentChanged = (pIns != pChn->pModInstrument); const bool sampleChanged = (pChn->pModSample != nullptr) && (pSmp != pChn->pModSample); const bool newTuning = (GetType() == MOD_TYPE_MPT && pIns && pIns->pTuning); // Playback behavior change for MPT: With portamento don't change sample if it is in // the same instrument as previous sample. if(bPorta && newTuning && pIns == pChn->pModInstrument && sampleChanged) return; if(sampleChanged && bPorta) { // IT compatibility: No sample change (also within multi-sample instruments) during portamento when using Compatible Gxx. // Test case: PortaInsNumCompat.it, PortaSampleCompat.it, PortaCutCompat.it if(m_playBehaviour[kITPortamentoInstrument] && m_SongFlags[SONG_ITCOMPATGXX] && !pChn->increment.IsZero()) { pSmp = pChn->pModSample; } // Special XM hack (also applies to MOD / S3M, except when playing IT-style S3Ms, such as k_vision.s3m) // Test case: PortaSmpChange.mod, PortaSmpChange.s3m if((!instrumentChanged && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)) && pIns) || (GetType() == MOD_TYPE_PLM) || (GetType() == MOD_TYPE_MOD && pChn->IsSamplePlaying()) || m_playBehaviour[kST3PortaSampleChange]) { // FT2 doesn't change the sample in this case, // but still uses the sample info from the old one (bug?) returnAfterVolumeAdjust = true; } } // IT compatibility: A lone instrument number should only reset sample properties to those of the corresponding sample in instrument mode. // C#5 01 ... <-- sample 1 // C-5 .. g02 <-- sample 2 // ... 01 ... <-- still sample 1, but with properties of sample 2 // In the above example, no sample change happens on the second row. In the third row, sample 1 keeps playing but with the // volume and panning properties of sample 2. // Test case: InstrAfterMultisamplePorta.it if(m_nInstruments && !instrumentChanged && sampleChanged && pChn->pCurrentSample != nullptr && m_playBehaviour[kITMultiSampleInstrumentNumber] && !pChn->rowCommand.IsNote()) { returnAfterVolumeAdjust = true; } // IT Compatibility: Envelope pickup after SCx cut (but don't do this when working with plugins, or else envelope carry stops working) // Test case: cut-carry.it if(!pChn->IsSamplePlaying() && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && (!pIns || !pIns->HasValidMIDIChannel())) { instrumentChanged = true; } // FT2 compatibility: new instrument + portamento = ignore new instrument number, but reload old instrument settings (the world of XM is upside down...) // And this does *not* happen if volume column portamento is used together with note delay... (handled in ProcessEffects(), where all the other note delay stuff is.) // Test case: porta-delay.xm if(instrumentChanged && bPorta && m_playBehaviour[kFT2PortaIgnoreInstr] && (pChn->pModInstrument != nullptr || pChn->pModSample != nullptr)) { pIns = pChn->pModInstrument; pSmp = pChn->pModSample; instrumentChanged = false; } else { pChn->pModInstrument = pIns; } // Update Volume if (bUpdVol && (!(GetType() & (MOD_TYPE_MOD | MOD_TYPE_S3M)) || ((pSmp != nullptr && pSmp->HasSampleData()) || pChn->HasMIDIOutput()))) { if(pSmp) { if(!pSmp->uFlags[SMP_NODEFAULTVOLUME]) pChn->nVolume = pSmp->nVolume; } else if(pIns && pIns->nMixPlug) { pChn->nVolume = pChn->GetVSTVolume(); } else { pChn->nVolume = 0; } } if(returnAfterVolumeAdjust && sampleChanged && m_playBehaviour[kMODSampleSwap] && pSmp != nullptr) { // ProTracker applies new instrument's finetune but keeps the old sample playing. // Test case: PortaSwapPT.mod pChn->nFineTune = pSmp->nFineTune; } if(returnAfterVolumeAdjust) return; // Instrument adjust pChn->nNewIns = 0; // IT Compatiblity: NNA is reset on every note change, not every instrument change (fixes s7xinsnum.it). if (pIns && ((!m_playBehaviour[kITNNAReset] && pSmp) || pIns->nMixPlug)) pChn->nNNA = pIns->nNNA; // Update volume pChn->UpdateInstrumentVolume(pSmp, pIns); // Update panning // FT2 compatibility: Only reset panning on instrument numbers, not notes (bUpdVol condition) // Test case: PanMemory.xm // IT compatibility: Sample and instrument panning is only applied on note change, not instrument change // Test case: PanReset.it if((bUpdVol || !(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) && !m_playBehaviour[kITPanningReset]) { ApplyInstrumentPanning(pChn, pIns, pSmp); } // Reset envelopes if(bResetEnv) { // Blurb by Storlek (from the SchismTracker code): // Conditions experimentally determined to cause envelope reset in Impulse Tracker: // - no note currently playing (of course) // - note given, no portamento // - instrument number given, portamento, compat gxx enabled // - instrument number given, no portamento, after keyoff, old effects enabled // If someone can enlighten me to what the logic really is here, I'd appreciate it. // Seems like it's just a total mess though, probably to get XMs to play right. bool reset, resetAlways; // IT Compatibility: Envelope reset // Test case: EnvReset.it if(m_playBehaviour[kITEnvelopeReset]) { const bool insNumber = (instr != 0); reset = (!pChn->nLength || (insNumber && bPorta && m_SongFlags[SONG_ITCOMPATGXX]) || (insNumber && !bPorta && pChn->dwFlags[CHN_NOTEFADE | CHN_KEYOFF] && m_SongFlags[SONG_ITOLDEFFECTS])); // NOTE: IT2.14 with SB/GUS/etc. output is different. We are going after IT's WAV writer here. // For SB/GUS/etc. emulation, envelope carry should only apply when the NNA isn't set to "Note Cut". // Test case: CarryNNA.it resetAlways = (!pChn->nFadeOutVol || instrumentChanged || pChn->dwFlags[CHN_KEYOFF]); } else { reset = (!bPorta || !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) || m_SongFlags[SONG_ITCOMPATGXX] || !pChn->nLength || (pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol)); resetAlways = !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) || instrumentChanged || pIns == nullptr || pChn->dwFlags[CHN_KEYOFF | CHN_NOTEFADE]; } if(reset) { pChn->dwFlags.set(CHN_FASTVOLRAMP); if(pIns != nullptr) { if(resetAlways) { pChn->ResetEnvelopes(); } else { if(!pIns->VolEnv.dwFlags[ENV_CARRY]) pChn->VolEnv.Reset(); if(!pIns->PanEnv.dwFlags[ENV_CARRY]) pChn->PanEnv.Reset(); if(!pIns->PitchEnv.dwFlags[ENV_CARRY]) pChn->PitchEnv.Reset(); } } // IT Compatibility: Autovibrato reset if(!m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } } else if(pIns != nullptr && !pIns->VolEnv.dwFlags[ENV_ENABLED]) { if(m_playBehaviour[kITPortamentoInstrument]) { pChn->VolEnv.Reset(); } else { pChn->ResetEnvelopes(); } } } // Invalid sample ? if(pSmp == nullptr && (pIns == nullptr || !pIns->HasValidMIDIChannel())) { pChn->pModSample = nullptr; pChn->nInsVol = 0; return; } // Tone-Portamento doesn't reset the pingpong direction flag if(bPorta && pSmp == pChn->pModSample && pSmp != nullptr) { // If channel length is 0, we cut a previous sample using SCx. In that case, we have to update sample length, loop points, etc... if(GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT) && pChn->nLength != 0) return; pChn->dwFlags.reset(CHN_KEYOFF | CHN_NOTEFADE); pChn->dwFlags = (pChn->dwFlags & (CHN_CHANNELFLAGS | CHN_PINGPONGFLAG)); } else //if(!instrumentChanged || pChn->rowCommand.instr != 0 || !IsCompatibleMode(TRK_FASTTRACKER2)) // SampleChange.xm? { pChn->dwFlags.reset(CHN_KEYOFF | CHN_NOTEFADE); // IT compatibility tentative fix: Don't change bidi loop direction when // no sample nor instrument is changed. if((m_playBehaviour[kITPingPongNoReset] || !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) && pSmp == pChn->pModSample && !instrumentChanged) pChn->dwFlags = (pChn->dwFlags & (CHN_CHANNELFLAGS | CHN_PINGPONGFLAG)); else pChn->dwFlags = (pChn->dwFlags & CHN_CHANNELFLAGS); if(pIns) { // Copy envelope flags (we actually only need the "enabled" and "pitch" flag) pChn->VolEnv.flags = pIns->VolEnv.dwFlags; pChn->PanEnv.flags = pIns->PanEnv.dwFlags; pChn->PitchEnv.flags = pIns->PitchEnv.dwFlags; // A cutoff frequency of 0 should not be reset just because the filter envelope is enabled. // Test case: FilterEnvReset.it if((pIns->PitchEnv.dwFlags & (ENV_ENABLED | ENV_FILTER)) == (ENV_ENABLED | ENV_FILTER) && !m_playBehaviour[kITFilterBehaviour]) { if(!pChn->nCutOff) pChn->nCutOff = 0x7F; } if(pIns->IsCutoffEnabled()) pChn->nCutOff = pIns->GetCutoff(); if(pIns->IsResonanceEnabled()) pChn->nResonance = pIns->GetResonance(); } } if(pSmp == nullptr) { pChn->pModSample = nullptr; pChn->nLength = 0; return; } if(bPorta && pChn->nLength == 0 && (m_playBehaviour[kFT2PortaNoNote] || m_playBehaviour[kITPortaNoNote])) { // IT/FT2 compatibility: If the note just stopped on the previous tick, prevent it from restarting. // Test cases: PortaJustStoppedNote.xm, PortaJustStoppedNote.it pChn->increment.Set(0); } pChn->pModSample = pSmp; pChn->nLength = pSmp->nLength; pChn->nLoopStart = pSmp->nLoopStart; pChn->nLoopEnd = pSmp->nLoopEnd; // ProTracker "oneshot" loops (if loop start is 0, play the whole sample once and then repeat until loop end) if(m_playBehaviour[kMODOneShotLoops] && pChn->nLoopStart == 0) pChn->nLoopEnd = pSmp->nLength; pChn->dwFlags |= (pSmp->uFlags & (CHN_SAMPLEFLAGS | CHN_SURROUND)); // IT Compatibility: Autovibrato reset if(m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } if(newTuning) { pChn->nC5Speed = pSmp->nC5Speed; pChn->m_CalculateFreq = true; pChn->nFineTune = 0; } else if(!bPorta || sampleChanged || !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) { // Don't reset finetune changed by "set finetune" command. // Test case: finetune.xm, finetune.mod // But *do* change the finetune if we switch to a different sample, to fix // Miranda`s axe by Jamson (jam007.xm) - this file doesn't use compatible play mode, // so we may want to use IsCompatibleMode instead if further problems arise. pChn->nC5Speed = pSmp->nC5Speed; pChn->nFineTune = pSmp->nFineTune; } pChn->nTranspose = pSmp->RelativeTone; // FT2 compatibility: Don't reset portamento target with new instrument numbers. // Test case: Porta-Pickup.xm // ProTracker does the same. // Test case: PortaTarget.mod if(!m_playBehaviour[kFT2PortaTargetNoReset] && GetType() != MOD_TYPE_MOD) { pChn->nPortamentoDest = 0; } pChn->m_PortamentoFineSteps = 0; if(pChn->dwFlags[CHN_SUSTAINLOOP]) { pChn->nLoopStart = pSmp->nSustainStart; pChn->nLoopEnd = pSmp->nSustainEnd; if(pChn->dwFlags[CHN_PINGPONGSUSTAIN]) pChn->dwFlags.set(CHN_PINGPONGLOOP); pChn->dwFlags.set(CHN_LOOP); } if(pChn->dwFlags[CHN_LOOP] && pChn->nLoopEnd < pChn->nLength) pChn->nLength = pChn->nLoopEnd; // Fix sample position on instrument change. This is needed for IT "on the fly" sample change. // XXX is this actually called? In ProcessEffects(), a note-on effect is emulated if there's an on the fly sample change! if(pChn->position.GetUInt() >= pChn->nLength) { if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) { pChn->position.Set(0); } } } void CSoundFile::NoteChange(ModChannel *pChn, int note, bool bPorta, bool bResetEnv, bool bManual) const { if (note < NOTE_MIN) return; const ModSample *pSmp = pChn->pModSample; const ModInstrument *pIns = pChn->pModInstrument; const bool newTuning = (GetType() == MOD_TYPE_MPT && pIns != nullptr && pIns->pTuning); // save the note that's actually used, as it's necessary to properly calculate PPS and stuff const int realnote = note; if((pIns) && (note - NOTE_MIN < (int)CountOf(pIns->Keyboard))) { uint32 n = pIns->Keyboard[note - NOTE_MIN]; if((n) && (n < MAX_SAMPLES)) { pSmp = &Samples[n]; } else if(m_playBehaviour[kITEmptyNoteMapSlot] && !pChn->HasMIDIOutput()) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it return; } note = pIns->NoteMap[note - NOTE_MIN]; } // Key Off if(note > NOTE_MAX) { // Key Off (+ Invalid Note for XM - TODO is this correct?) if(note == NOTE_KEYOFF || !(GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT))) { KeyOff(pChn); } else // Invalid Note -> Note Fade { if(/*note == NOTE_FADE && */ GetNumInstruments()) pChn->dwFlags.set(CHN_NOTEFADE); } // Note Cut if (note == NOTE_NOTECUT) { pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); // IT compatibility: Stopping sample playback by setting sample increment to 0 rather than volume // Test case: NoteOffInstr.it if ((!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) || (m_nInstruments != 0 && !m_playBehaviour[kITInstrWithNoteOff])) pChn->nVolume = 0; if(m_playBehaviour[kITInstrWithNoteOff]) pChn->increment.Set(0); pChn->nFadeOutVol = 0; } // IT compatibility tentative fix: Clear channel note memory. if(m_playBehaviour[kITClearOldNoteAfterCut]) { pChn->nNote = pChn->nNewNote = NOTE_NONE; } return; } if(newTuning) { if(!bPorta || pChn->nNote == NOTE_NONE) pChn->nPortamentoDest = 0; else { pChn->nPortamentoDest = pIns->pTuning->GetStepDistance(pChn->nNote, pChn->m_PortamentoFineSteps, static_cast<Tuning::NOTEINDEXTYPE>(note), 0); //Here pChn->nPortamentoDest means 'steps to slide'. pChn->m_PortamentoFineSteps = -pChn->nPortamentoDest; } } if(!bPorta && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MED | MOD_TYPE_MT2))) { if(pSmp) { pChn->nTranspose = pSmp->RelativeTone; pChn->nFineTune = pSmp->nFineTune; } } // IT Compatibility: Update multisample instruments frequency even if instrument is not specified (fixes the guitars in spx-shuttledeparture.it) // Test case: freqreset-noins.it if(!bPorta && pSmp && m_playBehaviour[kITMultiSampleBehaviour]) pChn->nC5Speed = pSmp->nC5Speed; if(bPorta && !pChn->IsSamplePlaying()) { if(m_playBehaviour[kFT2PortaNoNote]) { // FT2 Compatibility: Ignore notes with portamento if there was no note playing. // Test case: 3xx-no-old-samp.xm pChn->nPeriod = 0; return; } else if(m_playBehaviour[kITPortaNoNote]) { // IT Compatibility: Ignore portamento command if no note was playing (e.g. if a previous note has faded out). // Test case: Fade-Porta.it bPorta = false; } } if(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2|MOD_TYPE_MED|MOD_TYPE_MOD)) { note += pChn->nTranspose; // RealNote = PatternNote + RelativeTone; (0..118, 0 = C-0, 118 = A#9) Limit(note, NOTE_MIN + 11, NOTE_MIN + 130); // 119 possible notes } else { Limit(note, NOTE_MIN, NOTE_MAX); } if(m_playBehaviour[kITRealNoteMapping]) { // need to memorize the original note for various effects (e.g. PPS) pChn->nNote = static_cast<ModCommand::NOTE>(Clamp(realnote, NOTE_MIN, NOTE_MAX)); } else { pChn->nNote = static_cast<ModCommand::NOTE>(note); } pChn->m_CalculateFreq = true; if ((!bPorta) || (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))) pChn->nNewIns = 0; uint32 period = GetPeriodFromNote(note, pChn->nFineTune, pChn->nC5Speed); pChn->nPanbrelloOffset = 0; // IT compatibility: Sample and instrument panning is only applied on note change, not instrument change // Test case: PanReset.it if(m_playBehaviour[kITPanningReset]) ApplyInstrumentPanning(pChn, pIns, pSmp); if(bResetEnv && !bPorta) { pChn->nVolSwing = pChn->nPanSwing = 0; pChn->nResSwing = pChn->nCutSwing = 0; if(pIns) { // IT Compatiblity: NNA is reset on every note change, not every instrument change (fixes spx-farspacedance.it). if(m_playBehaviour[kITNNAReset]) pChn->nNNA = pIns->nNNA; if(!pIns->VolEnv.dwFlags[ENV_CARRY]) pChn->VolEnv.Reset(); if(!pIns->PanEnv.dwFlags[ENV_CARRY]) pChn->PanEnv.Reset(); if(!pIns->PitchEnv.dwFlags[ENV_CARRY]) pChn->PitchEnv.Reset(); // Volume Swing if(pIns->nVolSwing) { pChn->nVolSwing = static_cast<int16>(((mpt::random<int8>(AccessPRNG()) * pIns->nVolSwing) / 64 + 1) * (m_playBehaviour[kITSwingBehaviour] ? pChn->nInsVol : ((pChn->nVolume + 1) / 2)) / 199); } // Pan Swing if(pIns->nPanSwing) { pChn->nPanSwing = static_cast<int16>(((mpt::random<int8>(AccessPRNG()) * pIns->nPanSwing * 4) / 128)); if(!m_playBehaviour[kITSwingBehaviour]) { pChn->nRestorePanOnNewNote = static_cast<int16>(pChn->nPan + 1); } } // Cutoff Swing if(pIns->nCutSwing) { int32 d = ((int32)pIns->nCutSwing * (int32)(static_cast<int32>(mpt::random<int8>(AccessPRNG())) + 1)) / 128; pChn->nCutSwing = static_cast<int16>((d * pChn->nCutOff + 1) / 128); pChn->nRestoreCutoffOnNewNote = pChn->nCutOff + 1; } // Resonance Swing if(pIns->nResSwing) { int32 d = ((int32)pIns->nResSwing * (int32)(static_cast<int32>(mpt::random<int8>(AccessPRNG())) + 1)) / 128; pChn->nResSwing = static_cast<int16>((d * pChn->nResonance + 1) / 128); pChn->nRestoreResonanceOnNewNote = pChn->nResonance + 1; } } } if(!pSmp) return; if(period) { if((!bPorta) || (!pChn->nPeriod)) pChn->nPeriod = period; if(!newTuning) { // FT2 compatibility: Don't reset portamento target with new notes. // Test case: Porta-Pickup.xm // ProTracker does the same. // Test case: PortaTarget.mod // IT compatibility: Portamento target is completely cleared with new notes. // Test case: PortaReset.it if(bPorta || !(m_playBehaviour[kFT2PortaTargetNoReset] || m_playBehaviour[kITClearPortaTarget] || GetType() == MOD_TYPE_MOD)) { pChn->nPortamentoDest = period; } } if(!bPorta || (!pChn->nLength && !(GetType() & MOD_TYPE_S3M))) { pChn->pModSample = pSmp; pChn->nLength = pSmp->nLength; pChn->nLoopEnd = pSmp->nLength; pChn->nLoopStart = 0; pChn->position.Set(0); if(m_SongFlags[SONG_PT_MODE] && !pChn->rowCommand.instr) { pChn->position.SetInt(std::min<SmpLength>(pChn->proTrackerOffset, pChn->nLength - 1)); } else { pChn->proTrackerOffset = 0; } pChn->dwFlags = (pChn->dwFlags & CHN_CHANNELFLAGS) | (pSmp->uFlags & (CHN_SAMPLEFLAGS | CHN_SURROUND)); pChn->dwFlags.reset(CHN_PORTAMENTO); if(pChn->dwFlags[CHN_SUSTAINLOOP]) { pChn->nLoopStart = pSmp->nSustainStart; pChn->nLoopEnd = pSmp->nSustainEnd; pChn->dwFlags.set(CHN_PINGPONGLOOP, pChn->dwFlags[CHN_PINGPONGSUSTAIN]); pChn->dwFlags.set(CHN_LOOP); if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd; } else if(pChn->dwFlags[CHN_LOOP]) { pChn->nLoopStart = pSmp->nLoopStart; pChn->nLoopEnd = pSmp->nLoopEnd; if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd; } // ProTracker "oneshot" loops (if loop start is 0, play the whole sample once and then repeat until loop end) if(m_playBehaviour[kMODOneShotLoops] && pChn->nLoopStart == 0) pChn->nLoopEnd = pChn->nLength = pSmp->nLength; if(pChn->dwFlags[CHN_REVERSE]) { pChn->dwFlags.set(CHN_PINGPONGFLAG); pChn->position.SetInt(pChn->nLength - 1); } // Handle "retrigger" waveform type if(pChn->nVibratoType < 4) { // IT Compatibilty: Slightly different waveform offsets (why does MPT have two different offsets here with IT old effects enabled and disabled?) if(!m_playBehaviour[kITVibratoTremoloPanbrello] && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) pChn->nVibratoPos = 0x10; else if(GetType() == MOD_TYPE_MTM) pChn->nVibratoPos = 0x20; else if(!(GetType() & (MOD_TYPE_DIGI | MOD_TYPE_DBM))) pChn->nVibratoPos = 0; } // IT Compatibility: No "retrigger" waveform here if(!m_playBehaviour[kITVibratoTremoloPanbrello] && pChn->nTremoloType < 4) { pChn->nTremoloPos = 0; } } if(pChn->position.GetUInt() >= pChn->nLength) pChn->position.SetInt(pChn->nLoopStart); } else { bPorta = false; } if (!bPorta || (!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM))) || (pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol) || (m_SongFlags[SONG_ITCOMPATGXX] && pChn->rowCommand.instr != 0)) { if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) && pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol) { pChn->ResetEnvelopes(); // IT Compatibility: Autovibrato reset if(!m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } pChn->dwFlags.reset(CHN_NOTEFADE); pChn->nFadeOutVol = 65536; } if ((!bPorta) || (!m_SongFlags[SONG_ITCOMPATGXX]) || (pChn->rowCommand.instr)) { if ((!(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) || (pChn->rowCommand.instr)) { pChn->dwFlags.reset(CHN_NOTEFADE); pChn->nFadeOutVol = 65536; } } } // IT compatibility: Don't reset key-off flag on porta notes unless Compat Gxx is enabled // Test case: Off-Porta.it, Off-Porta-CompatGxx.it if(m_playBehaviour[kITDontResetNoteOffOnPorta] && bPorta && (!m_SongFlags[SONG_ITCOMPATGXX] || pChn->rowCommand.instr == 0)) pChn->dwFlags.reset(CHN_EXTRALOUD); else pChn->dwFlags.reset(CHN_EXTRALOUD | CHN_KEYOFF); // Enable Ramping if(!bPorta) { pChn->nLeftVU = pChn->nRightVU = 0xFF; pChn->dwFlags.reset(CHN_FILTER); pChn->dwFlags.set(CHN_FASTVOLRAMP); // IT compatibility 15. Retrigger is reset in RetrigNote (Tremor doesn't store anything here, so we just don't reset this as well) if(!m_playBehaviour[kITRetrigger] && !m_playBehaviour[kITTremor]) { // FT2 compatibility: Retrigger is reset in RetrigNote, tremor in ProcessEffects if(!m_playBehaviour[kFT2Retrigger] && !m_playBehaviour[kFT2Tremor]) { pChn->nRetrigCount = 0; pChn->nTremorCount = 0; } } if(bResetEnv) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } pChn->rightVol = pChn->leftVol = 0; bool useFilter = !m_SongFlags[SONG_MPTFILTERMODE]; // Setup Initial Filter for this note if(pIns) { if(pIns->IsResonanceEnabled()) { pChn->nResonance = pIns->GetResonance(); useFilter = true; } if(pIns->IsCutoffEnabled()) { pChn->nCutOff = pIns->GetCutoff(); useFilter = true; } if(useFilter && (pIns->nFilterMode != FLTMODE_UNCHANGED)) { pChn->nFilterMode = pIns->nFilterMode; } } else { pChn->nVolSwing = pChn->nPanSwing = 0; pChn->nCutSwing = pChn->nResSwing = 0; } if((pChn->nCutOff < 0x7F || m_playBehaviour[kITFilterBehaviour]) && useFilter) { SetupChannelFilter(pChn, true); } } // Special case for MPT if (bManual) pChn->dwFlags.reset(CHN_MUTE); if((pChn->dwFlags[CHN_MUTE] && (m_MixerSettings.MixerFlags & SNDMIX_MUTECHNMODE)) || (pChn->pModSample != nullptr && pChn->pModSample->uFlags[CHN_MUTE] && !bManual) || (pChn->pModInstrument != nullptr && pChn->pModInstrument->dwFlags[INS_MUTE] && !bManual)) { if (!bManual) pChn->nPeriod = 0; } // Reset the Amiga resampler for this channel if(!bPorta) { pChn->paulaState.Reset(); } } // Apply sample or instrumernt panning void CSoundFile::ApplyInstrumentPanning(ModChannel *pChn, const ModInstrument *instr, const ModSample *smp) const { int32 newPan = int32_min; // Default instrument panning if(instr != nullptr && instr->dwFlags[INS_SETPANNING]) newPan = instr->nPan; // Default sample panning if(smp != nullptr && smp->uFlags[CHN_PANNING]) newPan = smp->nPan; if(newPan != int32_min) { pChn->nPan = newPan; // IT compatibility: Sample and instrument panning overrides channel surround status. // Test case: SmpInsPanSurround.it if(m_playBehaviour[kPanOverride] && !m_SongFlags[SONG_SURROUNDPAN]) { pChn->dwFlags.reset(CHN_SURROUND); } } } CHANNELINDEX CSoundFile::GetNNAChannel(CHANNELINDEX nChn) const { const ModChannel *pChn = &m_PlayState.Chn[nChn]; // Check for empty channel const ModChannel *pi = &m_PlayState.Chn[m_nChannels]; for (CHANNELINDEX i = m_nChannels; i < MAX_CHANNELS; i++, pi++) if (!pi->nLength) return i; if (!pChn->nFadeOutVol) return 0; // All channels are used: check for lowest volume CHANNELINDEX result = 0; uint32 vol = (1u << (14 + 9)) / 4u; // 25% uint32 envpos = uint32_max; const ModChannel *pj = &m_PlayState.Chn[m_nChannels]; for (CHANNELINDEX j = m_nChannels; j < MAX_CHANNELS; j++, pj++) { if (!pj->nFadeOutVol) return j; // Use a combination of real volume [14 bit] (which includes volume envelopes, but also potentially global volume) and note volume [9 bit]. // Rationale: We need volume envelopes in case e.g. all NNA channels are playing at full volume but are looping on a 0-volume envelope node. // But if global volume is not applied to master and the global volume temporarily drops to 0, we would kill arbitrary channels. Hence, add the note volume as well. uint32 v = (pj->nRealVolume << 9) | pj->nVolume; if(pj->dwFlags[CHN_LOOP]) v >>= 1; if ((v < vol) || ((v == vol) && (pj->VolEnv.nEnvPosition > envpos))) { envpos = pj->VolEnv.nEnvPosition; vol = v; result = j; } } return result; } CHANNELINDEX CSoundFile::CheckNNA(CHANNELINDEX nChn, uint32 instr, int note, bool forceCut) { CHANNELINDEX nnaChn = CHANNELINDEX_INVALID; ModChannel &srcChn = m_PlayState.Chn[nChn]; const ModInstrument *pIns = nullptr; if(!ModCommand::IsNote(static_cast<ModCommand::NOTE>(note))) { return nnaChn; } // Always NNA cut - using if((!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_MT2)) || !m_nInstruments || forceCut) && !srcChn.HasMIDIOutput()) { if(!srcChn.nLength || srcChn.dwFlags[CHN_MUTE] || !(srcChn.rightVol | srcChn.leftVol)) { return CHANNELINDEX_INVALID; } nnaChn = GetNNAChannel(nChn); if(!nnaChn) return CHANNELINDEX_INVALID; ModChannel &chn = m_PlayState.Chn[nnaChn]; // Copy Channel chn = srcChn; chn.dwFlags.reset(CHN_VIBRATO | CHN_TREMOLO | CHN_MUTE | CHN_PORTAMENTO); chn.nPanbrelloOffset = 0; chn.nMasterChn = nChn + 1; chn.nCommand = CMD_NONE; chn.rowCommand.Clear(); // Cut the note chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); // Stop this channel srcChn.nLength = 0; srcChn.position.Set(0); srcChn.nROfs = srcChn.nLOfs = 0; srcChn.rightVol = srcChn.leftVol = 0; return nnaChn; } if(instr > GetNumInstruments()) instr = 0; const ModSample *pSample = srcChn.pModSample; // If no instrument is given, assume previous instrument to still be valid. // Test case: DNA-NoInstr.it pIns = instr > 0 ? Instruments[instr] : srcChn.pModInstrument; if(pIns != nullptr) { uint32 n = pIns->Keyboard[note - NOTE_MIN]; note = pIns->NoteMap[note - NOTE_MIN]; if ((n) && (n < MAX_SAMPLES)) { pSample = &Samples[n]; } else if(m_playBehaviour[kITEmptyNoteMapSlot] && !pIns->HasValidMIDIChannel()) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it return CHANNELINDEX_INVALID; } } if (srcChn.dwFlags[CHN_MUTE]) return CHANNELINDEX_INVALID; for(CHANNELINDEX i = nChn; i < MAX_CHANNELS; i++) if(i >= m_nChannels || i == nChn) { ModChannel &chn = m_PlayState.Chn[i]; bool applyDNAtoPlug = false; if((chn.nMasterChn == nChn + 1 || i == nChn) && chn.pModInstrument != nullptr) { bool bOk = false; // Duplicate Check Type switch(chn.pModInstrument->nDCT) { // Note case DCT_NOTE: if(note && chn.nNote == note && pIns == chn.pModInstrument) bOk = true; if(pIns && pIns->nMixPlug) applyDNAtoPlug = true; break; // Sample case DCT_SAMPLE: if(pSample != nullptr && pSample == chn.pModSample) bOk = true; break; // Instrument case DCT_INSTRUMENT: if(pIns == chn.pModInstrument) bOk = true; if(pIns && pIns->nMixPlug) applyDNAtoPlug = true; break; // Plugin case DCT_PLUGIN: if(pIns && (pIns->nMixPlug) && (pIns->nMixPlug == chn.pModInstrument->nMixPlug)) { applyDNAtoPlug = true; bOk = true; } break; } // Duplicate Note Action if (bOk) { #ifndef NO_PLUGINS if (applyDNAtoPlug && chn.nNote != NOTE_NONE) { switch(chn.pModInstrument->nDNA) { case DNA_NOTECUT: case DNA_NOTEOFF: case DNA_NOTEFADE: // Switch off duplicated note played on this plugin SendMIDINote(i, chn.GetPluginNote(m_playBehaviour[kITRealNoteMapping]) + NOTE_MAX_SPECIAL, 0); chn.nArpeggioLastNote = NOTE_NONE; break; } } #endif // NO_PLUGINS switch(chn.pModInstrument->nDNA) { // Cut case DNA_NOTECUT: KeyOff(&chn); chn.nVolume = 0; break; // Note Off case DNA_NOTEOFF: KeyOff(&chn); break; // Note Fade case DNA_NOTEFADE: chn.dwFlags.set(CHN_NOTEFADE); break; } if(!chn.nVolume) { chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } } // Do we need to apply New/Duplicate Note Action to a VSTi? bool applyNNAtoPlug = false; #ifndef NO_PLUGINS IMixPlugin *pPlugin = nullptr; if(srcChn.HasMIDIOutput() && ModCommand::IsNote(srcChn.nNote)) // instro sends to a midi chan { PLUGINDEX nPlugin = GetBestPlugin(nChn, PrioritiseInstrument, RespectMutes); if(nPlugin > 0 && nPlugin <= MAX_MIXPLUGINS) { pPlugin = m_MixPlugins[nPlugin-1].pMixPlugin; if(pPlugin) { // apply NNA to this plugin iff it is currently playing a note on this tracker channel // (and if it is playing a note, we know that would be the last note played on this chan). applyNNAtoPlug = pPlugin->IsNotePlaying(srcChn.GetPluginNote(m_playBehaviour[kITRealNoteMapping]), GetBestMidiChannel(nChn), nChn); } } } #endif // NO_PLUGINS // New Note Action if((srcChn.nRealVolume > 0 && srcChn.nLength > 0) || applyNNAtoPlug) { nnaChn = GetNNAChannel(nChn); if(nnaChn != 0) { ModChannel &chn = m_PlayState.Chn[nnaChn]; // Copy Channel chn = srcChn; chn.dwFlags.reset(CHN_VIBRATO | CHN_TREMOLO | CHN_PORTAMENTO); chn.nPanbrelloOffset = 0; chn.nMasterChn = nChn < GetNumChannels() ? nChn + 1 : 0; chn.nCommand = CMD_NONE; #ifndef NO_PLUGINS if(applyNNAtoPlug && pPlugin) { //Move note to the NNA channel (odd, but makes sense with DNA stuff). //Actually a bad idea since it then become very hard to kill some notes. //pPlugin->MoveNote(pChn.nNote, pChn.pModInstrument->nMidiChannel, nChn, n); switch(srcChn.nNNA) { case NNA_NOTEOFF: case NNA_NOTECUT: case NNA_NOTEFADE: //switch off note played on this plugin, on this tracker channel and midi channel //pPlugin->MidiCommand(pChn.pModInstrument->nMidiChannel, pChn.pModInstrument->nMidiProgram, pChn.nNote + NOTE_MAX_SPECIAL, 0, n); SendMIDINote(nChn, NOTE_KEYOFF, 0); srcChn.nArpeggioLastNote = NOTE_NONE; break; } } #endif // NO_PLUGINS // Key Off the note switch(srcChn.nNNA) { case NNA_NOTEOFF: KeyOff(&chn); break; case NNA_NOTECUT: chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE); break; case NNA_NOTEFADE: chn.dwFlags.set(CHN_NOTEFADE); break; } if(!chn.nVolume) { chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } // Stop this channel srcChn.nLength = 0; srcChn.position.Set(0); srcChn.nROfs = srcChn.nLOfs = 0; } } return nnaChn; } bool CSoundFile::ProcessEffects() { ModChannel *pChn = m_PlayState.Chn; ROWINDEX nBreakRow = ROWINDEX_INVALID; // Is changed if a break to row command is encountered ROWINDEX nPatLoopRow = ROWINDEX_INVALID; // Is changed if a pattern loop jump-back is executed ORDERINDEX nPosJump = ORDERINDEX_INVALID; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { const uint32 tickCount = m_PlayState.m_nTickCount % (m_PlayState.m_nMusicSpeed + m_PlayState.m_nFrameDelay); uint32 instr = pChn->rowCommand.instr; ModCommand::VOLCMD volcmd = pChn->rowCommand.volcmd; uint32 vol = pChn->rowCommand.vol; ModCommand::COMMAND cmd = pChn->rowCommand.command; uint32 param = pChn->rowCommand.param; bool bPorta = pChn->rowCommand.IsPortamento(); uint32 nStartTick = 0; pChn->isFirstTick = m_SongFlags[SONG_FIRSTTICK]; // Process parameter control note. if(pChn->rowCommand.note == NOTE_PC) { #ifndef NO_PLUGINS const PLUGINDEX plug = pChn->rowCommand.instr; const PlugParamIndex plugparam = pChn->rowCommand.GetValueVolCol(); const PlugParamValue value = pChn->rowCommand.GetValueEffectCol() / PlugParamValue(ModCommand::maxColumnValue); if(plug > 0 && plug <= MAX_MIXPLUGINS && m_MixPlugins[plug - 1].pMixPlugin) m_MixPlugins[plug-1].pMixPlugin->SetParameter(plugparam, value); #endif // NO_PLUGINS } // Process continuous parameter control note. // Row data is cleared after first tick so on following // ticks using channels m_nPlugParamValueStep to identify // the need for parameter control. The condition cmd == 0 // is to make sure that m_nPlugParamValueStep != 0 because // of NOTE_PCS, not because of macro. if(pChn->rowCommand.note == NOTE_PCS || (cmd == CMD_NONE && pChn->m_plugParamValueStep != 0)) { #ifndef NO_PLUGINS const bool isFirstTick = m_SongFlags[SONG_FIRSTTICK]; if(isFirstTick) pChn->m_RowPlug = pChn->rowCommand.instr; const PLUGINDEX nPlug = pChn->m_RowPlug; const bool hasValidPlug = (nPlug > 0 && nPlug <= MAX_MIXPLUGINS && m_MixPlugins[nPlug-1].pMixPlugin); if(hasValidPlug) { if(isFirstTick) pChn->m_RowPlugParam = ModCommand::GetValueVolCol(pChn->rowCommand.volcmd, pChn->rowCommand.vol); const PlugParamIndex plugparam = pChn->m_RowPlugParam; if(isFirstTick) { PlugParamValue targetvalue = ModCommand::GetValueEffectCol(pChn->rowCommand.command, pChn->rowCommand.param) / PlugParamValue(ModCommand::maxColumnValue); pChn->m_plugParamTargetValue = targetvalue; pChn->m_plugParamValueStep = (targetvalue - m_MixPlugins[nPlug-1].pMixPlugin->GetParameter(plugparam)) / float(GetNumTicksOnCurrentRow()); } if(m_PlayState.m_nTickCount + 1 == GetNumTicksOnCurrentRow()) { // On last tick, set parameter exactly to target value. m_MixPlugins[nPlug-1].pMixPlugin->SetParameter(plugparam, pChn->m_plugParamTargetValue); } else m_MixPlugins[nPlug-1].pMixPlugin->ModifyParameter(plugparam, pChn->m_plugParamValueStep); } #endif // NO_PLUGINS } // Apart from changing parameters, parameter control notes are intended to be 'invisible'. // To achieve this, clearing the note data so that rest of the process sees the row as empty row. if(ModCommand::IsPcNote(pChn->rowCommand.note)) { pChn->ClearRowCmd(); instr = 0; volcmd = VOLCMD_NONE; vol = 0; cmd = CMD_NONE; param = 0; bPorta = false; } // Process Invert Loop (MOD Effect, called every row if it's active) if(!m_SongFlags[SONG_FIRSTTICK]) { InvertLoop(&m_PlayState.Chn[nChn]); } else { if(instr) m_PlayState.Chn[nChn].nEFxOffset = 0; } // Process special effects (note delay, pattern delay, pattern loop) if (cmd == CMD_DELAYCUT) { //:xy --> note delay until tick x, note cut at tick x+y nStartTick = (param & 0xF0) >> 4; const uint32 cutAtTick = nStartTick + (param & 0x0F); NoteCut(nChn, cutAtTick, m_playBehaviour[kITSCxStopsSample]); } else if ((cmd == CMD_MODCMDEX) || (cmd == CMD_S3MCMDEX)) { if ((!param) && (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))) param = pChn->nOldCmdEx; else pChn->nOldCmdEx = static_cast<ModCommand::PARAM>(param); // Note Delay ? if ((param & 0xF0) == 0xD0) { nStartTick = param & 0x0F; if(nStartTick == 0) { //IT compatibility 22. SD0 == SD1 if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) nStartTick = 1; //ST3 ignores notes with SD0 completely else if(GetType() == MOD_TYPE_S3M) continue; } else if(nStartTick >= (m_PlayState.m_nMusicSpeed + m_PlayState.m_nFrameDelay) && m_playBehaviour[kITOutOfRangeDelay]) { // IT compatibility 08. Handling of out-of-range delay command. // Additional test case: tickdelay.it if(instr) { pChn->nNewIns = static_cast<ModCommand::INSTR>(instr); } continue; } } else if(m_SongFlags[SONG_FIRSTTICK]) { // Pattern Loop ? if((((param & 0xF0) == 0x60 && cmd == CMD_MODCMDEX) || ((param & 0xF0) == 0xB0 && cmd == CMD_S3MCMDEX)) && !(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])) // not even effects are processed on muted S3M channels { ROWINDEX nloop = PatternLoop(pChn, param & 0x0F); if (nloop != ROWINDEX_INVALID) { // FT2 compatibility: E6x overwrites jump targets of Dxx effects that are located left of the E6x effect. // Test cases: PatLoop-Jumps.xm, PatLoop-Various.xm if(nBreakRow != ROWINDEX_INVALID && m_playBehaviour[kFT2PatternLoopWithJumps]) { nBreakRow = nloop; } nPatLoopRow = nloop; } if(GetType() == MOD_TYPE_S3M) { // ST3 doesn't have per-channel pattern loop memory, so spam all changes to other channels as well. for (CHANNELINDEX i = 0; i < GetNumChannels(); i++) { m_PlayState.Chn[i].nPatternLoop = pChn->nPatternLoop; m_PlayState.Chn[i].nPatternLoopCount = pChn->nPatternLoopCount; } } } else if ((param & 0xF0) == 0xE0) { // Pattern Delay // In Scream Tracker 3 / Impulse Tracker, only the first delay command on this row is considered. // Test cases: PatternDelays.it, PatternDelays.s3m, PatternDelays.xm // XXX In Scream Tracker 3, the "left" channels are evaluated before the "right" channels, which is not emulated here! if(!(GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)) || !m_PlayState.m_nPatternDelay) { if(!(GetType() & (MOD_TYPE_S3M)) || (param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. m_PlayState.m_nPatternDelay = 1 + (param & 0x0F); } } } } } if(GetType() == MOD_TYPE_MTM && cmd == CMD_MODCMDEX && (param & 0xF0) == 0xD0) { // Apparently, retrigger and note delay have the same behaviour in MultiTracker: // They both restart the note at tick x, and if there is a note on the same row, // this note is started on the first tick. nStartTick = 0; param = 0x90 | (param & 0x0F); } if(nStartTick != 0 && pChn->rowCommand.note == NOTE_KEYOFF && pChn->rowCommand.volcmd == VOLCMD_PANNING && m_playBehaviour[kFT2PanWithDelayedNoteOff]) { // FT2 compatibility: If there's a delayed note off, panning commands are ignored. WTF! // Test case: PanOff.xm pChn->rowCommand.volcmd = VOLCMD_NONE; } bool triggerNote = (m_PlayState.m_nTickCount == nStartTick); // Can be delayed by a note delay effect if(m_playBehaviour[kFT2OutOfRangeDelay] && nStartTick >= m_PlayState.m_nMusicSpeed) { // FT2 compatibility: Note delays greater than the song speed should be ignored. // However, EEx pattern delay is *not* considered at all. // Test case: DelayCombination.xm, PortaDelay.xm triggerNote = false; } else if(m_playBehaviour[kRowDelayWithNoteDelay] && nStartTick > 0 && tickCount == nStartTick) { // IT compatibility: Delayed notes (using SDx) that are on the same row as a Row Delay effect are retriggered. // ProTracker / Scream Tracker 3 / FastTracker 2 do the same. // Test case: PatternDelay-NoteDelay.it, PatternDelay-NoteDelay.xm, PatternDelaysRetrig.mod triggerNote = true; } // IT compatibility: Tick-0 vs non-tick-0 effect distinction is always based on tick delay. // Test case: SlideDelay.it if(m_playBehaviour[kITFirstTickHandling]) { pChn->isFirstTick = tickCount == nStartTick; } // FT2 compatibility: Note + portamento + note delay = no portamento // Test case: PortaDelay.xm if(m_playBehaviour[kFT2PortaDelay] && nStartTick != 0) { bPorta = false; } if(m_SongFlags[SONG_PT_MODE] && instr && !m_PlayState.m_nTickCount) { // Instrument number resets the stacked ProTracker offset. // Test case: ptoffset.mod pChn->proTrackerOffset = 0; // ProTracker compatibility: Sample properties are always loaded on the first tick, even when there is a note delay. // Test case: InstrDelay.mod if(!triggerNote && pChn->IsSamplePlaying()) { pChn->nNewIns = static_cast<ModCommand::INSTR>(instr); if(instr <= GetNumSamples()) { pChn->nVolume = Samples[instr].nVolume; pChn->nFineTune = Samples[instr].nFineTune; } } } // Handles note/instrument/volume changes if(triggerNote) { ModCommand::NOTE note = pChn->rowCommand.note; if(instr) pChn->nNewIns = static_cast<ModCommand::INSTR>(instr); if(ModCommand::IsNote(note) && m_playBehaviour[kFT2Transpose]) { // Notes that exceed FT2's limit are completely ignored. // Test case: NoteLimit.xm int transpose = pChn->nTranspose; if(instr && !bPorta) { // Refresh transpose // Test case: NoteLimit2.xm SAMPLEINDEX sample = SAMPLEINDEX_INVALID; if(GetNumInstruments()) { // Instrument mode if(instr <= GetNumInstruments() && Instruments[instr] != nullptr) { sample = Instruments[instr]->Keyboard[note - NOTE_MIN]; } } else { // Sample mode sample = static_cast<SAMPLEINDEX>(instr); } if(sample <= GetNumSamples()) { transpose = GetSample(sample).RelativeTone; } } const int computedNote = note + transpose; if((computedNote < NOTE_MIN + 11 || computedNote > NOTE_MIN + 130)) { note = NOTE_NONE; } } else if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && GetNumInstruments() != 0 && ModCommand::IsNoteOrEmpty(static_cast<ModCommand::NOTE>(note))) { // IT compatibility: Invalid instrument numbers do nothing, but they are remembered for upcoming notes and do not trigger a note in that case. // Test case: InstrumentNumberChange.it INSTRUMENTINDEX instrToCheck = static_cast<INSTRUMENTINDEX>((instr != 0) ? instr : pChn->nOldIns); if(instrToCheck != 0 && (instrToCheck > GetNumInstruments() || Instruments[instrToCheck] == nullptr)) { note = NOTE_NONE; instr = 0; } } // XM: FT2 ignores a note next to a K00 effect, and a fade-out seems to be done when no volume envelope is present (not exactly the Kxx behaviour) if(cmd == CMD_KEYOFF && param == 0 && m_playBehaviour[kFT2KeyOff]) { note = NOTE_NONE; instr = 0; } bool retrigEnv = note == NOTE_NONE && instr != 0; // Apparently, any note number in a pattern causes instruments to recall their original volume settings - no matter if there's a Note Off next to it or whatever. // Test cases: keyoff+instr.xm, delay.xm bool reloadSampleSettings = (m_playBehaviour[kFT2ReloadSampleSettings] && instr != 0); // ProTracker Compatibility: If a sample was stopped before, lone instrument numbers can retrigger it // Test case: PTSwapEmpty.mod bool keepInstr = (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (m_playBehaviour[kMODSampleSwap] && !pChn->IsSamplePlaying() && pChn->pModSample != nullptr && !pChn->pModSample->HasSampleData()); // Now it's time for some FT2 crap... if (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)) { // XM: Key-Off + Sample == Note Cut (BUT: Only if no instr number or volume effect is present!) // Test case: NoteOffVolume.xm if(note == NOTE_KEYOFF && ((!instr && volcmd != VOLCMD_VOLUME && cmd != CMD_VOLUME) || !m_playBehaviour[kFT2KeyOff]) && (pChn->pModInstrument == nullptr || !pChn->pModInstrument->VolEnv.dwFlags[ENV_ENABLED])) { pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->nVolume = 0; note = NOTE_NONE; instr = 0; retrigEnv = false; // FT2 Compatbility: Start fading the note for notes with no delay. Only relevant when a volume command is encountered after the note-off. // Test case: NoteOffFadeNoEnv.xm if(m_SongFlags[SONG_FIRSTTICK] && m_playBehaviour[kFT2NoteOffFlags]) pChn->dwFlags.set(CHN_NOTEFADE); } else if(m_playBehaviour[kFT2RetrigWithNoteDelay] && !m_SongFlags[SONG_FIRSTTICK]) { // FT2 Compatibility: Some special hacks for rogue note delays... (EDx with x > 0) // Apparently anything that is next to a note delay behaves totally unpredictable in FT2. Swedish tracker logic. :) retrigEnv = true; // Portamento + Note Delay = No Portamento // Test case: porta-delay.xm bPorta = false; if(note == NOTE_NONE) { // If there's a note delay but no real note, retrig the last note. // Test case: delay2.xm, delay3.xm note = static_cast<ModCommand::NOTE>(pChn->nNote - pChn->nTranspose); } else if(note >= NOTE_MIN_SPECIAL) { // Gah! Even Note Off + Note Delay will cause envelopes to *retrigger*! How stupid is that? // ... Well, and that is actually all it does if there's an envelope. No fade out, no nothing. *sigh* // Test case: OffDelay.xm note = NOTE_NONE; keepInstr = false; reloadSampleSettings = true; } else { // Normal note keepInstr = true; reloadSampleSettings = true; } } } if((retrigEnv && !m_playBehaviour[kFT2ReloadSampleSettings]) || reloadSampleSettings) { const ModSample *oldSample = nullptr; // Reset default volume when retriggering envelopes if(GetNumInstruments()) { oldSample = pChn->pModSample; } else if (instr <= GetNumSamples()) { // Case: Only samples are used; no instruments. oldSample = &Samples[instr]; } if(oldSample != nullptr) { if(!oldSample->uFlags[SMP_NODEFAULTVOLUME]) pChn->nVolume = oldSample->nVolume; if(reloadSampleSettings) { // Also reload panning pChn->nPan = oldSample->nPan; } } } // FT2 compatibility: Instrument number disables tremor effect // Test case: TremorInstr.xm, TremoRecover.xm if(m_playBehaviour[kFT2Tremor] && instr != 0) { pChn->nTremorCount = 0x20; } if(retrigEnv) //Case: instrument with no note data. { //IT compatibility: Instrument with no note. if(m_playBehaviour[kITInstrWithoutNote] || GetType() == MOD_TYPE_PLM) { // IT compatibility: Completely retrigger note after sample end to also reset portamento. // Test case: PortaResetAfterRetrigger.it bool triggerAfterSmpEnd = m_playBehaviour[kITMultiSampleInstrumentNumber] && !pChn->IsSamplePlaying(); if(GetNumInstruments()) { // Instrument mode if(instr <= GetNumInstruments() && (pChn->pModInstrument != Instruments[instr] || triggerAfterSmpEnd)) note = pChn->nNote; } else { // Sample mode if(instr < MAX_SAMPLES && (pChn->pModSample != &Samples[instr] || triggerAfterSmpEnd)) note = pChn->nNote; } } if (GetNumInstruments() && (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) { pChn->ResetEnvelopes(); pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->dwFlags.reset(CHN_NOTEFADE); pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; pChn->nFadeOutVol = 65536; // FT2 Compatbility: Reset key-off status with instrument number // Test case: NoteOffInstrChange.xm if(m_playBehaviour[kFT2NoteOffFlags]) pChn->dwFlags.reset(CHN_KEYOFF); } if (!keepInstr) instr = 0; } // Note Cut/Off/Fade => ignore instrument if (note >= NOTE_MIN_SPECIAL) { // IT compatibility: Default volume of sample is recalled if instrument number is next to a note-off. // Test case: NoteOffInstr.it, noteoff2.it if(m_playBehaviour[kITInstrWithNoteOff] && instr) { SAMPLEINDEX smp = static_cast<SAMPLEINDEX>(instr); if(GetNumInstruments()) { smp = 0; if(instr <= GetNumInstruments() && Instruments[instr] != nullptr && ModCommand::IsNote(pChn->nLastNote)) { smp = Instruments[instr]->Keyboard[pChn->nLastNote - NOTE_MIN]; } } if(smp > 0 && smp <= GetNumSamples() && !Samples[smp].uFlags[SMP_NODEFAULTVOLUME]) pChn->nVolume = Samples[smp].nVolume; } instr = 0; } if(ModCommand::IsNote(note)) { pChn->nNewNote = pChn->nLastNote = note; // New Note Action ? if(!bPorta) { CheckNNA(nChn, instr, note, false); } } if(note) { if(pChn->nRestorePanOnNewNote > 0) { pChn->nPan = pChn->nRestorePanOnNewNote - 1; pChn->nRestorePanOnNewNote = 0; } if(pChn->nRestoreResonanceOnNewNote > 0) { pChn->nResonance = pChn->nRestoreResonanceOnNewNote - 1; pChn->nRestoreResonanceOnNewNote = 0; } if(pChn->nRestoreCutoffOnNewNote > 0) { pChn->nCutOff = pChn->nRestoreCutoffOnNewNote - 1; pChn->nRestoreCutoffOnNewNote = 0; } } // Instrument Change ? if(instr) { const ModSample *oldSample = pChn->pModSample; //const ModInstrument *oldInstrument = pChn->pModInstrument; InstrumentChange(pChn, instr, bPorta, true); // IT compatibility: Keep new instrument number for next instrument-less note even if sample playback is stopped // Test case: StoppedInstrSwap.it if(GetType() == MOD_TYPE_MOD) { // Test case: PortaSwapPT.mod if(!bPorta || !m_playBehaviour[kMODSampleSwap]) pChn->nNewIns = 0; } else { if(!m_playBehaviour[kITInstrWithNoteOff] || ModCommand::IsNote(note)) pChn->nNewIns = 0; } if(m_playBehaviour[kITPortamentoSwapResetsPos]) { // Test cases: PortaInsNum.it, PortaSample.it if(ModCommand::IsNote(note) && oldSample != pChn->pModSample) { //const bool newInstrument = oldInstrument != pChn->pModInstrument && pChn->pModInstrument->Keyboard[pChn->nNewNote - NOTE_MIN] != 0; pChn->position.Set(0); } } else if ((GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT) && oldSample != pChn->pModSample && ModCommand::IsNote(note))) { // Special IT case: portamento+note causes sample change -> ignore portamento bPorta = false; } else if(m_playBehaviour[kMODSampleSwap] && pChn->increment.IsZero()) { // If channel was paused and is resurrected by a lone instrument number, reset the sample position. // Test case: PTSwapEmpty.mod pChn->position.Set(0); } } // New Note ? if (note) { if ((!instr) && (pChn->nNewIns) && (note < 0x80)) { InstrumentChange(pChn, pChn->nNewIns, bPorta, pChn->pModSample == nullptr && pChn->pModInstrument == nullptr, !(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))); pChn->nNewIns = 0; } NoteChange(pChn, note, bPorta, !(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))); if ((bPorta) && (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) && (instr)) { pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->ResetEnvelopes(); pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } } // Tick-0 only volume commands if (volcmd == VOLCMD_VOLUME) { if (vol > 64) vol = 64; pChn->nVolume = vol << 2; pChn->dwFlags.set(CHN_FASTVOLRAMP); } else if (volcmd == VOLCMD_PANNING) { Panning(pChn, vol, Pan6bit); } #ifndef NO_PLUGINS if (m_nInstruments) ProcessMidiOut(nChn); #endif // NO_PLUGINS } if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; // Volume Column Effect (except volume & panning) /* A few notes, paraphrased from ITTECH.TXT by Storlek (creator of schismtracker): Ex/Fx/Gx are shared with Exx/Fxx/Gxx; Ex/Fx are 4x the 'normal' slide value Gx is linked with Ex/Fx if Compat Gxx is off, just like Gxx is with Exx/Fxx Gx values: 1, 4, 8, 16, 32, 64, 96, 128, 255 Ax/Bx/Cx/Dx values are used directly (i.e. D9 == D09), and are NOT shared with Dxx (value is stored into nOldVolParam and used by A0/B0/C0/D0) Hx uses the same value as Hxx and Uxx, and affects the *depth* so... hxx = (hx | (oldhxx & 0xf0)) ??? TODO is this done correctly? */ bool doVolumeColumn = m_PlayState.m_nTickCount >= nStartTick; // FT2 compatibility: If there's a note delay, volume column effects are NOT executed // on the first tick and, if there's an instrument number, on the delayed tick. // Test case: VolColDelay.xm, PortaDelay.xm if(m_playBehaviour[kFT2VolColDelay] && nStartTick != 0) { doVolumeColumn = m_PlayState.m_nTickCount != 0 && (m_PlayState.m_nTickCount != nStartTick || (pChn->rowCommand.instr == 0 && volcmd != VOLCMD_TONEPORTAMENTO)); } if(volcmd > VOLCMD_PANNING && doVolumeColumn) { if (volcmd == VOLCMD_TONEPORTAMENTO) { uint32 porta = 0; if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DMF | MOD_TYPE_DBM | MOD_TYPE_IMF | MOD_TYPE_PSM | MOD_TYPE_J2B | MOD_TYPE_ULT | MOD_TYPE_OKT | MOD_TYPE_MT2 | MOD_TYPE_MDL)) { porta = ImpulseTrackerPortaVolCmd[vol & 0x0F]; } else { if(cmd == CMD_TONEPORTAMENTO && GetType() == MOD_TYPE_XM) { // Yes, FT2 is *that* weird. If there is a Mx command in the volume column // and a normal 3xx command, the 3xx command is ignored but the Mx command's // effectiveness is doubled. // Test case: TonePortamentoMemory.xm cmd = CMD_NONE; vol *= 2; } porta = vol << 4; // FT2 compatibility: If there's a portamento and a note delay, execute the portamento, but don't update the parameter // Test case: PortaDelay.xm if(m_playBehaviour[kFT2PortaDelay] && nStartTick != 0) { porta = 0; } } TonePortamento(pChn, porta); } else { // FT2 Compatibility: FT2 ignores some volume commands with parameter = 0. if(m_playBehaviour[kFT2VolColMemory] && vol == 0) { switch(volcmd) { case VOLCMD_VOLUME: case VOLCMD_PANNING: case VOLCMD_VIBRATODEPTH: break; case VOLCMD_PANSLIDELEFT: // FT2 Compatibility: Pan slide left with zero parameter causes panning to be set to full left on every non-row tick. // Test case: PanSlideZero.xm if(!m_SongFlags[SONG_FIRSTTICK]) { pChn->nPan = 0; } MPT_FALLTHROUGH; default: // no memory here. volcmd = VOLCMD_NONE; } } else if(!m_playBehaviour[kITVolColMemory]) { // IT Compatibility: Effects in the volume column don't have an unified memory. // Test case: VolColMemory.it if(vol) pChn->nOldVolParam = static_cast<ModCommand::PARAM>(vol); else vol = pChn->nOldVolParam; } switch(volcmd) { case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } else { pChn->nOldVolParam = static_cast<ModCommand::PARAM>(vol); } VolumeSlide(pChn, static_cast<ModCommand::PARAM>(volcmd == VOLCMD_VOLSLIDEUP ? (vol << 4) : vol)); break; case VOLCMD_FINEVOLUP: // IT Compatibility: Fine volume slides in the volume column are only executed on the first tick, not on multiples of the first tick in case of pattern delay // Test case: FineVolColSlide.it if(m_PlayState.m_nTickCount == nStartTick || !m_playBehaviour[kITVolColMemory]) { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it FineVolumeUp(pChn, static_cast<ModCommand::PARAM>(vol), m_playBehaviour[kITVolColMemory]); } break; case VOLCMD_FINEVOLDOWN: // IT Compatibility: Fine volume slides in the volume column are only executed on the first tick, not on multiples of the first tick in case of pattern delay // Test case: FineVolColSlide.it if(m_PlayState.m_nTickCount == nStartTick || !m_playBehaviour[kITVolColMemory]) { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it FineVolumeDown(pChn, static_cast<ModCommand::PARAM>(vol), m_playBehaviour[kITVolColMemory]); } break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the "set vibrato speed" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = vol & 0x0F; else Vibrato(pChn, vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, vol); break; case VOLCMD_PANSLIDELEFT: PanningSlide(pChn, static_cast<ModCommand::PARAM>(vol), !m_playBehaviour[kFT2VolColMemory]); break; case VOLCMD_PANSLIDERIGHT: PanningSlide(pChn, static_cast<ModCommand::PARAM>(vol << 4), !m_playBehaviour[kFT2VolColMemory]); break; case VOLCMD_PORTAUP: // IT compatibility (one of the first testcases - link effect memory) PortamentoUp(nChn, static_cast<ModCommand::PARAM>(vol << 2), m_playBehaviour[kITVolColFinePortamento]); break; case VOLCMD_PORTADOWN: // IT compatibility (one of the first testcases - link effect memory) PortamentoDown(nChn, static_cast<ModCommand::PARAM>(vol << 2), m_playBehaviour[kITVolColFinePortamento]); break; case VOLCMD_OFFSET: if (triggerNote && pChn->pModSample && vol <= CountOf(pChn->pModSample->cues)) { SmpLength offset; if(vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[vol - 1]; SampleOffset(*pChn, offset); } break; } } } // Effects if(cmd != CMD_NONE) switch (cmd) { // Set Volume case CMD_VOLUME: if(m_SongFlags[SONG_FIRSTTICK]) { pChn->nVolume = (param < 64) ? param * 4 : 256; pChn->dwFlags.set(CHN_FASTVOLRAMP); } break; // Portamento Up case CMD_PORTAMENTOUP: if ((!param) && (GetType() & MOD_TYPE_MOD)) break; PortamentoUp(nChn, static_cast<ModCommand::PARAM>(param)); break; // Portamento Down case CMD_PORTAMENTODOWN: if ((!param) && (GetType() & MOD_TYPE_MOD)) break; PortamentoDown(nChn, static_cast<ModCommand::PARAM>(param)); break; // Volume Slide case CMD_VOLUMESLIDE: if (param || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param)); break; // Tone-Portamento case CMD_TONEPORTAMENTO: TonePortamento(pChn, param); break; // Tone-Portamento + Volume Slide case CMD_TONEPORTAVOL: if ((param) || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param)); TonePortamento(pChn, 0); break; // Vibrato case CMD_VIBRATO: Vibrato(pChn, param); break; // Vibrato + Volume Slide case CMD_VIBRATOVOL: if ((param) || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param)); Vibrato(pChn, 0); break; // Set Speed case CMD_SPEED: if(m_SongFlags[SONG_FIRSTTICK]) SetSpeed(m_PlayState, param); break; // Set Tempo case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(m_SongFlags[SONG_FIRSTTICK] && param != 0) SetSpeed(m_PlayState, param); break; } { param = CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn); if (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT)) { if (param) pChn->nOldTempo = static_cast<ModCommand::PARAM>(param); else param = pChn->nOldTempo; } TEMPO t(param, 0); LimitMax(t, GetModSpecifications().GetTempoMax()); SetTempo(t); } break; // Set Offset case CMD_OFFSET: if (triggerNote) { // FT2 compatibility: Portamento + Offset = Ignore offset // Test case: porta-offset.xm if(bPorta && GetType() == MOD_TYPE_XM) { break; } bool isExtended = false; SmpLength offset = CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn, &isExtended); if(!isExtended) { // No X-param (normal behaviour) offset <<= 8; if (offset) pChn->oldOffset = offset; else offset = pChn->oldOffset; offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } break; // Disorder Tracker 2 percentage offset case CMD_OFFSETPERCENTAGE: if(triggerNote) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, param, 255)); } break; // Arpeggio case CMD_ARPEGGIO: // IT compatibility 01. Don't ignore Arpeggio if no note is playing (also valid for ST3) if(m_PlayState.m_nTickCount) break; if((!pChn->nPeriod || !pChn->nNote) && (pChn->pModInstrument == nullptr || !pChn->pModInstrument->HasValidMIDIChannel()) // Plugin arpeggio && !m_playBehaviour[kITArpeggio] && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) break; if (!param && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MOD))) break; // Only important when editing MOD/XM files (000 effects are removed when loading files where this means "no effect") pChn->nCommand = CMD_ARPEGGIO; if (param) pChn->nArpeggio = static_cast<ModCommand::PARAM>(param); break; // Retrig case CMD_RETRIG: if (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) { if (!(param & 0xF0)) param |= pChn->nRetrigParam & 0xF0; if (!(param & 0x0F)) param |= pChn->nRetrigParam & 0x0F; param |= 0x100; // increment retrig count on first row } // IT compatibility 15. Retrigger if(m_playBehaviour[kITRetrigger]) { if (param) pChn->nRetrigParam = static_cast<uint8>(param & 0xFF); RetrigNote(nChn, pChn->nRetrigParam, (volcmd == VOLCMD_OFFSET) ? vol + 1 : 0); } else { // XM Retrig if (param) pChn->nRetrigParam = static_cast<uint8>(param & 0xFF); else param = pChn->nRetrigParam; RetrigNote(nChn, param, (volcmd == VOLCMD_OFFSET) ? vol + 1 : 0); } break; // Tremor case CMD_TREMOR: if(!m_SongFlags[SONG_FIRSTTICK]) { break; } // IT compatibility 12. / 13. Tremor (using modified DUMB's Tremor logic here because of old effects - http://dumb.sf.net/) if(m_playBehaviour[kITTremor]) { if(param && !m_SongFlags[SONG_ITOLDEFFECTS]) { // Old effects have different length interpretation (+1 for both on and off) if(param & 0xF0) param -= 0x10; if(param & 0x0F) param -= 0x01; } pChn->nTremorCount |= 0x80; // set on/off flag } else if(m_playBehaviour[kFT2Tremor]) { // XM Tremor. Logic is being processed in sndmix.cpp pChn->nTremorCount |= 0x80; // set on/off flag } pChn->nCommand = CMD_TREMOR; if (param) pChn->nTremorParam = static_cast<ModCommand::PARAM>(param); break; // Set Global Volume case CMD_GLOBALVOLUME: // IT compatibility: Only apply global volume on first tick (and multiples) // Test case: GlobalVolFirstTick.it if(!m_SongFlags[SONG_FIRSTTICK]) break; // ST3 applies global volume on tick 1 and does other weird things, but we won't emulate this for now. // if(((GetType() & MOD_TYPE_S3M) && m_nTickCount != 1) // || (!(GetType() & MOD_TYPE_S3M) && !m_SongFlags[SONG_FIRSTTICK])) // { // break; // } // FT2 compatibility: On channels that are "left" of the global volume command, the new global volume is not applied // until the second tick of the row. Since we apply global volume on the mix buffer rather than note volumes, this // cannot be fixed for now. // Test case: GlobalVolume.xm // if(IsCompatibleMode(TRK_FASTTRACKER2) && m_SongFlags[SONG_FIRSTTICK] && m_nMusicSpeed > 1) // { // break; // } if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values. // Test case: globalvol-invalid.it if(param <= 128) { m_PlayState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { m_PlayState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: //IT compatibility 16. Saving last global volume slide param per channel (FT2/IT) if(m_playBehaviour[kPerChannelGlobalVolSlide]) GlobalVolSlide(static_cast<ModCommand::PARAM>(param), pChn->nOldGlobalVolSlide); else GlobalVolSlide(static_cast<ModCommand::PARAM>(param), m_PlayState.Chn[0].nOldGlobalVolSlide); break; // Set 8-bit Panning case CMD_PANNING8: if(m_SongFlags[SONG_FIRSTTICK]) { Panning(pChn, param, Pan8bit); } break; // Panning Slide case CMD_PANNINGSLIDE: PanningSlide(pChn, static_cast<ModCommand::PARAM>(param)); break; // Tremolo case CMD_TREMOLO: Tremolo(pChn, param); break; // Fine Vibrato case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; // MOD/XM Exx Extended Commands case CMD_MODCMDEX: ExtendedMODCommands(nChn, static_cast<ModCommand::PARAM>(param)); break; // S3M/IT Sxx Extended Commands case CMD_S3MCMDEX: if(m_playBehaviour[kST3EffectMemory] && param == 0) { param = pChn->nArpeggio; // S00 uses the last non-zero effect parameter as memory, like other effects including Arpeggio, so we "borrow" our memory there. } ExtendedS3MCommands(nChn, static_cast<ModCommand::PARAM>(param)); break; // Key Off case CMD_KEYOFF: // This is how Key Off is supposed to sound... (in FT2 at least) if(m_playBehaviour[kFT2KeyOff]) { if (m_PlayState.m_nTickCount == param) { // XM: Key-Off + Sample == Note Cut if(pChn->pModInstrument == nullptr || !pChn->pModInstrument->VolEnv.dwFlags[ENV_ENABLED]) { if(param == 0 && (pChn->rowCommand.instr || pChn->rowCommand.volcmd != VOLCMD_NONE)) // FT2 is weird.... { pChn->dwFlags.set(CHN_NOTEFADE); } else { pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->nVolume = 0; } } KeyOff(pChn); } } // This is how it's NOT supposed to sound... else { if(m_SongFlags[SONG_FIRSTTICK]) KeyOff(pChn); } break; // Extra-fine porta up/down case CMD_XFINEPORTAUPDOWN: switch(param & 0xF0) { case 0x10: ExtraFinePortamentoUp(pChn, param & 0x0F); break; case 0x20: ExtraFinePortamentoDown(pChn, param & 0x0F); break; // ModPlug XM Extensions (ignore in compatible mode) case 0x50: case 0x60: case 0x70: case 0x90: case 0xA0: if(!m_playBehaviour[kFT2RestrictXCommand]) ExtendedS3MCommands(nChn, static_cast<ModCommand::PARAM>(param)); break; } break; // Set Channel Global Volume case CMD_CHANNELVOLUME: if(!m_SongFlags[SONG_FIRSTTICK]) break; if (param <= 64) { pChn->nGlobalVol = param; pChn->dwFlags.set(CHN_FASTVOLRAMP); } break; // Channel volume slide case CMD_CHANNELVOLSLIDE: ChannelVolSlide(pChn, static_cast<ModCommand::PARAM>(param)); break; // Panbrello (IT) case CMD_PANBRELLO: Panbrello(pChn, param); break; // Set Envelope Position case CMD_SETENVPOSITION: if(m_SongFlags[SONG_FIRSTTICK]) { pChn->VolEnv.nEnvPosition = param; // FT2 compatibility: FT2 only sets the position of the panning envelope if the volume envelope's sustain flag is set // Test case: SetEnvPos.xm if(!m_playBehaviour[kFT2SetPanEnvPos] || pChn->VolEnv.flags[ENV_SUSTAIN]) { pChn->PanEnv.nEnvPosition = param; pChn->PitchEnv.nEnvPosition = param; } } break; // Position Jump case CMD_POSITIONJUMP: m_PlayState.m_nNextPatStartRow = 0; // FT2 E60 bug nPosJump = static_cast<ORDERINDEX>(CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn)); // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if((GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)) && nBreakRow != ROWINDEX_INVALID) { nBreakRow = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(m_PlayState, nChn, static_cast<ModCommand::PARAM>(param)); if(row != ROWINDEX_INVALID) { nBreakRow = row; if(m_SongFlags[SONG_PATTERNLOOP]) { //If song is set to loop and a pattern break occurs we should stay on the same pattern. //Use nPosJump to force playback to "jump to this pattern" rather than move to next, as by default. //rewbs.to nPosJump = m_PlayState.m_nCurrentOrder; } } } break; // IMF / PTM Note Slides case CMD_NOTESLIDEUP: case CMD_NOTESLIDEDOWN: case CMD_NOTESLIDEUPRETRIG: case CMD_NOTESLIDEDOWNRETRIG: // Note that this command seems to be a bit buggy in Polytracker... Luckily, no tune seems to seriously use this // (Vic uses it e.g. in Spaceman or Perfect Reason to slide effect samples, noone will notice the difference :) NoteSlide(pChn, param, cmd == CMD_NOTESLIDEUP || cmd == CMD_NOTESLIDEUPRETRIG, cmd == CMD_NOTESLIDEUPRETRIG || cmd == CMD_NOTESLIDEDOWNRETRIG); break; // PTM Reverse sample + offset (executed on every tick) case CMD_REVERSEOFFSET: ReverseSampleOffset(*pChn, static_cast<ModCommand::PARAM>(param)); break; #ifndef NO_PLUGINS // DBM: Toggle DSP Echo case CMD_DBMECHO: if(m_PlayState.m_nTickCount == 0) { uint32 chns = (param >> 4), enable = (param & 0x0F); if(chns > 1 || enable > 2) { break; } CHANNELINDEX firstChn = nChn, lastChn = nChn; if(chns == 1) { firstChn = 0; lastChn = m_nChannels - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { ChnSettings[c].dwFlags.set(CHN_NOFX, enable == 1); m_PlayState.Chn[c].dwFlags.set(CHN_NOFX, enable == 1); } } break; #endif // NO_PLUGINS } if(m_playBehaviour[kST3EffectMemory] && param != 0) { UpdateS3MEffectMemory(pChn, static_cast<ModCommand::PARAM>(param)); } if(pChn->rowCommand.instr) { // Not necessarily consistent with actually playing instrument for IT compatibility pChn->nOldIns = pChn->rowCommand.instr; } } // for(...) end // Navigation Effects if(m_SongFlags[SONG_FIRSTTICK]) { const bool doPatternLoop = (nPatLoopRow != ROWINDEX_INVALID); const bool doBreakRow = (nBreakRow != ROWINDEX_INVALID); const bool doPosJump = (nPosJump != ORDERINDEX_INVALID); // Pattern Loop if(doPatternLoop) { m_PlayState.m_nNextOrder = m_PlayState.m_nCurrentOrder; m_PlayState.m_nNextRow = nPatLoopRow; if(m_PlayState.m_nPatternDelay) { m_PlayState.m_nNextRow++; } // IT Compatibility: If the restart row is past the end of the current pattern // (e.g. when continued from a previous pattern without explicit SB0 effect), continue the next pattern. // Test case: LoopStartAfterPatternEnd.it if(nPatLoopRow >= Patterns[m_PlayState.m_nPattern].GetNumRows()) { m_PlayState.m_nNextOrder++; m_PlayState.m_nNextRow = 0; } // As long as the pattern loop is running, mark the looped rows as not visited yet visitedSongRows.ResetPatternLoop(m_PlayState.m_nCurrentOrder, nPatLoopRow); } // Pattern Break / Position Jump only if no loop running // Exception: FastTracker 2 in all cases, Impulse Tracker in case of position jump // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if((doBreakRow || doPosJump) && (!doPatternLoop || m_playBehaviour[kFT2PatternLoopWithJumps] || (m_playBehaviour[kITPatternLoopWithJumps] && doPosJump))) { if(!doPosJump) nPosJump = m_PlayState.m_nCurrentOrder + 1; if(!doBreakRow) nBreakRow = 0; m_SongFlags.set(SONG_BREAKTOROW); if(nPosJump >= Order().size()) { nPosJump = Order().GetRestartPos(); } // IT / FT2 compatibility: don't reset loop count on pattern break. // Test case: gm-trippy01.it, PatLoop-Break.xm, PatLoop-Weird.xm, PatLoop-Break.mod if(nPosJump != m_PlayState.m_nCurrentOrder && !m_playBehaviour[kITPatternLoopBreak] && !m_playBehaviour[kFT2PatternLoopWithJumps] && GetType() != MOD_TYPE_MOD) { for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { m_PlayState.Chn[i].nPatternLoopCount = 0; } } m_PlayState.m_nNextRow = nBreakRow; if(!m_SongFlags[SONG_PATTERNLOOP]) m_PlayState.m_nNextOrder = nPosJump; } } return true; } //////////////////////////////////////////////////////////// // Channels effects // Update the effect memory of all S3M effects that use the last non-zero effect parameter as memory (Dxy, Exx, Fxx, Ixy, Jxy, Kxy, Lxy, Qxy, Rxy, Sxy) // Test case: ParamMemory.s3m void CSoundFile::UpdateS3MEffectMemory(ModChannel *pChn, ModCommand::PARAM param) const { pChn->nOldVolumeSlide = param; // Dxy / Kxy / Lxy pChn->nOldPortaUp = param; // Exx / Fxx pChn->nOldPortaDown = param; // Exx / Fxx pChn->nTremorParam = param; // Ixy pChn->nArpeggio = param; // Jxy pChn->nRetrigParam = param; // Qxy pChn->nTremoloDepth = (param & 0x0F) << 2; // Rxy pChn->nTremoloSpeed = (param >> 4) & 0x0F; // Rxy // Sxy is not handled here. } // Calculate full parameter for effects that support parameter extension at the given pattern location. // maxCommands sets the maximum number of XParam commands to look at for this effect // isExtended returns if the command is actually using any XParam extensions. uint32 CSoundFile::CalculateXParam(PATTERNINDEX pat, ROWINDEX row, CHANNELINDEX chn, bool *isExtended) const { if(isExtended != nullptr) *isExtended = false; ROWINDEX maxCommands = 4; const ModCommand *m = Patterns[pat].GetpModCommand(row, chn); uint32 val = m->param; switch(m->command) { case CMD_OFFSET: // 24 bit command maxCommands = 2; break; case CMD_TEMPO: case CMD_PATTERNBREAK: case CMD_POSITIONJUMP: // 16 bit command maxCommands = 1; break; default: return val; } const bool xmTempoFix = m->command == CMD_TEMPO && GetType() == MOD_TYPE_XM; ROWINDEX numRows = std::min(Patterns[pat].GetNumRows() - row - 1, maxCommands); while(numRows > 0) { m += Patterns[pat].GetNumChannels(); if(m->command != CMD_XPARAM) { break; } if(xmTempoFix && val < 256) { // With XM, 0x20 is the lowest tempo. Anything below changes ticks per row. val -= 0x20; } val = (val << 8) | m->param; numRows--; if(isExtended != nullptr) *isExtended = true; } return val; } ROWINDEX CSoundFile::PatternBreak(PlayState &state, CHANNELINDEX chn, uint8 param) const { if(param >= 64 && (GetType() & MOD_TYPE_S3M)) { // ST3 ignores invalid pattern breaks. return ROWINDEX_INVALID; } state.m_nNextPatStartRow = 0; // FT2 E60 bug return static_cast<ROWINDEX>(CalculateXParam(state.m_nPattern, state.m_nRow, chn)); } void CSoundFile::PortamentoUp(CHANNELINDEX nChn, ModCommand::PARAM param, const bool doFinePortamentoAsRegular) { ModChannel *pChn = &m_PlayState.Chn[nChn]; if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } else { param = pChn->nOldPortaUp; } const bool doFineSlides = !doFinePortamentoAsRegular && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_AMF0 | MOD_TYPE_DIGI | MOD_TYPE_STP | MOD_TYPE_DTM)); // Process MIDI pitch bend for instrument plugins MidiPortamento(nChn, param, doFineSlides); if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning) { // Portamento for instruments with custom tuning if(param >= 0xF0 && !doFinePortamentoAsRegular) PortamentoFineMPT(pChn, param - 0xF0); else if(param >= 0xE0 && !doFinePortamentoAsRegular) PortamentoExtraFineMPT(pChn, param - 0xE0); else PortamentoMPT(pChn, param); return; } else if(GetType() == MOD_TYPE_PLM) { // A normal portamento up or down makes a follow-up tone portamento go the same direction. pChn->nPortamentoDest = 1; } if (doFineSlides && param >= 0xE0) { if (param & 0x0F) { if ((param & 0xF0) == 0xF0) { FinePortamentoUp(pChn, param & 0x0F); return; } else if ((param & 0xF0) == 0xE0 && GetType() != MOD_TYPE_DBM) { ExtraFinePortamentoUp(pChn, param & 0x0F); return; } } if(GetType() != MOD_TYPE_DBM) { // DBM only has fine slides, no extra-fine slides. return; } } // Regular Slide if(!pChn->isFirstTick || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]) || GetType() == MOD_TYPE_669) { DoFreqSlide(pChn, -int(param) * 4); } } void CSoundFile::PortamentoDown(CHANNELINDEX nChn, ModCommand::PARAM param, const bool doFinePortamentoAsRegular) { ModChannel *pChn = &m_PlayState.Chn[nChn]; if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } else { param = pChn->nOldPortaDown; } const bool doFineSlides = !doFinePortamentoAsRegular && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_AMF0 | MOD_TYPE_DIGI | MOD_TYPE_STP | MOD_TYPE_DTM)); // Process MIDI pitch bend for instrument plugins MidiPortamento(nChn, -static_cast<int>(param), doFineSlides); if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning) { // Portamento for instruments with custom tuning if(param >= 0xF0 && !doFinePortamentoAsRegular) PortamentoFineMPT(pChn, -static_cast<int>(param - 0xF0)); else if(param >= 0xE0 && !doFinePortamentoAsRegular) PortamentoExtraFineMPT(pChn, -static_cast<int>(param - 0xE0)); else PortamentoMPT(pChn, -static_cast<int>(param)); return; } else if(GetType() == MOD_TYPE_PLM) { // A normal portamento up or down makes a follow-up tone portamento go the same direction. pChn->nPortamentoDest = 65535; } if(doFineSlides && param >= 0xE0) { if (param & 0x0F) { if ((param & 0xF0) == 0xF0) { FinePortamentoDown(pChn, param & 0x0F); return; } else if ((param & 0xF0) == 0xE0 && GetType() != MOD_TYPE_DBM) { ExtraFinePortamentoDown(pChn, param & 0x0F); return; } } if(GetType() != MOD_TYPE_DBM) { // DBM only has fine slides, no extra-fine slides. return; } } if(!pChn->isFirstTick || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]) || GetType() == MOD_TYPE_669) { DoFreqSlide(pChn, int(param) * 4); } } // Send portamento commands to plugins void CSoundFile::MidiPortamento(CHANNELINDEX nChn, int param, bool doFineSlides) { int actualParam = mpt::abs(param); int pitchBend = 0; // Old MIDI Pitch Bends: // - Applied on every tick // - No fine pitch slides (they are interpreted as normal slides) // New MIDI Pitch Bends: // - Behaviour identical to sample pitch bends if the instrument's PWD parameter corresponds to the actual VSTi setting. if(doFineSlides && actualParam >= 0xE0 && !m_playBehaviour[kOldMIDIPitchBends]) { if(m_PlayState.Chn[nChn].isFirstTick) { // Extra fine slide... pitchBend = (actualParam & 0x0F) * sgn(param); if(actualParam >= 0xF0) { // ... or just a fine slide! pitchBend *= 4; } } } else if(!m_PlayState.Chn[nChn].isFirstTick || m_playBehaviour[kOldMIDIPitchBends]) { // Regular slide pitchBend = param * 4; } if(pitchBend) { #ifndef NO_PLUGINS IMixPlugin *plugin = GetChannelInstrumentPlugin(nChn); if(plugin != nullptr) { int8 pwd = 13; // Early OpenMPT legacy... Actually it's not *exactly* 13, but close enough... if(m_PlayState.Chn[nChn].pModInstrument != nullptr) { pwd = m_PlayState.Chn[nChn].pModInstrument->midiPWD; } plugin->MidiPitchBend(GetBestMidiChannel(nChn), pitchBend, pwd); } #endif // NO_PLUGINS } } void CSoundFile::FinePortamentoUp(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldFinePortaUpDown = (pChn->nOldFinePortaUpDown & 0x0F) | (param << 4); else param = (pChn->nOldFinePortaUpDown >> 4); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { const auto oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideUpTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) { if(m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod < Util::MaxValueOfType(pChn->nPeriod)) pChn->nPeriod++; else if(!m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod > 1) pChn->nPeriod--; } } else { pChn->nPeriod -= (int)(param * 4); if (pChn->nPeriod < 1) { pChn->nPeriod = 1; if(GetType() == MOD_TYPE_S3M) { pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } } } } void CSoundFile::FinePortamentoDown(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldFinePortaUpDown = (pChn->nOldFinePortaUpDown & 0xF0) | (param & 0x0F); else param = (pChn->nOldFinePortaUpDown & 0x0F); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if (m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { const auto oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideDownTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) { if(!m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod < Util::MaxValueOfType(pChn->nPeriod)) pChn->nPeriod++; else if(m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod > 1) pChn->nPeriod--; } } else { pChn->nPeriod += (int)(param * 4); if (pChn->nPeriod > 0xFFFF) pChn->nPeriod = 0xFFFF; } } } } void CSoundFile::ExtraFinePortamentoUp(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldExtraFinePortaUpDown = (pChn->nOldExtraFinePortaUpDown & 0x0F) | (param << 4); else param = (pChn->nOldExtraFinePortaUpDown >> 4); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { int oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetFineLinearSlideUpTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) pChn->nPeriod++; } else { pChn->nPeriod -= (int)(param); if (pChn->nPeriod < 1) { pChn->nPeriod = 1; if(GetType() == MOD_TYPE_S3M) { pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } } } } void CSoundFile::ExtraFinePortamentoDown(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldExtraFinePortaUpDown = (pChn->nOldExtraFinePortaUpDown & 0xF0) | (param & 0x0F); else param = (pChn->nOldExtraFinePortaUpDown & 0x0F); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { int oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetFineLinearSlideDownTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) pChn->nPeriod--; } else { pChn->nPeriod += (int)(param); if (pChn->nPeriod > 0xFFFF) pChn->nPeriod = 0xFFFF; } } } } // Implemented for IMF compatibility, can't actually save this in any formats // Slide up / down every x ticks by y semitones void CSoundFile::NoteSlide(ModChannel *pChn, uint32 param, bool slideUp, bool retrig) const { uint8 x, y; if(m_SongFlags[SONG_FIRSTTICK]) { x = param & 0xF0; if (x) pChn->nNoteSlideSpeed = (x >> 4); y = param & 0x0F; if (y) pChn->nNoteSlideStep = y; pChn->nNoteSlideCounter = pChn->nNoteSlideSpeed; } else { if (--pChn->nNoteSlideCounter == 0) { pChn->nNoteSlideCounter = pChn->nNoteSlideSpeed; // update it pChn->nPeriod = GetPeriodFromNote ((slideUp ? 1 : -1) * pChn->nNoteSlideStep + GetNoteFromPeriod(pChn->nPeriod), 8363, 0); if(retrig) { pChn->position.Set(0); } } } } // Portamento Slide void CSoundFile::TonePortamento(ModChannel *pChn, uint32 param) const { pChn->dwFlags.set(CHN_PORTAMENTO); //IT compatibility 03: Share effect memory with portamento up/down if((!m_SongFlags[SONG_ITCOMPATGXX] && m_playBehaviour[kITPortaMemoryShare]) || GetType() == MOD_TYPE_PLM) { if(param == 0) param = pChn->nOldPortaUp; pChn->nOldPortaUp = pChn->nOldPortaDown = static_cast<uint8>(param); } if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning) { //Behavior: Param tells number of finesteps(or 'fullsteps'(notes) with glissando) //to slide per row(not per tick). const int32 old_PortamentoTickSlide = (m_PlayState.m_nTickCount != 0) ? pChn->m_PortamentoTickSlide : 0; if(param) pChn->nPortamentoSlide = param; else if(pChn->nPortamentoSlide == 0) return; if((pChn->nPortamentoDest > 0 && pChn->nPortamentoSlide < 0) || (pChn->nPortamentoDest < 0 && pChn->nPortamentoSlide > 0)) pChn->nPortamentoSlide = -pChn->nPortamentoSlide; pChn->m_PortamentoTickSlide = static_cast<int32>((m_PlayState.m_nTickCount + 1.0) * pChn->nPortamentoSlide / m_PlayState.m_nMusicSpeed); if(pChn->dwFlags[CHN_GLISSANDO]) { pChn->m_PortamentoTickSlide *= pChn->pModInstrument->pTuning->GetFineStepCount() + 1; //With glissando interpreting param as notes instead of finesteps. } const int32 slide = pChn->m_PortamentoTickSlide - old_PortamentoTickSlide; if(mpt::abs(pChn->nPortamentoDest) <= mpt::abs(slide)) { if(pChn->nPortamentoDest != 0) { pChn->m_PortamentoFineSteps += pChn->nPortamentoDest; pChn->nPortamentoDest = 0; pChn->m_CalculateFreq = true; } } else { pChn->m_PortamentoFineSteps += slide; pChn->nPortamentoDest -= slide; pChn->m_CalculateFreq = true; } return; } //End candidate MPT behavior. bool doPorta = !pChn->isFirstTick || (GetType() & (MOD_TYPE_DBM | MOD_TYPE_669)) || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]); if(GetType() == MOD_TYPE_PLM && param >= 0xF0) { param -= 0xF0; doPorta = pChn->isFirstTick; } if(param) { if(GetType() == MOD_TYPE_669) { param *= 10; } pChn->nPortamentoSlide = param * 4; } if(pChn->nPeriod && pChn->nPortamentoDest && doPorta) { if (pChn->nPeriod < pChn->nPortamentoDest) { int32 delta = pChn->nPortamentoSlide; if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { uint32 n = pChn->nPortamentoSlide / 4; if (n > 255) n = 255; // Return (a*b+c/2)/c - no divide error // Table is 65536*2(n/192) delta = Util::muldivr(pChn->nPeriod, LinearSlideUpTable[n], 65536) - pChn->nPeriod; if (delta < 1) delta = 1; } pChn->nPeriod += delta; if (pChn->nPeriod > pChn->nPortamentoDest) pChn->nPeriod = pChn->nPortamentoDest; } else if (pChn->nPeriod > pChn->nPortamentoDest) { int32 delta = -pChn->nPortamentoSlide; if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { uint32 n = pChn->nPortamentoSlide / 4; if (n > 255) n = 255; delta = Util::muldivr(pChn->nPeriod, LinearSlideDownTable[n], 65536) - pChn->nPeriod; if (delta > -1) delta = -1; } pChn->nPeriod += delta; if (pChn->nPeriod < pChn->nPortamentoDest) pChn->nPeriod = pChn->nPortamentoDest; } } // IT compatibility 23. Portamento with no note // ProTracker also disables portamento once the target is reached. // Test case: PortaTarget.mod if(pChn->nPeriod == pChn->nPortamentoDest && (m_playBehaviour[kITPortaTargetReached] || GetType() == MOD_TYPE_MOD)) pChn->nPortamentoDest = 0; } void CSoundFile::Vibrato(ModChannel *p, uint32 param) const { if (param & 0x0F) p->nVibratoDepth = (param & 0x0F) * 4; if (param & 0xF0) p->nVibratoSpeed = (param >> 4) & 0x0F; p->dwFlags.set(CHN_VIBRATO); } void CSoundFile::FineVibrato(ModChannel *p, uint32 param) const { if (param & 0x0F) p->nVibratoDepth = param & 0x0F; if (param & 0xF0) p->nVibratoSpeed = (param >> 4) & 0x0F; p->dwFlags.set(CHN_VIBRATO); // ST3 compatibility: Do not distinguish between vibrato types in effect memory // Test case: VibratoTypeChange.s3m if(m_playBehaviour[kST3VibratoMemory] && (param & 0x0F)) { p->nVibratoDepth *= 4u; } } void CSoundFile::Panbrello(ModChannel *p, uint32 param) const { if (param & 0x0F) p->nPanbrelloDepth = param & 0x0F; if (param & 0xF0) p->nPanbrelloSpeed = (param >> 4) & 0x0F; } void CSoundFile::Panning(ModChannel *pChn, uint32 param, PanningType panBits) const { // No panning in ProTracker mode if(m_playBehaviour[kMODIgnorePanning]) { return; } // IT Compatibility (and other trackers as well): panning disables surround (unless panning in rear channels is enabled, which is not supported by the original trackers anyway) if (!m_SongFlags[SONG_SURROUNDPAN] && (panBits == Pan8bit || m_playBehaviour[kPanOverride])) { pChn->dwFlags.reset(CHN_SURROUND); } if(panBits == Pan4bit) { // 0...15 panning pChn->nPan = (param * 256 + 8) / 15; } else if(panBits == Pan6bit) { // 0...64 panning if(param > 64) param = 64; pChn->nPan = param * 4; } else { if(!(GetType() & (MOD_TYPE_S3M | MOD_TYPE_DSM | MOD_TYPE_AMF | MOD_TYPE_MTM))) { // Real 8-bit panning pChn->nPan = param; } else { // 7-bit panning + surround if(param <= 0x80) { pChn->nPan = param << 1; } else if(param == 0xA4) { pChn->dwFlags.set(CHN_SURROUND); pChn->nPan = 0x80; } } } pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->nRestorePanOnNewNote = 0; //IT compatibility 20. Set pan overrides random pan if(m_playBehaviour[kPanOverride]) { pChn->nPanSwing = 0; pChn->nPanbrelloOffset = 0; } } void CSoundFile::VolumeSlide(ModChannel *pChn, ModCommand::PARAM param) { if (param) pChn->nOldVolumeSlide = param; else param = pChn->nOldVolumeSlide; if((GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_DIGI | MOD_TYPE_STP | MOD_TYPE_DTM))) { // MOD / XM nibble priority if((param & 0xF0) != 0) { param &= 0xF0; } else { param &= 0x0F; } } int newvolume = pChn->nVolume; if(!(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_AMF0 | MOD_TYPE_MED | MOD_TYPE_DIGI))) { if ((param & 0x0F) == 0x0F) //Fine upslide or slide -15 { if (param & 0xF0) //Fine upslide { FineVolumeUp(pChn, (param >> 4), false); return; } else //Slide -15 { if(pChn->isFirstTick && !m_SongFlags[SONG_FASTVOLSLIDES]) { newvolume -= 0x0F * 4; } } } else if ((param & 0xF0) == 0xF0) //Fine downslide or slide +15 { if (param & 0x0F) //Fine downslide { FineVolumeDown(pChn, (param & 0x0F), false); return; } else //Slide +15 { if(pChn->isFirstTick && !m_SongFlags[SONG_FASTVOLSLIDES]) { newvolume += 0x0F * 4; } } } } if(!pChn->isFirstTick || m_SongFlags[SONG_FASTVOLSLIDES] || (m_PlayState.m_nMusicSpeed == 1 && GetType() == MOD_TYPE_DBM)) { // IT compatibility: Ignore slide commands with both nibbles set. if (param & 0x0F) { if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (param & 0xF0) == 0) newvolume -= (int)((param & 0x0F) * 4); } else { newvolume += (int)((param & 0xF0) >> 2); } if (GetType() == MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP); } newvolume = Clamp(newvolume, 0, 256); pChn->nVolume = newvolume; } void CSoundFile::PanningSlide(ModChannel *pChn, ModCommand::PARAM param, bool memory) { if(memory) { // FT2 compatibility: Use effect memory (lxx and rxx in XM shouldn't use effect memory). // Test case: PanSlideMem.xm if(param) pChn->nOldPanSlide = param; else param = pChn->nOldPanSlide; } if((GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { // XM nibble priority if((param & 0xF0) != 0) { param &= 0xF0; } else { param &= 0x0F; } } int32 nPanSlide = 0; if(!(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { if(m_SongFlags[SONG_FIRSTTICK]) { param = (param & 0xF0) / 4u; nPanSlide = - (int)param; } } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { if(m_SongFlags[SONG_FIRSTTICK]) { nPanSlide = (param & 0x0F) * 4u; } } else if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0x0F) { // IT compatibility: Ignore slide commands with both nibbles set. if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (param & 0xF0) == 0) nPanSlide = (int)((param & 0x0F) * 4u); } else { nPanSlide = -(int)((param & 0xF0) / 4u); } } } else { if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0xF0) { nPanSlide = (int)((param & 0xF0) / 4u); } else { nPanSlide = -(int)((param & 0x0F) * 4u); } // FT2 compatibility: FT2's panning slide is like IT's fine panning slide (not as deep) if(m_playBehaviour[kFT2PanSlide]) nPanSlide /= 4; } } if (nPanSlide) { nPanSlide += pChn->nPan; nPanSlide = Clamp(nPanSlide, 0, 256); pChn->nPan = nPanSlide; pChn->nRestorePanOnNewNote = 0; } } void CSoundFile::FineVolumeUp(ModChannel *pChn, ModCommand::PARAM param, bool volCol) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: EAx / EBx memory is not linked // Test case: FineVol-LinkMem.xm if(param) pChn->nOldFineVolUpDown = (param << 4) | (pChn->nOldFineVolUpDown & 0x0F); else param = (pChn->nOldFineVolUpDown >> 4); } else if(volCol) { if(param) pChn->nOldVolParam = param; else param = pChn->nOldVolParam; } else { if(param) pChn->nOldFineVolUpDown = param; else param = pChn->nOldFineVolUpDown; } if(pChn->isFirstTick) { pChn->nVolume += param * 4; if(pChn->nVolume > 256) pChn->nVolume = 256; if(GetType() & MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP); } } void CSoundFile::FineVolumeDown(ModChannel *pChn, ModCommand::PARAM param, bool volCol) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: EAx / EBx memory is not linked // Test case: FineVol-LinkMem.xm if(param) pChn->nOldFineVolUpDown = param | (pChn->nOldFineVolUpDown & 0xF0); else param = (pChn->nOldFineVolUpDown & 0x0F); } else if(volCol) { if(param) pChn->nOldVolParam = param; else param = pChn->nOldVolParam; } else { if(param) pChn->nOldFineVolUpDown = param; else param = pChn->nOldFineVolUpDown; } if(pChn->isFirstTick) { pChn->nVolume -= param * 4; if(pChn->nVolume < 0) pChn->nVolume = 0; if(GetType() & MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP); } } void CSoundFile::Tremolo(ModChannel *pChn, uint32 param) const { if (param & 0x0F) pChn->nTremoloDepth = (param & 0x0F) << 2; if (param & 0xF0) pChn->nTremoloSpeed = (param >> 4) & 0x0F; pChn->dwFlags.set(CHN_TREMOLO); } void CSoundFile::ChannelVolSlide(ModChannel *pChn, ModCommand::PARAM param) const { int32 nChnSlide = 0; if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { if(m_SongFlags[SONG_FIRSTTICK]) nChnSlide = param >> 4; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { if(m_SongFlags[SONG_FIRSTTICK]) nChnSlide = - (int)(param & 0x0F); } else { if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0x0F) { if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_J2B | MOD_TYPE_DBM)) || (param & 0xF0) == 0) nChnSlide = -(int)(param & 0x0F); } else { nChnSlide = (int)((param & 0xF0) >> 4); } } } if (nChnSlide) { nChnSlide += pChn->nGlobalVol; nChnSlide = Clamp(nChnSlide, 0, 64); pChn->nGlobalVol = nChnSlide; } } void CSoundFile::ExtendedMODCommands(CHANNELINDEX nChn, ModCommand::PARAM param) { ModChannel *pChn = &m_PlayState.Chn[nChn]; uint8 command = param & 0xF0; param &= 0x0F; switch(command) { // E0x: Set Filter case 0x00: for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { m_PlayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } break; // E1x: Fine Portamento Up case 0x10: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoUp(pChn, param); break; // E2x: Fine Portamento Down case 0x20: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoDown(pChn, param); break; // E3x: Set Glissando Control case 0x30: pChn->dwFlags.set(CHN_GLISSANDO, param != 0); break; // E4x: Set Vibrato WaveForm case 0x40: pChn->nVibratoType = param & 0x07; break; // E5x: Set FineTune case 0x50: if(!m_SongFlags[SONG_FIRSTTICK]) { break; } if(GetType() & (MOD_TYPE_MOD | MOD_TYPE_DIGI | MOD_TYPE_AMF0 | MOD_TYPE_MED)) { pChn->nFineTune = MOD2XMFineTune(param); if(pChn->nPeriod && pChn->rowCommand.IsNote()) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed); } else if(pChn->rowCommand.IsNote()) { pChn->nFineTune = MOD2XMFineTune(param - 8); if(pChn->nPeriod) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed); } break; // E6x: Pattern Loop // E7x: Set Tremolo WaveForm case 0x70: pChn->nTremoloType = param & 0x07; break; // E8x: Set 4-bit Panning case 0x80: if(m_SongFlags[SONG_FIRSTTICK]) { Panning(pChn, param, Pan4bit); } break; // E9x: Retrig case 0x90: RetrigNote(nChn, param); break; // EAx: Fine Volume Up case 0xA0: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeUp(pChn, param, false); break; // EBx: Fine Volume Down case 0xB0: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeDown(pChn, param, false); break; // ECx: Note Cut case 0xC0: NoteCut(nChn, param, false); break; // EDx: Note Delay // EEx: Pattern Delay case 0xF0: if(GetType() == MOD_TYPE_MOD) // MOD: Invert Loop { pChn->nEFxSpeed = param; if(m_SongFlags[SONG_FIRSTTICK]) InvertLoop(pChn); } else // XM: Set Active Midi Macro { pChn->nActiveMacro = param; } break; } } void CSoundFile::ExtendedS3MCommands(CHANNELINDEX nChn, ModCommand::PARAM param) { ModChannel *pChn = &m_PlayState.Chn[nChn]; uint8 command = param & 0xF0; param &= 0x0F; switch(command) { // S0x: Set Filter // S1x: Set Glissando Control case 0x10: pChn->dwFlags.set(CHN_GLISSANDO, param != 0); break; // S2x: Set FineTune case 0x20: if(!m_SongFlags[SONG_FIRSTTICK]) break; if(GetType() != MOD_TYPE_669) { pChn->nC5Speed = S3MFineTuneTable[param]; pChn->nFineTune = MOD2XMFineTune(param); if (pChn->nPeriod) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed); } else if(pChn->pModSample != nullptr) { pChn->nC5Speed = pChn->pModSample->nC5Speed + param * 80; } break; // S3x: Set Vibrato Waveform case 0x30: if(GetType() == MOD_TYPE_S3M) { pChn->nVibratoType = param & 0x03; } else { // IT compatibility: Ignore waveform types > 3 if(m_playBehaviour[kITVibratoTremoloPanbrello]) pChn->nVibratoType = (param < 0x04) ? param : 0; else pChn->nVibratoType = param & 0x07; } break; // S4x: Set Tremolo Waveform case 0x40: if(GetType() == MOD_TYPE_S3M) { pChn->nTremoloType = param & 0x03; } else { // IT compatibility: Ignore waveform types > 3 if(m_playBehaviour[kITVibratoTremoloPanbrello]) pChn->nTremoloType = (param < 0x04) ? param : 0; else pChn->nTremoloType = param & 0x07; } break; // S5x: Set Panbrello Waveform case 0x50: // IT compatibility: Ignore waveform types > 3 if(m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nPanbrelloType = (param < 0x04) ? param : 0; pChn->nPanbrelloPos = 0; } else { pChn->nPanbrelloType = param & 0x07; } break; // S6x: Pattern Delay for x frames case 0x60: if(m_SongFlags[SONG_FIRSTTICK] && m_PlayState.m_nTickCount == 0) { // Tick delays are added up. // Scream Tracker 3 does actually not support this command. // We'll use the same behaviour as for Impulse Tracker, as we can assume that // most S3Ms that make use of this command were made with Impulse Tracker. // MPT added this command to the XM format through the X6x effect, so we will use // the same behaviour here as well. // Test cases: PatternDelays.it, PatternDelays.s3m, PatternDelays.xm m_PlayState.m_nFrameDelay += param; } break; // S7x: Envelope Control / Instrument Control case 0x70: if(!m_SongFlags[SONG_FIRSTTICK]) break; switch(param) { case 0: case 1: case 2: { ModChannel *bkp = &m_PlayState.Chn[m_nChannels]; for (CHANNELINDEX i=m_nChannels; i<MAX_CHANNELS; i++, bkp++) { if (bkp->nMasterChn == nChn+1) { if (param == 1) { KeyOff(bkp); } else if (param == 2) { bkp->dwFlags.set(CHN_NOTEFADE); } else { bkp->dwFlags.set(CHN_NOTEFADE); bkp->nFadeOutVol = 0; } #ifndef NO_PLUGINS const ModInstrument *pIns = bkp->pModInstrument; IMixPlugin *pPlugin; if(pIns != nullptr && pIns->nMixPlug && (pPlugin = m_MixPlugins[pIns->nMixPlug - 1].pMixPlugin) != nullptr) { pPlugin->MidiCommand(GetBestMidiChannel(nChn), pIns->nMidiProgram, pIns->wMidiBank, bkp->nNote + NOTE_MAX_SPECIAL, 0, nChn); } #endif // NO_PLUGINS } } } break; case 3: pChn->nNNA = NNA_NOTECUT; break; case 4: pChn->nNNA = NNA_CONTINUE; break; case 5: pChn->nNNA = NNA_NOTEOFF; break; case 6: pChn->nNNA = NNA_NOTEFADE; break; case 7: pChn->VolEnv.flags.reset(ENV_ENABLED); break; case 8: pChn->VolEnv.flags.set(ENV_ENABLED); break; case 9: pChn->PanEnv.flags.reset(ENV_ENABLED); break; case 10: pChn->PanEnv.flags.set(ENV_ENABLED); break; case 11: pChn->PitchEnv.flags.reset(ENV_ENABLED); break; case 12: pChn->PitchEnv.flags.set(ENV_ENABLED); break; case 13: // S7D: Enable pitch envelope, force to play as pitch envelope case 14: // S7E: Enable pitch envelope, force to play as filter envelope if(GetType() == MOD_TYPE_MPT) { pChn->PitchEnv.flags.set(ENV_ENABLED); pChn->PitchEnv.flags.set(ENV_FILTER, param != 13); } break; } break; // S8x: Set 4-bit Panning case 0x80: if(m_SongFlags[SONG_FIRSTTICK]) { Panning(pChn, param, Pan4bit); } break; // S9x: Sound Control case 0x90: ExtendedChannelEffect(pChn, param); break; // SAx: Set 64k Offset case 0xA0: if(m_SongFlags[SONG_FIRSTTICK]) { pChn->nOldHiOffset = static_cast<uint8>(param); if (!m_playBehaviour[kITHighOffsetNoRetrig] && pChn->rowCommand.IsNote()) { SmpLength pos = param << 16; if (pos < pChn->nLength) pChn->position.SetInt(pos); } } break; // SBx: Pattern Loop // SCx: Note Cut case 0xC0: if(param == 0) { //IT compatibility 22. SC0 == SC1 if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) param = 1; // ST3 doesn't cut notes with SC0 else if(GetType() == MOD_TYPE_S3M) return; } // S3M/IT compatibility: Note Cut really cuts notes and does not just mute them (so that following volume commands could restore the sample) // Test case: scx.it NoteCut(nChn, param, m_playBehaviour[kITSCxStopsSample] || GetType() == MOD_TYPE_S3M); break; // SDx: Note Delay // SEx: Pattern Delay for x rows // SFx: S3M: Not used, IT: Set Active Midi Macro case 0xF0: if(GetType() != MOD_TYPE_S3M) { pChn->nActiveMacro = static_cast<uint8>(param); } break; } } void CSoundFile::ExtendedChannelEffect(ModChannel *pChn, uint32 param) { // S9x and X9x commands (S3M/XM/IT only) if(!m_SongFlags[SONG_FIRSTTICK]) return; switch(param & 0x0F) { // S90: Surround Off case 0x00: pChn->dwFlags.reset(CHN_SURROUND); break; // S91: Surround On case 0x01: pChn->dwFlags.set(CHN_SURROUND); pChn->nPan = 128; break; //////////////////////////////////////////////////////////// // ModPlug Extensions // S98: Reverb Off case 0x08: pChn->dwFlags.reset(CHN_REVERB); pChn->dwFlags.set(CHN_NOREVERB); break; // S99: Reverb On case 0x09: pChn->dwFlags.reset(CHN_NOREVERB); pChn->dwFlags.set(CHN_REVERB); break; // S9A: 2-Channels surround mode case 0x0A: m_SongFlags.reset(SONG_SURROUNDPAN); break; // S9B: 4-Channels surround mode case 0x0B: m_SongFlags.set(SONG_SURROUNDPAN); break; // S9C: IT Filter Mode case 0x0C: m_SongFlags.reset(SONG_MPTFILTERMODE); break; // S9D: MPT Filter Mode case 0x0D: m_SongFlags.set(SONG_MPTFILTERMODE); break; // S9E: Go forward case 0x0E: pChn->dwFlags.reset(CHN_PINGPONGFLAG); break; // S9F: Go backward (and set playback position to the end if sample just started) case 0x0F: if(pChn->position.IsZero() && pChn->nLength && (pChn->rowCommand.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } pChn->dwFlags.set(CHN_PINGPONGFLAG); break; } } void CSoundFile::InvertLoop(ModChannel *pChn) { // EFx implementation for MOD files (PT 1.1A and up: Invert Loop) // This effect trashes samples. Thanks to 8bitbubsy for making this work. :) if(GetType() != MOD_TYPE_MOD || pChn->nEFxSpeed == 0) return; // we obviously also need a sample for this ModSample *pModSample = const_cast<ModSample *>(pChn->pModSample); if(pModSample == nullptr || !pModSample->HasSampleData() || !pModSample->uFlags[CHN_LOOP] || pModSample->uFlags[CHN_16BIT]) return; pChn->nEFxDelay += ModEFxTable[pChn->nEFxSpeed & 0x0F]; if((pChn->nEFxDelay & 0x80) == 0) return; // only applied if the "delay" reaches 128 pChn->nEFxDelay = 0; if (++pChn->nEFxOffset >= pModSample->nLoopEnd - pModSample->nLoopStart) pChn->nEFxOffset = 0; // TRASH IT!!! (Yes, the sample!) uint8 &sample = mpt::byte_cast<uint8 *>(pModSample->sampleb())[pModSample->nLoopStart + pChn->nEFxOffset]; sample = ~sample; ctrlSmp::PrecomputeLoops(*pModSample, *this, false); } // Process a MIDI Macro. // Parameters: // [in] nChn: Mod channel to apply macro on // [in] isSmooth: If true, internal macros are interpolated between two rows // [in] macro: Actual MIDI Macro string // [in] param: Parameter for parametric macros (Z00 - Z7F) // [in] plugin: Plugin to send MIDI message to (if not specified but needed, it is autodetected) void CSoundFile::ProcessMIDIMacro(CHANNELINDEX nChn, bool isSmooth, const char *macro, uint8 param, PLUGINDEX plugin) { ModChannel &chn = m_PlayState.Chn[nChn]; const ModInstrument *pIns = GetNumInstruments() ? chn.pModInstrument : nullptr; uint8 out[MACRO_LENGTH]; uint32 outPos = 0; // output buffer position, which also equals the number of complete bytes const uint8 lastZxxParam = chn.lastZxxParam; bool firstNibble = true; for(uint32 pos = 0; pos < (MACRO_LENGTH - 1) && macro[pos]; pos++) { bool isNibble = false; // did we parse a nibble or a byte value? uint8 data = 0; // data that has just been parsed // Parse next macro byte... See Impulse Tracker's MIDI.TXT for detailed information on each possible character. if(macro[pos] >= '0' && macro[pos] <= '9') { isNibble = true; data = static_cast<uint8>(macro[pos] - '0'); } else if(macro[pos] >= 'A' && macro[pos] <= 'F') { isNibble = true; data = static_cast<uint8>(macro[pos] - 'A' + 0x0A); } else if(macro[pos] == 'c') { // MIDI channel isNibble = true; data = GetBestMidiChannel(nChn); } else if(macro[pos] == 'n') { // Last triggered note if(ModCommand::IsNote(chn.nLastNote)) { data = chn.nLastNote - NOTE_MIN; } } else if(macro[pos] == 'v') { // Velocity // This is "almost" how IT does it - apparently, IT seems to lag one row behind on global volume or channel volume changes. const int swing = (m_playBehaviour[kITSwingBehaviour] || m_playBehaviour[kMPTOldSwingBehaviour]) ? chn.nVolSwing : 0; const int vol = Util::muldiv((chn.nVolume + swing) * m_PlayState.m_nGlobalVolume, chn.nGlobalVol * chn.nInsVol, 1 << 20); data = static_cast<uint8>(Clamp(vol / 2, 1, 127)); //data = (unsigned char)MIN((chn.nVolume * chn.nGlobalVol * m_nGlobalVolume) >> (1 + 6 + 8), 127); } else if(macro[pos] == 'u') { // Calculated volume // Same note as with velocity applies here, but apparently also for instrument / sample volumes? const int vol = Util::muldiv(chn.nCalcVolume * m_PlayState.m_nGlobalVolume, chn.nGlobalVol * chn.nInsVol, 1 << 26); data = static_cast<uint8>(Clamp(vol / 2, 1, 127)); //data = (unsigned char)MIN((chn.nCalcVolume * chn.nGlobalVol * m_nGlobalVolume) >> (7 + 6 + 8), 127); } else if(macro[pos] == 'x') { // Pan set data = static_cast<uint8>(std::min(chn.nPan / 2, 127)); } else if(macro[pos] == 'y') { // Calculated pan data = static_cast<uint8>(std::min(chn.nRealPan / 2, 127)); } else if(macro[pos] == 'a') { // High byte of bank select if(pIns && pIns->wMidiBank) { data = static_cast<uint8>(((pIns->wMidiBank - 1) >> 7) & 0x7F); } } else if(macro[pos] == 'b') { // Low byte of bank select if(pIns && pIns->wMidiBank) { data = static_cast<uint8>((pIns->wMidiBank - 1) & 0x7F); } } else if(macro[pos] == 'o') { // Offset (ignoring high offset) data = static_cast<uint8>((chn.oldOffset >> 8) & 0xFF); } else if(macro[pos] == 'h') { // Host channel number data = static_cast<uint8>((nChn >= GetNumChannels() ? (chn.nMasterChn - 1) : nChn) & 0x7F); } else if(macro[pos] == 'm') { // Loop direction (judging from the character, it was supposed to be loop type, though) data = chn.dwFlags[CHN_PINGPONGFLAG] ? 1 : 0; } else if(macro[pos] == 'p') { // Program select if(pIns && pIns->nMidiProgram) { data = static_cast<uint8>((pIns->nMidiProgram - 1) & 0x7F); } } else if(macro[pos] == 'z') { // Zxx parameter data = param & 0x7F; if(isSmooth && chn.lastZxxParam < 0x80 && (outPos < 3 || out[outPos - 3] != 0xF0 || out[outPos - 2] < 0xF0)) { // Interpolation for external MIDI messages - interpolation for internal messages // is handled separately to allow for more than 7-bit granularity where it's possible data = static_cast<uint8>(CalculateSmoothParamChange((float)lastZxxParam, (float)data)); } chn.lastZxxParam = data; } else if(macro[pos] == 's') { // SysEx Checksum (not an original Impulse Tracker macro variable, but added for convenience) uint32 startPos = outPos; while(startPos > 0 && out[--startPos] != 0xF0); if(outPos - startPos < 5 || out[startPos] != 0xF0) { continue; } for(uint32 p = startPos + 5; p != outPos; p++) { data += out[p]; } data = (~data + 1) & 0x7F; } else { // Unrecognized byte (e.g. space char) continue; } // Append parsed data if(isNibble) // parsed a nibble (constant or 'c' variable) { if(firstNibble) { out[outPos] = data; } else { out[outPos] = (out[outPos] << 4) | data; outPos++; } firstNibble = !firstNibble; } else // parsed a byte (variable) { if(!firstNibble) // From MIDI.TXT: '9n' is exactly the same as '09 n' or '9 n' -- so finish current byte first { outPos++; } out[outPos++] = data; firstNibble = true; } } if(!firstNibble) { // Finish current byte outPos++; } // Macro string has been parsed and translated, now send the message(s)... uint32 sendPos = 0; uint8 runningStatus = 0; while(sendPos < outPos) { uint32 sendLen = 0; if(out[sendPos] == 0xF0) { // SysEx start if((outPos - sendPos >= 4) && (out[sendPos + 1] == 0xF0 || out[sendPos + 1] == 0xF1)) { // Internal macro (normal (F0F0) or extended (F0F1)), 4 bytes long sendLen = 4; } else { // SysEx message, find end of message for(uint32 i = sendPos + 1; i < outPos; i++) { if(out[i] == 0xF7) { // Found end of SysEx message sendLen = i - sendPos + 1; break; } } if(sendLen == 0) { // Didn't find end, so "invent" end of SysEx message out[outPos++] = 0xF7; sendLen = outPos - sendPos; } } } else if(!(out[sendPos] & 0x80)) { // Missing status byte? Try inserting running status if(runningStatus != 0) { sendPos--; out[sendPos] = runningStatus; } else { // No running status to re-use; skip this byte sendPos++; } continue; } else { // Other MIDI messages sendLen = std::min<uint32>(MIDIEvents::GetEventLength(out[sendPos]), outPos - sendPos); } if(sendLen == 0) { break; } if(out[sendPos] < 0xF0) { runningStatus = out[sendPos]; } uint32 bytesSent = SendMIDIData(nChn, isSmooth, out + sendPos, sendLen, plugin); // If there's no error in the macro data (e.g. unrecognized internal MIDI macro), we have sendLen == bytesSent. if(bytesSent > 0) { sendPos += bytesSent; } else { sendPos += sendLen; } } } // Calculate smooth MIDI macro slide parameter for current tick. float CSoundFile::CalculateSmoothParamChange(float currentValue, float param) const { MPT_ASSERT(GetNumTicksOnCurrentRow() > m_PlayState.m_nTickCount); const uint32 ticksLeft = GetNumTicksOnCurrentRow() - m_PlayState.m_nTickCount; if(ticksLeft > 1) { // Slide param const float step = (param - currentValue) / (float)ticksLeft; return (currentValue + step); } else { // On last tick, set exact value. return param; } } // Process exactly one MIDI message parsed by ProcessMIDIMacro. Returns bytes sent on success, 0 on (parse) failure. uint32 CSoundFile::SendMIDIData(CHANNELINDEX nChn, bool isSmooth, const unsigned char *macro, uint32 macroLen, PLUGINDEX plugin) { if(macroLen < 1) { return 0; } if(macro[0] == 0xFA || macro[0] == 0xFC || macro[0] == 0xFF) { // Start Song, Stop Song, MIDI Reset - both interpreted internally and sent to plugins for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { m_PlayState.Chn[chn].nCutOff = 0x7F; m_PlayState.Chn[chn].nResonance = 0x00; } } ModChannel &chn = m_PlayState.Chn[nChn]; if(macro[0] == 0xF0 && (macro[1] == 0xF0 || macro[1] == 0xF1)) { // Internal device. if(macroLen < 4) { return 0; } const bool isExtended = (macro[1] == 0xF1); const uint8 macroCode = macro[2]; const uint8 param = macro[3]; if(macroCode == 0x00 && !isExtended && param < 0x80) { // F0.F0.00.xx: Set CutOff if(!isSmooth) { chn.nCutOff = param; } else { chn.nCutOff = Util::Round<uint8>(CalculateSmoothParamChange(chn.nCutOff, param)); } chn.nRestoreCutoffOnNewNote = 0; SetupChannelFilter(&chn, !chn.dwFlags[CHN_FILTER]); return 4; } else if(macroCode == 0x01 && !isExtended && param < 0x80) { // F0.F0.01.xx: Set Resonance if(!isSmooth) { chn.nResonance = param; } else { chn.nResonance = (uint8)CalculateSmoothParamChange((float)chn.nResonance, (float)param); } chn.nRestoreResonanceOnNewNote = 0; SetupChannelFilter(&chn, !chn.dwFlags[CHN_FILTER]); return 4; } else if(macroCode == 0x02 && !isExtended) { // F0.F0.02.xx: Set filter mode (high nibble determines filter mode) if(param < 0x20) { chn.nFilterMode = (param >> 4); SetupChannelFilter(&chn, !chn.dwFlags[CHN_FILTER]); } return 4; #ifndef NO_PLUGINS } else if(macroCode == 0x03 && !isExtended) { // F0.F0.03.xx: Set plug dry/wet const PLUGINDEX nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted); if ((nPlug) && (nPlug <= MAX_MIXPLUGINS) && param < 0x80) { const float newRatio = (0x7F - (param & 0x7F)) / 127.0f; if(!isSmooth) { m_MixPlugins[nPlug - 1].fDryRatio = newRatio; } else { m_MixPlugins[nPlug - 1].fDryRatio = CalculateSmoothParamChange(m_MixPlugins[nPlug - 1].fDryRatio, newRatio); } } return 4; } else if((macroCode & 0x80) || isExtended) { // F0.F0.{80|n}.xx / F0.F1.n.xx: Set VST effect parameter n to xx const PLUGINDEX nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted); const uint32 plugParam = isExtended ? (0x80 + macroCode) : (macroCode & 0x7F); if((nPlug) && (nPlug <= MAX_MIXPLUGINS)) { IMixPlugin *pPlugin = m_MixPlugins[nPlug - 1].pMixPlugin; if(pPlugin && param < 0x80) { const float fParam = param / 127.0f; if(!isSmooth) { pPlugin->SetParameter(plugParam, fParam); } else { pPlugin->SetParameter(plugParam, CalculateSmoothParamChange(pPlugin->GetParameter(plugParam), fParam)); } } } return 4; #endif // NO_PLUGINS } // If we reach this point, the internal macro was invalid. } else { #ifndef NO_PLUGINS // Not an internal device. Pass on to appropriate plugin. const CHANNELINDEX plugChannel = (nChn < GetNumChannels()) ? nChn + 1 : chn.nMasterChn; if(plugChannel > 0 && plugChannel <= GetNumChannels()) // XXX do we need this? I guess it might be relevant for previewing notes in the pattern... Or when using this mechanism for volume/panning! { PLUGINDEX nPlug = 0; if(!chn.dwFlags[CHN_NOFX]) { nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted); } if(nPlug > 0 && nPlug <= MAX_MIXPLUGINS) { IMixPlugin *pPlugin = m_MixPlugins[nPlug - 1].pMixPlugin; if (pPlugin != nullptr) { if(macro[0] == 0xF0) { pPlugin->MidiSysexSend(macro, macroLen); } else { uint32 len = std::min<uint32>(MIDIEvents::GetEventLength(macro[0]), macroLen); uint32 curData = 0; memcpy(&curData, macro, len); pPlugin->MidiSend(curData); } } } } #else MPT_UNREFERENCED_PARAMETER(plugin); #endif // NO_PLUGINS return macroLen; } return 0; } void CSoundFile::SendMIDINote(CHANNELINDEX chn, uint16 note, uint16 volume) { #ifndef NO_PLUGINS auto &channel = m_PlayState.Chn[chn]; const ModInstrument *pIns = channel.pModInstrument; // instro sends to a midi chan if (pIns && pIns->HasValidMIDIChannel()) { PLUGINDEX nPlug = pIns->nMixPlug; if ((nPlug) && (nPlug <= MAX_MIXPLUGINS)) { IMixPlugin *pPlug = m_MixPlugins[nPlug-1].pMixPlugin; if (pPlug != nullptr) { pPlug->MidiCommand(GetBestMidiChannel(chn), pIns->nMidiProgram, pIns->wMidiBank, note, volume, chn); if(note < NOTE_MIN_SPECIAL) channel.nLeftVU = channel.nRightVU = 0xFF; } } } #endif // NO_PLUGINS } void CSoundFile::SampleOffset(ModChannel &chn, SmpLength param) const { chn.proTrackerOffset += param; if(param >= chn.nLoopEnd && GetType() == MOD_TYPE_MTM && chn.dwFlags[CHN_LOOP] && chn.nLoopEnd > 0) { // Offset wrap-around param = (param - chn.nLoopStart) % (chn.nLoopEnd - chn.nLoopStart) + chn.nLoopStart; } if(GetType() == MOD_TYPE_MDL && chn.dwFlags[CHN_16BIT]) { // Digitrakker really uses byte offsets, not sample offsets. WTF! param /= 2u; } if(chn.rowCommand.IsNote()) { // IT compatibility: If this note is not mapped to a sample, ignore it. // Test case: empty_sample_offset.it if(chn.pModInstrument != nullptr) { SAMPLEINDEX smp = chn.pModInstrument->Keyboard[chn.rowCommand.note - NOTE_MIN]; if(smp == 0 || smp > GetNumSamples()) return; } if(m_SongFlags[SONG_PT_MODE]) { // ProTracker compatbility: PT1/2-style funky 9xx offset command // Test case: ptoffset.mod chn.position.Set(chn.proTrackerOffset); chn.proTrackerOffset += param; } else { chn.position.Set(param); } if (chn.position.GetUInt() >= chn.nLength || (chn.dwFlags[CHN_LOOP] && chn.position.GetUInt() >= chn.nLoopEnd)) { // Offset beyond sample size if (!(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MOD | MOD_TYPE_MTM))) { // IT Compatibility: Offset if(m_playBehaviour[kITOffset]) { if(m_SongFlags[SONG_ITOLDEFFECTS]) chn.position.Set(chn.nLength); // Old FX: Clip to end of sample else chn.position.Set(0); // Reset to beginning of sample } else { chn.position.Set(chn.nLoopStart); if(m_SongFlags[SONG_ITOLDEFFECTS] && chn.nLength > 4) { chn.position.Set(chn.nLength - 2); } } } else if(m_playBehaviour[kFT2OffsetOutOfRange] || GetType() == MOD_TYPE_MTM) { // FT2 Compatibility: Don't play note if offset is beyond sample length // Test case: 3xx-no-old-samp.xm chn.dwFlags.set(CHN_FASTVOLRAMP); chn.nPeriod = 0; } else if(GetType() == MOD_TYPE_MOD && chn.dwFlags[CHN_LOOP]) { chn.position.Set(chn.nLoopStart); } } } else if ((param < chn.nLength) && (GetType() & (MOD_TYPE_MTM | MOD_TYPE_DMF | MOD_TYPE_MDL | MOD_TYPE_PLM))) { // Some trackers can also call offset effects without notes next to them... chn.position.Set(param); } } // void CSoundFile::ReverseSampleOffset(ModChannel &chn, ModCommand::PARAM param) const { if(chn.pModSample != nullptr) { chn.dwFlags.set(CHN_PINGPONGFLAG); chn.dwFlags.reset(CHN_LOOP); chn.nLength = chn.pModSample->nLength; // If there was a loop, extend sample to whole length. chn.position.Set((chn.nLength - 1) - std::min<SmpLength>(SmpLength(param) << 8, chn.nLength - 1), 0); } } void CSoundFile::RetrigNote(CHANNELINDEX nChn, int param, int offset) { // Retrig: bit 8 is set if it's the new XM retrig ModChannel &chn = m_PlayState.Chn[nChn]; int retrigSpeed = param & 0x0F; int16 retrigCount = chn.nRetrigCount; bool doRetrig = false; // IT compatibility 15. Retrigger if(m_playBehaviour[kITRetrigger]) { if(m_PlayState.m_nTickCount == 0 && chn.rowCommand.note) { chn.nRetrigCount = param & 0xf; } else if(!chn.nRetrigCount || !--chn.nRetrigCount) { chn.nRetrigCount = param & 0xf; doRetrig = true; } } else if(m_playBehaviour[kFT2Retrigger] && (param & 0x100)) { // Buggy-like-hell FT2 Rxy retrig! // Test case: retrig.xm if(m_SongFlags[SONG_FIRSTTICK]) { // Here are some really stupid things FT2 does on the first tick. // Test case: RetrigTick0.xm if(chn.rowCommand.instr > 0 && chn.rowCommand.IsNoteOrEmpty()) retrigCount = 1; if(chn.rowCommand.volcmd == VOLCMD_VOLUME && chn.rowCommand.vol != 0) { // I guess this condition simply checked if the volume byte was != 0 in FT2. chn.nRetrigCount = retrigCount; return; } } if(retrigCount >= retrigSpeed) { if(!m_SongFlags[SONG_FIRSTTICK] || !chn.rowCommand.IsNote()) { doRetrig = true; retrigCount = 0; } } } else { // old routines if (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT)) { if (!retrigSpeed) retrigSpeed = 1; if ((retrigCount) && (!(retrigCount % retrigSpeed))) doRetrig = true; retrigCount++; } else if(GetType() == MOD_TYPE_MTM) { // In MultiTracker, E9x retriggers the last note at exactly the x-th tick of the row doRetrig = m_PlayState.m_nTickCount == static_cast<uint32>(param & 0x0F) && retrigSpeed != 0; } else { int realspeed = retrigSpeed; // FT2 bug: if a retrig (Rxy) occurs together with a volume command, the first retrig interval is increased by one tick if ((param & 0x100) && (chn.rowCommand.volcmd == VOLCMD_VOLUME) && (chn.rowCommand.param & 0xF0)) realspeed++; if(!m_SongFlags[SONG_FIRSTTICK] || (param & 0x100)) { if (!realspeed) realspeed = 1; if ((!(param & 0x100)) && (m_PlayState.m_nMusicSpeed) && (!(m_PlayState.m_nTickCount % realspeed))) doRetrig = true; retrigCount++; } else if (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) retrigCount = 0; if (retrigCount >= realspeed) { if ((m_PlayState.m_nTickCount) || ((param & 0x100) && (!chn.rowCommand.note))) doRetrig = true; } if(m_playBehaviour[kFT2Retrigger] && param == 0) { // E90 = Retrig instantly, and only once doRetrig = (m_PlayState.m_nTickCount == 0); } } } // IT compatibility: If a sample is shorter than the retrig time (i.e. it stops before the retrig counter hits zero), it is not retriggered. // Test case: retrig-short.it if(chn.nLength == 0 && m_playBehaviour[kITShortSampleRetrig] && !chn.HasMIDIOutput()) { return; } if(doRetrig) { uint32 dv = (param >> 4) & 0x0F; int vol = chn.nVolume; if (dv) { // FT2 compatibility: Retrig + volume will not change volume of retrigged notes if(!m_playBehaviour[kFT2Retrigger] || !(chn.rowCommand.volcmd == VOLCMD_VOLUME)) { if (retrigTable1[dv]) vol = (vol * retrigTable1[dv]) >> 4; else vol += ((int)retrigTable2[dv]) << 2; } Limit(vol, 0, 256); chn.dwFlags.set(CHN_FASTVOLRAMP); } uint32 note = chn.nNewNote; int32 oldPeriod = chn.nPeriod; if (note >= NOTE_MIN && note <= NOTE_MAX && chn.nLength) CheckNNA(nChn, 0, note, true); bool resetEnv = false; if(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)) { if((chn.rowCommand.instr) && (param < 0x100)) { InstrumentChange(&chn, chn.rowCommand.instr, false, false); resetEnv = true; } if (param < 0x100) resetEnv = true; } bool fading = chn.dwFlags[CHN_NOTEFADE]; // IT compatibility: Really weird combination of envelopes and retrigger (see Storlek's q.it testcase) // Test case: retrig.it NoteChange(&chn, note, m_playBehaviour[kITRetrigger], resetEnv); // XM compatibility: Prevent NoteChange from resetting the fade flag in case an instrument number + note-off is present. // Test case: RetrigFade.xm if(fading && GetType() == MOD_TYPE_XM) chn.dwFlags.set(CHN_NOTEFADE); chn.nVolume = vol; if(m_nInstruments) { chn.rowCommand.note = static_cast<ModCommand::NOTE>(note); // No retrig without note... #ifndef NO_PLUGINS ProcessMidiOut(nChn); //Send retrig to Midi #endif // NO_PLUGINS } if ((GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT)) && (!chn.rowCommand.note) && (oldPeriod)) chn.nPeriod = oldPeriod; if (!(GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))) retrigCount = 0; // IT compatibility: see previous IT compatibility comment =) if(m_playBehaviour[kITRetrigger]) chn.position.Set(0); offset--; if(offset >= 0 && offset <= static_cast<int>(CountOf(chn.pModSample->cues)) && chn.pModSample != nullptr) { if(offset == 0) offset = chn.oldOffset; else offset = chn.oldOffset = chn.pModSample->cues[offset - 1]; SampleOffset(chn, offset); } } // buggy-like-hell FT2 Rxy retrig! if(m_playBehaviour[kFT2Retrigger] && (param & 0x100)) retrigCount++; // Now we can also store the retrig value for IT... if(!m_playBehaviour[kITRetrigger]) chn.nRetrigCount = retrigCount; } void CSoundFile::DoFreqSlide(ModChannel *pChn, int32 nFreqSlide) const { if(!pChn->nPeriod) return; if(GetType() == MOD_TYPE_669) { // Like other oldskool trackers, Composer 669 doesn't have linear slides... // But the slides are done in Hertz rather than periods, meaning that they // are more effective in the lower notes (rather than the higher notes). nFreqSlide *= -20; } if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { // IT Linear slides const auto nOldPeriod = pChn->nPeriod; uint32 n = mpt::abs(nFreqSlide) / 4u; LimitMax(n, 255u); if(n != 0) { pChn->nPeriod = Util::muldivr(pChn->nPeriod, nFreqSlide < 0 ? GetLinearSlideUpTable(this, n) : GetLinearSlideDownTable(this, n), 65536); if(pChn->nPeriod == nOldPeriod) { const bool incPeriod = m_playBehaviour[kHertzInLinearMode] == (nFreqSlide < 0); if(incPeriod && pChn->nPeriod < Util::MaxValueOfType(pChn->nPeriod)) pChn->nPeriod++; else if(!incPeriod && pChn->nPeriod > 1) pChn->nPeriod--; } } } else { pChn->nPeriod += nFreqSlide; } if (pChn->nPeriod < 1) { pChn->nPeriod = 1; if(GetType() == MOD_TYPE_S3M) { pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } void CSoundFile::NoteCut(CHANNELINDEX nChn, uint32 nTick, bool cutSample) { if (m_PlayState.m_nTickCount == nTick) { ModChannel *pChn = &m_PlayState.Chn[nChn]; if(cutSample) { pChn->increment.Set(0); pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE); } else { pChn->nVolume = 0; } pChn->dwFlags.set(CHN_FASTVOLRAMP); // instro sends to a midi chan SendMIDINote(nChn, /*pChn->nNote+*/NOTE_MAX_SPECIAL, 0); } } void CSoundFile::KeyOff(ModChannel *pChn) const { const bool bKeyOn = !pChn->dwFlags[CHN_KEYOFF]; pChn->dwFlags.set(CHN_KEYOFF); if(pChn->pModInstrument != nullptr && !pChn->VolEnv.flags[ENV_ENABLED]) { pChn->dwFlags.set(CHN_NOTEFADE); } if (!pChn->nLength) return; if (pChn->dwFlags[CHN_SUSTAINLOOP] && pChn->pModSample && bKeyOn) { const ModSample *pSmp = pChn->pModSample; if(pSmp->uFlags[CHN_LOOP]) { if (pSmp->uFlags[CHN_PINGPONGLOOP]) pChn->dwFlags.set(CHN_PINGPONGLOOP); else pChn->dwFlags.reset(CHN_PINGPONGLOOP | CHN_PINGPONGFLAG); pChn->dwFlags.set(CHN_LOOP); pChn->nLength = pSmp->nLength; pChn->nLoopStart = pSmp->nLoopStart; pChn->nLoopEnd = pSmp->nLoopEnd; if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd; if(pChn->position.GetUInt() > pChn->nLength) { // Test case: SusAfterLoop.it pChn->position.Set(pChn->position.GetInt() - pChn->nLength + pChn->nLoopStart); } } else { pChn->dwFlags.reset(CHN_LOOP | CHN_PINGPONGLOOP | CHN_PINGPONGFLAG); pChn->nLength = pSmp->nLength; } } if (pChn->pModInstrument) { const ModInstrument *pIns = pChn->pModInstrument; if((pIns->VolEnv.dwFlags[ENV_LOOP] || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MDL))) && pIns->nFadeOut != 0) { pChn->dwFlags.set(CHN_NOTEFADE); } if (pIns->VolEnv.nReleaseNode != ENV_RELEASE_NODE_UNSET && pChn->VolEnv.nEnvValueAtReleaseJump == NOT_YET_RELEASED) { pChn->VolEnv.nEnvValueAtReleaseJump = pIns->VolEnv.GetValueFromPosition(pChn->VolEnv.nEnvPosition, 256); pChn->VolEnv.nEnvPosition = pIns->VolEnv[pIns->VolEnv.nReleaseNode].tick; } } } ////////////////////////////////////////////////////////// // CSoundFile: Global Effects void CSoundFile::SetSpeed(PlayState &playState, uint32 param) const { #ifdef MODPLUG_TRACKER // FT2 appears to be decrementing the tick count before checking for zero, // so it effectively counts down 65536 ticks with speed = 0 (song speed is a 16-bit variable in FT2) if(GetType() == MOD_TYPE_XM && !param) { playState.m_nMusicSpeed = uint16_max; } #endif // MODPLUG_TRACKER if(param > 0) playState.m_nMusicSpeed = param; if(GetType() == MOD_TYPE_STM && param > 0) { playState.m_nMusicSpeed = std::max<uint32>(param >> 4u, 1); playState.m_nMusicTempo = ConvertST2Tempo(static_cast<uint8>(param)); } } // Convert a ST2 tempo byte to classic tempo and speed combination TEMPO CSoundFile::ConvertST2Tempo(uint8 tempo) { static const uint8 ST2TempoFactor[] = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 }; static const uint32 st2MixingRate = 23863; // Highest possible setting in ST2 // This underflows at tempo 06...0F, and the resulting tick lengths depend on the mixing rate. int32 samplesPerTick = st2MixingRate / (49 - ((ST2TempoFactor[tempo >> 4u] * (tempo & 0x0F)) >> 4u)); if(samplesPerTick <= 0) samplesPerTick += 65536; return TEMPO().SetRaw(Util::muldivrfloor(st2MixingRate, 5 * TEMPO::fractFact, samplesPerTick * 2)); } void CSoundFile::SetTempo(TEMPO param, bool setFromUI) { const CModSpecifications &specs = GetModSpecifications(); // Anything lower than the minimum tempo is considered to be a tempo slide const TEMPO minTempo = (GetType() == MOD_TYPE_MDL) ? TEMPO(1, 0) : TEMPO(32, 0); if(setFromUI) { // Set tempo from UI - ignore slide commands and such. m_PlayState.m_nMusicTempo = Clamp(param, specs.GetTempoMin(), specs.GetTempoMax()); } else if(param >= minTempo && m_SongFlags[SONG_FIRSTTICK] == !m_playBehaviour[kMODTempoOnSecondTick]) { // ProTracker sets the tempo after the first tick. // Note: The case of one tick per row is handled in ProcessRow() instead. // Test case: TempoChange.mod m_PlayState.m_nMusicTempo = std::min(param, specs.GetTempoMax()); } else if(param < minTempo && !m_SongFlags[SONG_FIRSTTICK]) { // Tempo Slide TEMPO tempDiff(param.GetInt() & 0x0F, 0); if((param.GetInt() & 0xF0) == 0x10) m_PlayState.m_nMusicTempo += tempDiff; else m_PlayState.m_nMusicTempo -= tempDiff; TEMPO tempoMin = specs.GetTempoMin(), tempoMax = specs.GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(m_PlayState.m_nMusicTempo, tempoMin, tempoMax); } } ROWINDEX CSoundFile::PatternLoop(ModChannel *pChn, uint32 param) { if (param) { // Loop Repeat if(pChn->nPatternLoopCount) { // There's a loop left pChn->nPatternLoopCount--; if(!pChn->nPatternLoopCount) { // IT compatibility 10. Pattern loops (+ same fix for S3M files) // When finishing a pattern loop, the next loop without a dedicated SB0 starts on the first row after the previous loop. if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { pChn->nPatternLoop = m_PlayState.m_nRow + 1; } return ROWINDEX_INVALID; } } else { // First time we get into the loop => Set loop count. // IT compatibility 10. Pattern loops (+ same fix for XM / MOD / S3M files) if(!m_playBehaviour[kITFT2PatternLoop] && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_S3M))) { ModChannel *p = m_PlayState.Chn; for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, p++) if (p != pChn) { // Loop on other channel if(p->nPatternLoopCount) return ROWINDEX_INVALID; } } pChn->nPatternLoopCount = static_cast<uint8>(param); } m_PlayState.m_nNextPatStartRow = pChn->nPatternLoop; // Nasty FT2 E60 bug emulation! return pChn->nPatternLoop; } else { // Loop Start pChn->nPatternLoop = m_PlayState.m_nRow; } return ROWINDEX_INVALID; } void CSoundFile::GlobalVolSlide(ModCommand::PARAM param, uint8 &nOldGlobalVolSlide) { int32 nGlbSlide = 0; if (param) nOldGlobalVolSlide = param; else param = nOldGlobalVolSlide; if((GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { // XM nibble priority if((param & 0xF0) != 0) { param &= 0xF0; } else { param &= 0x0F; } } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { if(m_SongFlags[SONG_FIRSTTICK]) nGlbSlide = (param >> 4) * 2; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { if(m_SongFlags[SONG_FIRSTTICK]) nGlbSlide = - (int)((param & 0x0F) * 2); } else { if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0xF0) { // IT compatibility: Ignore slide commands with both nibbles set. if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM)) || (param & 0x0F) == 0) nGlbSlide = (int)((param & 0xF0) >> 4) * 2; } else { nGlbSlide = -(int)((param & 0x0F) * 2); } } } if (nGlbSlide) { if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM))) nGlbSlide *= 2; nGlbSlide += m_PlayState.m_nGlobalVolume; Limit(nGlbSlide, 0, 256); m_PlayState.m_nGlobalVolume = nGlbSlide; } } ////////////////////////////////////////////////////// // Note/Period/Frequency functions // Find lowest note which has same or lower period as a given period (i.e. the note has the same or higher frequency) uint32 CSoundFile::GetNoteFromPeriod(uint32 period, int32 nFineTune, uint32 nC5Speed) const { if(!period) return 0; if(m_playBehaviour[kFT2Periods]) { // FT2's "RelocateTon" function actually rounds up and down, while GetNoteFromPeriod normally just truncates. nFineTune += 64; } // This essentially implements std::lower_bound, with the difference that we don't need an iterable container. uint32 minNote = NOTE_MIN, maxNote = NOTE_MAX, count = maxNote - minNote + 1; const bool periodIsFreq = PeriodsAreFrequencies(); while(count > 0) { const uint32 step = count / 2, midNote = minNote + step; uint32 n = GetPeriodFromNote(midNote, nFineTune, nC5Speed); if((n > period && !periodIsFreq) || (n < period && periodIsFreq) || !n) { minNote = midNote + 1; count -= step + 1; } else { count = step; } } return minNote; } uint32 CSoundFile::GetPeriodFromNote(uint32 note, int32 nFineTune, uint32 nC5Speed) const { if (note == NOTE_NONE || (note >= NOTE_MIN_SPECIAL)) return 0; note -= NOTE_MIN; if (!UseFinetuneAndTranspose()) { if(GetType() & (MOD_TYPE_MDL | MOD_TYPE_DTM)) { // MDL uses non-linear slides, but their effectiveness does not depend on the middle-C frequency. return (FreqS3MTable[note % 12u] << 4) >> (note / 12); } if(m_SongFlags[SONG_LINEARSLIDES] || GetType() == MOD_TYPE_669) { // In IT linear slide mode, directly use frequency in Hertz rather than periods. if(m_playBehaviour[kHertzInLinearMode] || GetType() == MOD_TYPE_669) return Util::muldiv_unsigned(nC5Speed, LinearSlideUpTable[(note % 12u) * 16u] << (note / 12u), 65536 << 5); else return (FreqS3MTable[note % 12u] << 5) >> (note / 12); } else { if (!nC5Speed) nC5Speed = 8363; LimitMax(nC5Speed, uint32_max >> (note / 12u)); //(a*b)/c return Util::muldiv_unsigned(8363, (FreqS3MTable[note % 12u] << 5), nC5Speed << (note / 12u)); //8363 * freq[note%12] / nC5Speed * 2^(5-note/12) } } else if (GetType() == MOD_TYPE_XM) { if (note < 12) note = 12; note -= 12; // FT2 Compatibility: The lower three bits of the finetune are truncated. // Test case: Finetune-Precision.xm if(m_playBehaviour[kFT2FinetunePrecision]) { nFineTune &= ~7; } if(m_SongFlags[SONG_LINEARSLIDES]) { int l = ((NOTE_MAX - note) << 6) - (nFineTune / 2); if (l < 1) l = 1; return static_cast<uint32>(l); } else { int finetune = nFineTune; uint32 rnote = (note % 12) << 3; uint32 roct = note / 12; int rfine = finetune / 16; int i = rnote + rfine + 8; Limit(i , 0, 103); uint32 per1 = XMPeriodTable[i]; if(finetune < 0) { rfine--; finetune = -finetune; } else rfine++; i = rnote+rfine+8; if (i < 0) i = 0; if (i >= 104) i = 103; uint32 per2 = XMPeriodTable[i]; rfine = finetune & 0x0F; per1 *= 16-rfine; per2 *= rfine; return ((per1 + per2) << 1) >> roct; } } else { nFineTune = XM2MODFineTune(nFineTune); if ((nFineTune) || (note < 36) || (note >= 36 + 6 * 12)) return (ProTrackerTunedPeriods[nFineTune * 12u + note % 12u] << 5) >> (note / 12u); else return (ProTrackerPeriodTable[note - 36] << 2); } } // Converts period value to sample frequency. Return value is fixed point, with FREQ_FRACBITS fractional bits. uint32 CSoundFile::GetFreqFromPeriod(uint32 period, uint32 c5speed, int32 nPeriodFrac) const { if (!period) return 0; if (GetType() == MOD_TYPE_XM) { if(m_playBehaviour[kFT2Periods]) { // FT2 compatibility: Period is a 16-bit value in FT2, and it overflows happily. // Test case: FreqWraparound.xm period &= 0xFFFF; } if(m_SongFlags[SONG_LINEARSLIDES]) { uint32 octave; if(m_playBehaviour[kFT2Periods]) { // Under normal circumstances, this calculation returns the same values as the non-compatible one. // However, once the 12 octaves are exceeded (through portamento slides), the octave shift goes // crazy in FT2, meaning that the frequency wraps around randomly... // The entries in FT2's conversion table are four times as big, hence we have to do an additional shift by two bits. // Test case: FreqWraparound.xm // 12 octaves * (12 * 64) LUT entries = 9216, add 767 for rounding uint32 div = ((9216u + 767u - period) / 768); octave = ((14 - div) & 0x1F); } else { octave = (period / 768) + 2; } return (XMLinearTable[period % 768] << (FREQ_FRACBITS + 2)) >> octave; } else { if(!period) period = 1; return ((8363 * 1712L) << FREQ_FRACBITS) / period; } } else if (UseFinetuneAndTranspose()) { return ((3546895L * 4) << FREQ_FRACBITS) / period; } else if(GetType() == MOD_TYPE_669) { // We only really use c5speed for the finetune pattern command. All samples in 669 files have the same middle-C speed (imported as 8363 Hz). return (period + c5speed - 8363) << FREQ_FRACBITS; } else if(GetType() & (MOD_TYPE_MDL | MOD_TYPE_DTM)) { LimitMax(period, Util::MaxValueOfType(period) >> 8); if (!c5speed) c5speed = 8363; return Util::muldiv_unsigned(c5speed, (1712L << 7) << FREQ_FRACBITS, (period << 8) + nPeriodFrac); } else { LimitMax(period, Util::MaxValueOfType(period) >> 8); if(m_SongFlags[SONG_LINEARSLIDES]) { if(m_playBehaviour[kHertzInLinearMode]) { // IT linear slides already use frequencies instead of periods. static_assert(FREQ_FRACBITS <= 8, "Check this shift operator"); return uint32(((uint64(period) << 8) + nPeriodFrac) >> (8 - FREQ_FRACBITS)); } else { if (!c5speed) c5speed = 8363; return Util::muldiv_unsigned(c5speed, (1712L << 8) << FREQ_FRACBITS, (period << 8) + nPeriodFrac); } } else { return Util::muldiv_unsigned(8363, (1712L << 8) << FREQ_FRACBITS, (period << 8) + nPeriodFrac); } } } PLUGINDEX CSoundFile::GetBestPlugin(CHANNELINDEX nChn, PluginPriority priority, PluginMutePriority respectMutes) const { if (nChn >= MAX_CHANNELS) //Check valid channel number { return 0; } //Define search source order PLUGINDEX nPlugin = 0; switch (priority) { case ChannelOnly: nPlugin = GetChannelPlugin(nChn, respectMutes); break; case InstrumentOnly: nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes); break; case PrioritiseInstrument: nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes); if ((!nPlugin) || (nPlugin > MAX_MIXPLUGINS)) { nPlugin = GetChannelPlugin(nChn, respectMutes); } break; case PrioritiseChannel: nPlugin = GetChannelPlugin(nChn, respectMutes); if ((!nPlugin) || (nPlugin > MAX_MIXPLUGINS)) { nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes); } break; } return nPlugin; // 0 Means no plugin found. } PLUGINDEX CSoundFile::GetChannelPlugin(CHANNELINDEX nChn, PluginMutePriority respectMutes) const { const ModChannel &channel = m_PlayState.Chn[nChn]; PLUGINDEX nPlugin; if((respectMutes == RespectMutes && channel.dwFlags[CHN_MUTE]) || channel.dwFlags[CHN_NOFX]) { nPlugin = 0; } else { // If it looks like this is an NNA channel, we need to find the master channel. // This ensures we pick up the right ChnSettings. // NB: nMasterChn == 0 means no master channel, so we need to -1 to get correct index. if (nChn >= m_nChannels && channel.nMasterChn > 0) { nChn = channel.nMasterChn - 1; } if(nChn < MAX_BASECHANNELS) { nPlugin = ChnSettings[nChn].nMixPlugin; } else { nPlugin = 0; } } return nPlugin; } PLUGINDEX CSoundFile::GetActiveInstrumentPlugin(CHANNELINDEX nChn, PluginMutePriority respectMutes) const { // Unlike channel settings, pModInstrument is copied from the original chan to the NNA chan, // so we don't need to worry about finding the master chan. PLUGINDEX plug = 0; if(m_PlayState.Chn[nChn].pModInstrument != nullptr) { if(respectMutes == RespectMutes && m_PlayState.Chn[nChn].pModSample && m_PlayState.Chn[nChn].pModSample->uFlags[CHN_MUTE]) { plug = 0; } else { plug = m_PlayState.Chn[nChn].pModInstrument->nMixPlug; } } return plug; } // Retrieve the plugin that is associated with the channel's current instrument. // No plugin is returned if the channel is muted or if the instrument doesn't have a MIDI channel set up, // As this is meant to be used with instrument plugins. IMixPlugin *CSoundFile::GetChannelInstrumentPlugin(CHANNELINDEX chn) const { #ifndef NO_PLUGINS if(m_PlayState.Chn[chn].dwFlags[CHN_MUTE | CHN_SYNCMUTE]) { // Don't process portamento on muted channels. Note that this might have a side-effect // on other channels which trigger notes on the same MIDI channel of the same plugin, // as those won't be pitch-bent anymore. return nullptr; } if(m_PlayState.Chn[chn].HasMIDIOutput()) { const ModInstrument *pIns = m_PlayState.Chn[chn].pModInstrument; // Instrument sends to a MIDI channel if(pIns->nMixPlug != 0 && pIns->nMixPlug <= MAX_MIXPLUGINS) { return m_MixPlugins[pIns->nMixPlug - 1].pMixPlugin; } } #else MPT_UNREFERENCED_PARAMETER(chn); #endif // NO_PLUGINS return nullptr; } // Get the MIDI channel currently associated with a given tracker channel uint8 CSoundFile::GetBestMidiChannel(CHANNELINDEX nChn) const { if(nChn >= MAX_CHANNELS) { return 0; } const ModInstrument *ins = m_PlayState.Chn[nChn].pModInstrument; if(ins != nullptr) { if(ins->nMidiChannel == MidiMappedChannel) { // For mapped channels, return their pattern channel, modulo 16 (because there are only 16 MIDI channels) return (m_PlayState.Chn[nChn].nMasterChn ? (m_PlayState.Chn[nChn].nMasterChn - 1) : nChn) % 16; } else if(ins->HasValidMIDIChannel()) { return (ins->nMidiChannel - 1) & 0x0F; } } return 0; } #ifdef MODPLUG_TRACKER void CSoundFile::HandlePatternTransitionEvents() { // MPT sequence override if(m_PlayState.m_nSeqOverride != ORDERINDEX_INVALID && m_PlayState.m_nSeqOverride < Order().size()) { if(m_SongFlags[SONG_PATTERNLOOP]) { m_PlayState.m_nPattern = Order()[m_PlayState.m_nSeqOverride]; } m_PlayState.m_nCurrentOrder = m_PlayState.m_nSeqOverride; m_PlayState.m_nSeqOverride = ORDERINDEX_INVALID; } // Channel mutes for (CHANNELINDEX chan = 0; chan < GetNumChannels(); chan++) { if (m_bChannelMuteTogglePending[chan]) { if(GetpModDoc()) { GetpModDoc()->MuteChannel(chan, !GetpModDoc()->IsChannelMuted(chan)); } m_bChannelMuteTogglePending[chan] = false; } } } #endif // MODPLUG_TRACKER // Update time signatures (global or pattern-specific). Don't forget to call this when changing the RPB/RPM settings anywhere! void CSoundFile::UpdateTimeSignature() { if(!Patterns.IsValidIndex(m_PlayState.m_nPattern) || !Patterns[m_PlayState.m_nPattern].GetOverrideSignature()) { m_PlayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; m_PlayState.m_nCurrentRowsPerMeasure = m_nDefaultRowsPerMeasure; } else { m_PlayState.m_nCurrentRowsPerBeat = Patterns[m_PlayState.m_nPattern].GetRowsPerBeat(); m_PlayState.m_nCurrentRowsPerMeasure = Patterns[m_PlayState.m_nPattern].GetRowsPerMeasure(); } } void CSoundFile::PortamentoMPT(ModChannel* pChn, int param) { //Behavior: Modifies portamento by param-steps on every tick. //Note that step meaning depends on tuning. pChn->m_PortamentoFineSteps += param; pChn->m_CalculateFreq = true; } void CSoundFile::PortamentoFineMPT(ModChannel* pChn, int param) { //Behavior: Divides portamento change between ticks/row. For example //if Ticks/row == 6, and param == +-6, portamento goes up/down by one tuning-dependent //fine step every tick. if(m_PlayState.m_nTickCount == 0) pChn->nOldFinePortaUpDown = 0; const int tickParam = static_cast<int>((m_PlayState.m_nTickCount + 1.0) * param / m_PlayState.m_nMusicSpeed); pChn->m_PortamentoFineSteps += (param >= 0) ? tickParam - pChn->nOldFinePortaUpDown : tickParam + pChn->nOldFinePortaUpDown; if(m_PlayState.m_nTickCount + 1 == m_PlayState.m_nMusicSpeed) pChn->nOldFinePortaUpDown = static_cast<int8>(mpt::abs(param)); else pChn->nOldFinePortaUpDown = static_cast<int8>(mpt::abs(tickParam)); pChn->m_CalculateFreq = true; } void CSoundFile::PortamentoExtraFineMPT(ModChannel* pChn, int param) { // This kinda behaves like regular fine portamento. // It changes the pitch by n finetune steps on the first tick. if(pChn->isFirstTick) { pChn->m_PortamentoFineSteps += param; pChn->m_CalculateFreq = true; } } OPENMPT_NAMESPACE_END
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_65_0
crossvul-cpp_data_good_2323_0
/* This file has been derived from Konversation, the KDE IRC client. 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 2 of the License, or (at your option) any later version. */ /* Copyright (C) 1997 Robey Pointer <robeypointer@gmail.com> Copyright (C) 2005 Ismail Donmez <ismail@kde.org> Copyright (C) 2009 Travis McHenry <tmchenryaz@cox.net> Copyright (C) 2009 Johannes Huber <johu@gmx.de> */ #include "cipher.h" #include "logger.h" Cipher::Cipher() { m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923"); setType("blowfish"); } Cipher::Cipher(QByteArray key, QString cipherType) { m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923"); setKey(key); setType(cipherType); } Cipher::~Cipher() {} bool Cipher::setKey(QByteArray key) { if (key.isEmpty()) { m_key.clear(); return false; } if (key.mid(0, 4).toLower() == "ecb:") { m_cbc = false; m_key = key.mid(4); } //strip cbc: if included else if (key.mid(0, 4).toLower() == "cbc:") { m_cbc = true; m_key = key.mid(4); } else { // if(Preferences::self()->encryptionType()) // m_cbc = true; // else m_cbc = false; m_key = key; } return true; } bool Cipher::setType(const QString &type) { //TODO check QCA::isSupported() m_type = type; return true; } QByteArray Cipher::decrypt(QByteArray cipherText) { QByteArray pfx = ""; bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type //if we get cbc if (cipherText.mid(0, 5) == "+OK *") { //if we have cbc if (m_cbc) cipherText = cipherText.mid(5); //if we don't else { cipherText = cipherText.mid(5); pfx = "ERROR_NONECB: "; error = true; } } //if we get ecb else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ") { //if we had cbc if (m_cbc) { cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5); pfx = "ERROR_NONCBC: "; error = true; } //if we don't else { if (cipherText.mid(0, 4) == "+OK ") cipherText = cipherText.mid(4); else cipherText = cipherText.mid(5); } } //all other cases we fail else return cipherText; QByteArray temp; // (if cbc and no error we parse cbc) || (if ecb and error we parse cbc) if ((m_cbc && !error) || (!m_cbc && error)) { cipherText = cipherText; temp = blowfishCBC(cipherText, false); if (temp == cipherText) { // kDebug("Decryption from CBC Failed"); return cipherText+' '+'\n'; } else cipherText = temp; } else { temp = blowfishECB(cipherText, false); if (temp == cipherText) { // kDebug("Decryption from ECB Failed"); return cipherText+' '+'\n'; } else cipherText = temp; } // TODO FIXME the proper fix for this is to show encryption differently e.g. [nick] instead of <nick> // don't hate me for the mircryption reference there. if (cipherText.at(0) == 1) pfx = "\x0"; cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here? return cipherText; } QByteArray Cipher::initKeyExchange() { QCA::Initializer init; m_tempKey = QCA::KeyGenerator().createDH(QCA::DLGroup(m_primeNum, QCA::BigInteger(2))).toDH(); if (m_tempKey.isNull()) return QByteArray(); QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray(); //remove leading 0 if (publicKey.length() > 135 && publicKey.at(0) == '\0') publicKey = publicKey.mid(1); return publicKey.toBase64().append('A'); } QByteArray Cipher::parseInitKeyX(QByteArray key) { QCA::Initializer init; bool isCBC = false; if (key.endsWith(" CBC")) { isCBC = true; key.chop(4); } if (key.length() != 181) return QByteArray(); QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180)); QCA::DLGroup group(m_primeNum, QCA::BigInteger(2)); QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH(); if (privateKey.isNull()) return QByteArray(); QByteArray publicKey = privateKey.y().toArray().toByteArray(); //remove leading 0 if (publicKey.length() > 135 && publicKey.at(0) == '\0') publicKey = publicKey.mid(1); QCA::DHPublicKey remotePub(group, remoteKey); if (remotePub.isNull()) return QByteArray(); QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); //remove trailing = because mircryption and fish think it's a swell idea. while (sharedKey.endsWith('=')) sharedKey.chop(1); if (isCBC) sharedKey.prepend("cbc:"); bool success = setKey(sharedKey); if (!success) return QByteArray(); return publicKey.toBase64().append('A'); } bool Cipher::parseFinishKeyX(QByteArray key) { QCA::Initializer init; if (key.length() != 181) return false; QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180)); QCA::DLGroup group(m_primeNum, QCA::BigInteger(2)); QCA::DHPublicKey remotePub(group, remoteKey); if (remotePub.isNull()) return false; if (m_tempKey.isNull()) return false; QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); //remove trailng = because mircryption and fish think it's a swell idea. while (sharedKey.endsWith('=')) sharedKey.chop(1); bool success = setKey(sharedKey); return success; } QByteArray Cipher::decryptTopic(QByteArray cipherText) { if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic cipherText = cipherText.mid(4); else if (cipherText.left(5) == "«m«") cipherText = cipherText.mid(5, cipherText.length()-10); else return cipherText; QByteArray temp; //TODO currently no backwards sanity checks for topic, it seems to use different standards //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings if (m_cbc) temp = blowfishCBC(cipherText.mid(1), false); else temp = blowfishECB(cipherText, false); if (temp == cipherText) { return cipherText; } else cipherText = temp; if (cipherText.mid(0, 2) == "@@") cipherText = cipherText.mid(2); return cipherText; } bool Cipher::encrypt(QByteArray &cipherText) { if (cipherText.left(3) == "+p ") //don't encode if...? cipherText = cipherText.mid(3); else { if (m_cbc) //encode in ecb or cbc decide how to determine later { QByteArray temp = blowfishCBC(cipherText, true); if (temp == cipherText) { // kDebug("CBC Encoding Failed"); return false; } cipherText = "+OK *" + temp; } else { QByteArray temp = blowfishECB(cipherText, true); if (temp == cipherText) { // kDebug("ECB Encoding Failed"); return false; } cipherText = "+OK " + temp; } } return true; } //THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; if (direction) { // make sure cipherText is an interval of 8 bits. We do this before so that we // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail while ((temp.length() % 8) != 0) temp.append('\0'); QCA::InitializationVector iv(8); temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation } else { temp = QByteArray::fromBase64(temp); //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy' //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0"))); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) //send in base64 temp2 = temp2.toBase64(); else //cut off the 8bits of IV temp2 = temp2.remove(0, 8); return temp2; } QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; //do padding ourselves if (direction) { while ((temp.length() % 8) != 0) temp.append('\0'); } else { // ECB Blowfish encodes in blocks of 12 chars, so anything else is malformed input if ((temp.length() % 12) != 0) return cipherText; temp = b64ToByte(temp); while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) { // Sanity check if ((temp2.length() % 8) != 0) return cipherText; temp2 = byteToB64(temp2); } return temp2; } //Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility QByteArray Cipher::byteToB64(QByteArray text) { int left = 0; int right = 0; int k = -1; int v; QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; QByteArray encoded; while (k < (text.length() - 1)) { k++; v = text.at(k); if (v < 0) v += 256; left = v << 24; k++; v = text.at(k); if (v < 0) v += 256; left += v << 16; k++; v = text.at(k); if (v < 0) v += 256; left += v << 8; k++; v = text.at(k); if (v < 0) v += 256; left += v; k++; v = text.at(k); if (v < 0) v += 256; right = v << 24; k++; v = text.at(k); if (v < 0) v += 256; right += v << 16; k++; v = text.at(k); if (v < 0) v += 256; right += v << 8; k++; v = text.at(k); if (v < 0) v += 256; right += v; for (int i = 0; i < 6; i++) { encoded.append(base64.at(right & 0x3F).toAscii()); right = right >> 6; } //TODO make sure the .toascii doesn't break anything for (int i = 0; i < 6; i++) { encoded.append(base64.at(left & 0x3F).toAscii()); left = left >> 6; } } return encoded; } QByteArray Cipher::b64ToByte(QByteArray text) { QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; QByteArray decoded; int k = -1; while (k < (text.length() - 1)) { int right = 0; int left = 0; int v = 0; int w = 0; int z = 0; for (int i = 0; i < 6; i++) { k++; v = base64.indexOf(text.at(k)); right |= v << (i * 6); } for (int i = 0; i < 6; i++) { k++; v = base64.indexOf(text.at(k)); left |= v << (i * 6); } for (int i = 0; i < 4; i++) { w = ((left & (0xFF << ((3 - i) * 8)))); z = w >> ((3 - i) * 8); if (z < 0) { z = z + 256; } decoded.append(z); } for (int i = 0; i < 4; i++) { w = ((right & (0xFF << ((3 - i) * 8)))); z = w >> ((3 - i) * 8); if (z < 0) { z = z + 256; } decoded.append(z); } } return decoded; } bool Cipher::neededFeaturesAvailable() { QCA::Initializer init; if (QCA::isSupported("blowfish-ecb") && QCA::isSupported("blowfish-cbc") && QCA::isSupported("dh")) return true; return false; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_2323_0
crossvul-cpp_data_bad_1380_1
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/bz2/bz2-file.h" #include "hphp/runtime/base/array-init.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// BZ2File::BZ2File(): m_bzFile(nullptr), m_innerFile(req::make<PlainFile>()) { m_innerFile->unregister(); setIsLocal(m_innerFile->isLocal()); } BZ2File::BZ2File(req::ptr<PlainFile>&& innerFile) : m_bzFile(nullptr), m_innerFile(std::move(innerFile)) { setIsLocal(m_innerFile->isLocal()); } BZ2File::~BZ2File() { closeImpl(); } void BZ2File::sweep() { closeImpl(); File::sweep(); } bool BZ2File::open(const String& filename, const String& mode) { assertx(m_bzFile == nullptr); return m_innerFile->open(filename, mode) && (m_bzFile = BZ2_bzdopen(dup(m_innerFile->fd()), mode.data())); } bool BZ2File::close() { invokeFiltersOnClose(); return closeImpl(); } int64_t BZ2File::errnu() { assertx(m_bzFile); int errnum = 0; BZ2_bzerror(m_bzFile, &errnum); return errnum; } String BZ2File::errstr() { assertx(m_bzFile); int errnum; return BZ2_bzerror(m_bzFile, &errnum); } const StaticString s_errno("errno"), s_errstr("errstr"); Array BZ2File::error() { assertx(m_bzFile); int errnum; const char * errstr; errstr = BZ2_bzerror(m_bzFile, &errnum); return make_map_array(s_errno, errnum, s_errstr, String(errstr)); } bool BZ2File::flush() { assertx(m_bzFile); return BZ2_bzflush(m_bzFile); } int64_t BZ2File::readImpl(char * buf, int64_t length) { if (length == 0) { return 0; } assertx(m_bzFile); int len = BZ2_bzread(m_bzFile, buf, length); /* Sometimes libbz2 will return fewer bytes than requested, and set bzerror * to BZ_STREAM_END, but it's not actually EOF, and you can keep reading from * the file - so, only set EOF after a failed read. This matches PHP5. */ if (len <= 0) { setEof(true); if (len < 0) { return -1; } } return len; } int64_t BZ2File::writeImpl(const char * buf, int64_t length) { assertx(m_bzFile); return BZ2_bzwrite(m_bzFile, (char *)buf, length); } bool BZ2File::closeImpl() { if (!isClosed()) { if (m_bzFile) { BZ2_bzclose(m_bzFile); m_bzFile = nullptr; } setIsClosed(true); if (m_innerFile) { m_innerFile->close(); } } File::closeImpl(); return true; } bool BZ2File::eof() { assertx(m_bzFile); return getEof(); } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_1380_1
crossvul-cpp_data_bad_4252_0
/* JSON_parser.c */ /* 2005-12-30 */ /* Copyright (c) 2005 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // If we have json-c then don't use this library since that one has a more // permissive licence #ifndef HAVE_JSONC #include "hphp/runtime/ext/json/JSON_parser.h" #include <folly/FBVector.h> #include "hphp/runtime/base/array-provenance.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/collections.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-info.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/base/init-fini-node.h" #include "hphp/runtime/base/utf8-decode.h" #include "hphp/runtime/ext/json/ext_json.h" #include "hphp/runtime/ext/collections/ext_collections-map.h" #include "hphp/runtime/ext/collections/ext_collections-vector.h" #include "hphp/system/systemlib.h" #include "hphp/util/fast_strtoll_base10.h" #include "hphp/zend/zend-strtod.h" #define MAX_LENGTH_OF_LONG 20 static const char long_min_digits[] = "9223372036854775808"; namespace HPHP { /* Characters are mapped into these 32 symbol classes. This allows for significant reductions in the size of the state transition table. */ /* error */ #define S_ERR -1 /* space */ #define S_SPA 0 /* other whitespace */ #define S_WSP 1 /* { */ #define S_LBE 2 /* } */ #define S_RBE 3 /* [ */ #define S_LBT 4 /* ] */ #define S_RBT 5 /* : */ #define S_COL 6 /* , */ #define S_COM 7 /* " */ #define S_QUO 8 /* \ */ #define S_BAC 9 /* / */ #define S_SLA 10 /* + */ #define S_PLU 11 /* - */ #define S_MIN 12 /* . */ #define S_DOT 13 /* 0 */ #define S_ZER 14 /* 123456789 */ #define S_DIG 15 /* a */ #define S__A_ 16 /* b */ #define S__B_ 17 /* c */ #define S__C_ 18 /* d */ #define S__D_ 19 /* e */ #define S__E_ 20 /* f */ #define S__F_ 21 /* l */ #define S__L_ 22 /* n */ #define S__N_ 23 /* r */ #define S__R_ 24 /* s */ #define S__S_ 25 /* t */ #define S__T_ 26 /* u */ #define S__U_ 27 /* ABCDF */ #define S_A_F 28 /* E */ #define S_E 29 /* everything else */ #define S_ETC 30 /* This table maps the 128 ASCII characters into the 32 character classes. The remaining Unicode characters should be mapped to S_ETC. */ alignas(64) static const int8_t ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*<fb>*/ alignas(64) static const int8_t loose_ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*</fb>*/ /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. A new state is a number between 0 and 29. An action is a negative number between -1 and -9. A JSON text is accepted if the end of the text is in state 9 and mode is Mode::DONE. */ alignas(64) static const int8_t state_transition_table[30][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} }; /*<fb>*/ /* Alternate "loose" transition table to support unquoted keys. Note: State 3 has same outgoing transitions in both transition tables. This is used below in the fast-case for appending simple characters (3 -> 3). */ alignas(64) static const int8_t loose_state_transition_table[31][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-7,-1,-1,-1,-7, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /*30*/ {30,-1,30,30,30,30,-10,30,-4,4,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30} }; /*</fb>*/ /** * These modes can be pushed on the PDA stack. */ enum class Mode { INVALID = 0, DONE = 1, KEY = 2, OBJECT = 3, ARRAY = 4 }; namespace { int dehexchar(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - ('A' - 10); if (c >= 'a' && c <= 'f') return c - ('a' - 10); return -1; } NEVER_INLINE static void tvDecRefRange(TypedValue* begin, TypedValue* end) { assertx(begin <= end); for (auto tv = begin; tv != end; ++tv) { tvDecRefGen(tv); } } /* * Parses a subset of JSON. Currently unsupported: * - Non-ASCII * - Character escape sequences * - Non-string array keys * - Arrays nested > 255 levels */ struct SimpleParser { static constexpr int kMaxArrayDepth = 255; /* * Returns buffer size in bytes needed to handle any input up to given length. */ static size_t BufferBytesForLength(int length) { return (length + 1) * sizeof(TypedValue) / 2; // Worst case: "[0,0,...,0]" } /* * Returns false for unsupported or malformed input (does not distinguish). */ static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); parser.skipSpace(); if (!ok || parser.p != inp + length) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; } private: SimpleParser(const char* input, int length, TypedValue* buffer, JSONContainerType container_type, bool is_tsimplejson) : p(input) , top(buffer) , array_depth(-kMaxArrayDepth) /* Start negative to simplify check. */ , container_type(container_type) , is_tsimplejson(is_tsimplejson) { assertx(input[length] == 0); // Parser relies on sentinel to avoid checks. } /* * Skip whitespace, then if next char is 'ch', consume it and return true, * otherwise let it be and return false. */ bool matchSeparator(char ch) { if (LIKELY(*p++ == ch)) return true; return matchSeparatorSlow(ch); } NEVER_INLINE bool matchSeparatorSlow(char ch) { --p; skipSpace(); if (LIKELY(*p++ == ch)) return true; --p; return false; } NEVER_INLINE void skipSpace() { while (isSpace(*p)) p++; } bool isSpace(char ch) const { return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\f'; } /* * Variant parser. * * JSON arrays don't permit leading 0's in numbers, so we have to thread that * context through here to parseNumber(). */ bool parseValue(bool array_elem = false) { auto const ch = *p++; if (ch == '{') return parseMixed(); else if (ch == '[') return parsePacked(); else if (ch == '\"') return parseString(); else if ((ch >= '0' && ch <= '9') || ch == '-') return parseNumber(ch, array_elem); else if (ch == 't') return parseRue(); else if (ch == 'f') return parseAlse(); else if (ch == 'n') return parseUll(); else if (isSpace(ch)) { skipSpace(); return parseValue(array_elem); } else return false; } bool parseRue() { if (*p++ != 'r') return false; if (*p++ != 'u') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = true; return true; } bool parseAlse() { if (*p++ != 'a') return false; if (*p++ != 'l') return false; if (*p++ != 's') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = false; return true; } bool parseUll() { if (*p++ != 'u') return false; if (*p++ != 'l') return false; if (*p++ != 'l') return false; top++->m_type = KindOfNull; return true; } bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } } bool parseRawString(int* len) { assertx(p[-1] == '"'); // SimpleParser only handles "-quoted strings *len = 0; auto const charTop = reinterpret_cast<signed char*>(top); for (signed char ch = *p++; ch != '\"'; ch = *p++) { charTop[(*len)++] = ch; // overwritten later if `ch == '\\'` if (ch < ' ') { // `ch < ' '` catches null and also non-ASCII (since signed char) return false; } else if (ch == '\\') { if (!handleBackslash(charTop[*len - 1])) return false; } } return true; } bool parseString() { int len; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); pushStringData(StringData::Make(start, len, CopyString)); return true; } bool parseMixedKey() { int len; int64_t num; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); auto const slice = folly::StringPiece(start, len); start[len] = '\0'; if (container_type != JSONContainerType::HACK_ARRAYS && container_type != JSONContainerType::LEGACY_HACK_ARRAYS && is_strictly_integer(start, len, num)) { pushInt64(num); } else if (auto const str = lookupStaticString(slice)) { auto const tv = top++; tv->m_type = KindOfPersistentString; tv->m_data.pstr = str; } else { pushStringData(StringData::Make(start, len, CopyString)); } return true; } bool parsePacked() { auto const fp = top; if (!matchSeparator(']')) { if (++array_depth >= 0) return false; do { if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator(']')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateVec() : PackedArray::MakeVecNatural(top - fp, fp); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyVecArray()->copy() : PackedArray::MakeVecNatural(top - fp, fp); ret->setLegacyArray(true); return ret; } if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { return top == fp ? ArrayData::CreateVArray() : PackedArray::MakeVArrayNatural(top - fp, fp); } assertx(container_type == JSONContainerType::DARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArrayNatural(top - fp, fp); }(); top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } bool parseMixed() { auto const fp = top; if (!matchSeparator('}')) { if (++array_depth >= 0) return false; do { if (!matchSeparator('\"')) return false; // Only support string keys. if (!parseMixedKey()) return false; // TODO(14491721): Precompute and save hash to avoid deref in MakeMixed. if (!matchSeparator(':')) return false; if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator('}')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateDict() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyDictArray()->copy() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); ret->setLegacyArray(true); return ret; } assertx(container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArray((top - fp) >> 1, fp)->asArrayData(); }(); // MixedArray::MakeMixed can return nullptr if there are duplicate keys if (!arr) return false; top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } /* * Parse remainder of number after initial character firstChar (maybe '-'). */ bool parseNumber(char firstChar, bool array_elem = false) { uint64_t x = 0; bool neg = false; const char* begin = p - 1; if (firstChar == '-') { neg = true; } else { x = firstChar - '0'; // first digit } // Parse maximal digit sequence into x (non-negative). while (*p >= '0' && *p <= '9') { x = (x * 10) + (*p - '0'); ++p; } if (*p == '.' || *p == 'e' || *p == 'E') { pushDouble(zend_strtod(begin, &p)); return true; } auto len = p - begin; // JSON arrays don't permit leading 0's in numbers. if (UNLIKELY(len > 1 && firstChar == '0' && array_elem)) { return false; } // Now 'x' is the usigned absolute value of a naively parsed integer, but // potentially overflowed mod 2^64. if (LIKELY(len < 19) || (len == 19 && firstChar <= '8')) { int64_t sx = x; pushInt64(neg ? -sx : sx); } else { parseBigInt(len); } return true; } /* * Assuming 'len' characters ('0'-'9', maybe prefix '-') have been read, * re-parse and push as an int64_t if possible, otherwise as a double. */ void parseBigInt(int len) { assertx(*p > '9' || *p < '0'); // Aleady read maximal digit sequence. errno = 0; const int64_t sx = strtoll(p - len, nullptr, 10); if (errno == ERANGE) { const double dval = zend_strtod(p - len, nullptr); assertx(dval == floor(dval)); pushDouble(dval); } else { pushInt64(sx); } } void pushDouble(double data) { auto const tv = top++; tv->m_type = KindOfDouble; tv->m_data.dbl = data; } void pushInt64(int64_t data) { auto const tv = top++; tv->m_type = KindOfInt64; tv->m_data.num = data; } void pushStringData(StringData* data) { auto const tv = top++; tv->m_type = KindOfString; tv->m_data.pstr = data; } void pushArrayData(ArrayData* data) { auto const tv = top++; tv->m_type = data->toDataType(); tv->m_data.parr = data; assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } const char* p; TypedValue* top; int array_depth; JSONContainerType container_type; bool is_tsimplejson; }; /* * String buffer wrapper that does NOT check its capacity in release mode. User * supplies the allocation and must ensure to never append past the end. */ struct UncheckedBuffer { void clear() { p = begin; } // Use given buffer with space for 'cap' chars, including '\0'. void setBuf(char* buf, size_t cap) { begin = p = buf; #ifndef NDEBUG end = begin + cap; #endif } void append(char c) { assertx(p < end); *p++ = c; } void shrinkBy(int decrease) { p -= decrease; assertx(p >= begin); } int size() { return p - begin; } // NUL-terminates the output before returning it, for backward-compatibility. char* data() { assertx(p < end); *p = 0; return begin; } String copy() { return String(data(), size(), CopyString); } char* p{nullptr}; char* begin{nullptr}; #ifndef NDEBUG char* end{nullptr}; #endif }; } /** * A stack maintains the states of nested structures. */ struct json_parser { struct json_state { Mode mode; String key; Variant val; }; folly::fbvector<json_state> stack; // check_non_safepoint_surprise() above will not trigger gc TYPE_SCAN_IGNORE_FIELD(stack); int top; int mark; // the watermark int depth; json_error_codes error_code; // Thread-local buffer; reused on each call. JSON parsing cannot lead to code // execution and is not re-entrant. SimpleParser assumes no surprise checks. union { TypedValue* tv{nullptr}; // SimpleParser's stack. char* raw; // sb_buf/key } tl_buffer; TYPE_SCAN_IGNORE_FIELD(tv); UncheckedBuffer sb_buf; UncheckedBuffer sb_key; int sb_cap{0}; // Capacity of each of sb_buf/key. void initSb(int length) { if (UNLIKELY(length >= sb_cap)) { // No decoded string in the output can use more bytes than input size. const auto new_cap = length + 1; size_t bufSize = length <= RuntimeOption::EvalSimpleJsonMaxLength ? SimpleParser::BufferBytesForLength(length) : new_cap * 2; if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; if (!tl_heap->preAllocOOM(bufSize)) { tl_buffer.raw = (char*)json_malloc(bufSize); if (!tl_buffer.raw) tl_heap->forceOOM(); } check_non_safepoint_surprise(); always_assert(tl_buffer.raw); sb_buf.setBuf(tl_buffer.raw, new_cap); sb_key.setBuf(tl_buffer.raw + new_cap, new_cap); // Set new capacity if and ony if allocations succeed. sb_cap = new_cap; } else { sb_buf.clear(); sb_key.clear(); } } void flushSb() { if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; sb_buf.setBuf(nullptr, 0); sb_key.setBuf(nullptr, 0); } private: static void* json_malloc(size_t size) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_malloc(size); } else { return malloc(size); } } static void json_free(void* ptr) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_free(ptr); } else { return free(ptr); } } }; RDS_LOCAL(json_parser, s_json_parser); // In Zend, the json_parser struct is publicly // accessible. Thus the fields could be accessed // directly. Just using setter/accessor functions // to get around that. json_error_codes json_get_last_error_code() { return s_json_parser->error_code; } void json_set_last_error_code(json_error_codes ec) { s_json_parser->error_code = ec; } const char *json_get_last_error_msg() { switch (s_json_parser->error_code) { case JSON_ERROR_NONE: return "No error"; case JSON_ERROR_DEPTH: return "Maximum stack depth exceeded"; case JSON_ERROR_STATE_MISMATCH: return "State mismatch (invalid or malformed JSON)"; case JSON_ERROR_CTRL_CHAR: return "Control character error, possibly incorrectly encoded"; case JSON_ERROR_SYNTAX: return "Syntax error"; case JSON_ERROR_UTF8: return "Malformed UTF-8 characters, possibly incorrectly encoded"; case json_error_codes::JSON_ERROR_RECURSION: return "Recursion detected"; case json_error_codes::JSON_ERROR_INF_OR_NAN: return "Inf and NaN cannot be JSON encoded"; case json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE: return "Type is not supported"; default: return "Unknown error"; } } // For each request, make sure we start with the default error code. void json_parser_init() { s_json_parser->error_code = JSON_ERROR_NONE; } void json_parser_flush_caches() { s_json_parser->flushSb(); } /** * Push a mode onto the stack. Return false if there is overflow. */ static int push(json_parser *json, Mode mode) { if (json->top + 1 >= json->depth) { return false; } json->top += 1; json->stack[json->top].mode = mode; if (json->top > json->mark) { json->mark = json->top; } return true; } /** * Pop the stack, assuring that the current mode matches the expectation. * Return false if there is underflow or if the modes mismatch. */ static int pop(json_parser *json, Mode mode) { if (json->top < 0 || json->stack[json->top].mode != mode) { return false; } json->stack[json->top].mode = Mode::INVALID; json->top -= 1; return true; } static String copy_and_clear(UncheckedBuffer &buf) { auto ret = buf.size() > 0 ? buf.copy() : empty_string(); buf.clear(); return ret; } static Variant to_double(UncheckedBuffer &buf) { auto data = buf.data(); auto ret = data ? zend_strtod(data, nullptr) : 0.0; buf.clear(); return ret; } static void json_create_zval(Variant &z, UncheckedBuffer &buf, DataType type, int64_t options) { switch (type) { case KindOfBoolean: z = (buf.data() && (*buf.data() == 't')); return; case KindOfInt64: { bool bigint = false; const char *p = buf.data(); assertx(p); if (p == NULL) { z = int64_t(0); return; } bool neg = *buf.data() == '-'; int len = buf.size(); if (neg) len--; if (len >= MAX_LENGTH_OF_LONG - 1) { if (len == MAX_LENGTH_OF_LONG - 1) { int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits); if (!(cmp < 0 || (cmp == 0 && neg))) { bigint = true; } } else { bigint = true; } } if (bigint) { if (!(options & k_JSON_BIGINT_AS_STRING)) { // See KindOfDouble (below) z = to_double(buf); } else { z = copy_and_clear(buf); } } else { z = fast_strtoll_base10(buf.data()); } return; } case KindOfDouble: // Use zend_strtod() instead of strtod() here since JSON specifies using // a '.' for decimal separators regardless of locale. z = to_double(buf); return; case KindOfString: z = copy_and_clear(buf); return; case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfPersistentArray: case KindOfArray: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfObject: case KindOfResource: case KindOfFunc: case KindOfClass: case KindOfClsMeth: case KindOfRecord: z = uninit_null(); return; } not_reached(); } NEVER_INLINE void utf16_to_utf8_tail(UncheckedBuffer &buf, unsigned short utf16) { if (utf16 < 0x800) { buf.append((char)(0xc0 | (utf16 >> 6))); buf.append((char)(0x80 | (utf16 & 0x3f))); } else if ((utf16 & 0xfc00) == 0xdc00 && buf.size() >= 3 && ((unsigned char)buf.data()[buf.size() - 3]) == 0xed && ((unsigned char)buf.data()[buf.size() - 2] & 0xf0) == 0xa0 && ((unsigned char)buf.data()[buf.size() - 1] & 0xc0) == 0x80) { /* found surrogate pair */ unsigned long utf32; utf32 = (((buf.data()[buf.size() - 2] & 0xf) << 16) | ((buf.data()[buf.size() - 1] & 0x3f) << 10) | (utf16 & 0x3ff)) + 0x10000; buf.shrinkBy(3); buf.append((char)(0xf0 | (utf32 >> 18))); buf.append((char)(0x80 | ((utf32 >> 12) & 0x3f))); buf.append((char)(0x80 | ((utf32 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf32 & 0x3f))); } else { buf.append((char)(0xe0 | (utf16 >> 12))); buf.append((char)(0x80 | ((utf16 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf16 & 0x3f))); } } ALWAYS_INLINE void utf16_to_utf8(UncheckedBuffer &buf, unsigned short utf16) { if (LIKELY(utf16 < 0x80)) { buf.append((char)utf16); return; } return utf16_to_utf8_tail(buf, utf16); } StaticString s__empty_("_empty_"); static void object_set(const json_parser* json, Variant &var, const String& key, const Variant& value, int assoc, JSONContainerType container_type) { if (!assoc) { // We know it is stdClass, and everything is public (and dynamic). if (key.empty()) { var.getObjectData()->setProp(nullptr, s__empty_.get(), *value.asTypedValue()); } else { var.getObjectData()->o_set(key, value); } } else { if (container_type == JSONContainerType::COLLECTIONS) { auto keyTV = make_tv<KindOfString>(key.get()); collections::set(var.getObjectData(), &keyTV, value.asTypedValue()); } else if (container_type == JSONContainerType::HACK_ARRAYS || container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { forceToDict(var).set(key, value); } else { int64_t i; if (key.get()->isStrictlyInteger(i)) { forceToDArray(var).set(i, value); } else { forceToDArray(var).set(key, value); } } if (var.isArray()) { DEBUG_ONLY auto const data = var.getArrayData(); assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } } } static void attach_zval(json_parser *json, const String& key, int assoc, JSONContainerType container_type) { if (json->top < 1) { return; } auto& root = json->stack[json->top - 1].val; auto& child = json->stack[json->top].val; auto up_mode = json->stack[json->top - 1].mode; if (up_mode == Mode::ARRAY) { if (container_type == JSONContainerType::COLLECTIONS) { collections::append(root.getObjectData(), child.asTypedValue()); } else { root.asArrRef().append(child); } } else if (up_mode == Mode::OBJECT) { object_set(json, root, key, child, assoc, container_type); } } JSONContainerType get_container_type_from_options(int64_t options) { if ((options & k_JSON_FB_STABLE_MAPS) || (options & k_JSON_FB_COLLECTIONS)) { return JSONContainerType::COLLECTIONS; } if (options & k_JSON_FB_HACK_ARRAYS) { return JSONContainerType::HACK_ARRAYS; } if (options & k_JSON_FB_DARRAYS) { return JSONContainerType::DARRAYS; } if (options & k_JSON_FB_DARRAYS_AND_VARRAYS) { return JSONContainerType::DARRAYS_AND_VARRAYS; } if (options & k_JSON_FB_LEGACY_HACK_ARRAYS) { return JSONContainerType::LEGACY_HACK_ARRAYS; } return JSONContainerType::DARRAYS; } /** * The JSON_parser takes a UTF-8 encoded string and determines if it is a * syntactically correct JSON text. Along the way, it creates a PHP variable. * * It is implemented as a Pushdown Automaton; that means it is a finite state * machine with a stack. * * The behavior is as follows: * Container Type | is_assoc | JSON input => output type * * COLLECTIONS | true | "{}" => c_Map * COLLECTIONS | false | "{}" => c_Map * COLLECTIONS | true | "[]" => c_Vector * COLLECTIONS | false | "[]" => c_Vector * * HACK_ARRAYS | true | "{}" => dict * HACK_ARRAYS | false | "{}" => stdClass * HACK_ARRAYS | true | "[]" => vec * HACK_ARRAYS | false | "[]" => stdClass * * DARRAYS | true | "{}" => darray * DARRAYS | false | "{}" => stdClass * DARRAYS | true | "[]" => darray * DARRAYS | false | "[]" => stdClass * * DARRAYS_AND_VARRAYS | true | "{}" => darray * DARRAYS_AND_VARRAYS | false | "{}" => stdClass * DARRAYS_AND_VARRAYS | true | "[]" => varray * DARRAYS_AND_VARRAYS | false | "[]" => stdClass */ bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } #endif /* HAVE_JSONC */
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_4252_0
crossvul-cpp_data_good_4252_0
/* JSON_parser.c */ /* 2005-12-30 */ /* Copyright (c) 2005 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // If we have json-c then don't use this library since that one has a more // permissive licence #ifndef HAVE_JSONC #include "hphp/runtime/ext/json/JSON_parser.h" #include <folly/FBVector.h> #include "hphp/runtime/base/array-provenance.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/collections.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-info.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/base/init-fini-node.h" #include "hphp/runtime/base/utf8-decode.h" #include "hphp/runtime/ext/json/ext_json.h" #include "hphp/runtime/ext/collections/ext_collections-map.h" #include "hphp/runtime/ext/collections/ext_collections-vector.h" #include "hphp/system/systemlib.h" #include "hphp/util/fast_strtoll_base10.h" #include "hphp/zend/zend-strtod.h" #define MAX_LENGTH_OF_LONG 20 static const char long_min_digits[] = "9223372036854775808"; namespace HPHP { /* Characters are mapped into these 32 symbol classes. This allows for significant reductions in the size of the state transition table. */ /* error */ #define S_ERR -1 /* space */ #define S_SPA 0 /* other whitespace */ #define S_WSP 1 /* { */ #define S_LBE 2 /* } */ #define S_RBE 3 /* [ */ #define S_LBT 4 /* ] */ #define S_RBT 5 /* : */ #define S_COL 6 /* , */ #define S_COM 7 /* " */ #define S_QUO 8 /* \ */ #define S_BAC 9 /* / */ #define S_SLA 10 /* + */ #define S_PLU 11 /* - */ #define S_MIN 12 /* . */ #define S_DOT 13 /* 0 */ #define S_ZER 14 /* 123456789 */ #define S_DIG 15 /* a */ #define S__A_ 16 /* b */ #define S__B_ 17 /* c */ #define S__C_ 18 /* d */ #define S__D_ 19 /* e */ #define S__E_ 20 /* f */ #define S__F_ 21 /* l */ #define S__L_ 22 /* n */ #define S__N_ 23 /* r */ #define S__R_ 24 /* s */ #define S__S_ 25 /* t */ #define S__T_ 26 /* u */ #define S__U_ 27 /* ABCDF */ #define S_A_F 28 /* E */ #define S_E 29 /* everything else */ #define S_ETC 30 /* This table maps the 128 ASCII characters into the 32 character classes. The remaining Unicode characters should be mapped to S_ETC. */ alignas(64) static const int8_t ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*<fb>*/ alignas(64) static const int8_t loose_ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*</fb>*/ /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. A new state is a number between 0 and 29. An action is a negative number between -1 and -9. A JSON text is accepted if the end of the text is in state 9 and mode is Mode::DONE. */ alignas(64) static const int8_t state_transition_table[30][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} }; /*<fb>*/ /* Alternate "loose" transition table to support unquoted keys. Note: State 3 has same outgoing transitions in both transition tables. This is used below in the fast-case for appending simple characters (3 -> 3). */ alignas(64) static const int8_t loose_state_transition_table[31][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-7,-1,-1,-1,-7, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /*30*/ {30,-1,30,30,30,30,-10,30,-4,4,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30} }; /*</fb>*/ /** * These modes can be pushed on the PDA stack. */ enum class Mode { INVALID = 0, DONE = 1, KEY = 2, OBJECT = 3, ARRAY = 4 }; namespace { int dehexchar(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - ('A' - 10); if (c >= 'a' && c <= 'f') return c - ('a' - 10); return -1; } NEVER_INLINE static void tvDecRefRange(TypedValue* begin, TypedValue* end) { assertx(begin <= end); for (auto tv = begin; tv != end; ++tv) { tvDecRefGen(tv); } } /* * Parses a subset of JSON. Currently unsupported: * - Non-ASCII * - Character escape sequences * - Non-string array keys * - Arrays nested > 255 levels */ struct SimpleParser { static constexpr int kMaxArrayDepth = 255; /* * Returns buffer size in bytes needed to handle any input up to given length. */ static size_t BufferBytesForLength(int length) { return (length + 1) * sizeof(TypedValue) / 2; // Worst case: "[0,0,...,0]" } /* * Returns false for unsupported or malformed input (does not distinguish). */ static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); parser.skipSpace(); if (!ok || parser.p != inp + length) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; } private: SimpleParser(const char* input, int length, TypedValue* buffer, JSONContainerType container_type, bool is_tsimplejson) : p(input) , top(buffer) , array_depth(-kMaxArrayDepth) /* Start negative to simplify check. */ , container_type(container_type) , is_tsimplejson(is_tsimplejson) { assertx(input[length] == 0); // Parser relies on sentinel to avoid checks. } /* * Skip whitespace, then if next char is 'ch', consume it and return true, * otherwise let it be and return false. */ bool matchSeparator(char ch) { if (LIKELY(*p++ == ch)) return true; return matchSeparatorSlow(ch); } NEVER_INLINE bool matchSeparatorSlow(char ch) { --p; skipSpace(); if (LIKELY(*p++ == ch)) return true; --p; return false; } NEVER_INLINE void skipSpace() { while (isSpace(*p)) p++; } bool isSpace(char ch) const { return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\f'; } /* * Variant parser. * * JSON arrays don't permit leading 0's in numbers, so we have to thread that * context through here to parseNumber(). */ bool parseValue(bool array_elem = false) { auto const ch = *p++; if (ch == '{') return parseMixed(); else if (ch == '[') return parsePacked(); else if (ch == '\"') return parseString(); else if ((ch >= '0' && ch <= '9') || ch == '-') return parseNumber(ch, array_elem); else if (ch == 't') return parseRue(); else if (ch == 'f') return parseAlse(); else if (ch == 'n') return parseUll(); else if (isSpace(ch)) { skipSpace(); return parseValue(array_elem); } else return false; } bool parseRue() { if (*p++ != 'r') return false; if (*p++ != 'u') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = true; return true; } bool parseAlse() { if (*p++ != 'a') return false; if (*p++ != 'l') return false; if (*p++ != 's') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = false; return true; } bool parseUll() { if (*p++ != 'u') return false; if (*p++ != 'l') return false; if (*p++ != 'l') return false; top++->m_type = KindOfNull; return true; } bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } } bool parseRawString(int* len) { assertx(p[-1] == '"'); // SimpleParser only handles "-quoted strings *len = 0; auto const charTop = reinterpret_cast<signed char*>(top); for (signed char ch = *p++; ch != '\"'; ch = *p++) { charTop[(*len)++] = ch; // overwritten later if `ch == '\\'` if (ch < ' ') { // `ch < ' '` catches null and also non-ASCII (since signed char) return false; } else if (ch == '\\') { if (!handleBackslash(charTop[*len - 1])) return false; } } return true; } bool parseString() { int len; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); pushStringData(StringData::Make(start, len, CopyString)); return true; } bool parseMixedKey() { int len; int64_t num; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); auto const slice = folly::StringPiece(start, len); start[len] = '\0'; if (container_type != JSONContainerType::HACK_ARRAYS && container_type != JSONContainerType::LEGACY_HACK_ARRAYS && is_strictly_integer(start, len, num)) { pushInt64(num); } else if (auto const str = lookupStaticString(slice)) { auto const tv = top++; tv->m_type = KindOfPersistentString; tv->m_data.pstr = str; } else { pushStringData(StringData::Make(start, len, CopyString)); } return true; } bool parsePacked() { auto const fp = top; if (!matchSeparator(']')) { if (++array_depth >= 0) return false; do { if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator(']')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateVec() : PackedArray::MakeVecNatural(top - fp, fp); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyVecArray()->copy() : PackedArray::MakeVecNatural(top - fp, fp); ret->setLegacyArray(true); return ret; } if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { return top == fp ? ArrayData::CreateVArray() : PackedArray::MakeVArrayNatural(top - fp, fp); } assertx(container_type == JSONContainerType::DARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArrayNatural(top - fp, fp); }(); top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } bool parseMixed() { auto const fp = top; if (!matchSeparator('}')) { if (++array_depth >= 0) return false; do { if (!matchSeparator('\"')) return false; // Only support string keys. if (!parseMixedKey()) return false; // TODO(14491721): Precompute and save hash to avoid deref in MakeMixed. if (!matchSeparator(':')) return false; if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator('}')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateDict() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyDictArray()->copy() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); ret->setLegacyArray(true); return ret; } assertx(container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArray((top - fp) >> 1, fp)->asArrayData(); }(); // MixedArray::MakeMixed can return nullptr if there are duplicate keys if (!arr) return false; top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } /* * Parse remainder of number after initial character firstChar (maybe '-'). */ bool parseNumber(char firstChar, bool array_elem = false) { uint64_t x = 0; bool neg = false; const char* begin = p - 1; if (firstChar == '-') { neg = true; } else { x = firstChar - '0'; // first digit } // Parse maximal digit sequence into x (non-negative). while (*p >= '0' && *p <= '9') { x = (x * 10) + (*p - '0'); ++p; } if (*p == '.' || *p == 'e' || *p == 'E') { pushDouble(zend_strtod(begin, &p)); return true; } auto len = p - begin; // JSON arrays don't permit leading 0's in numbers. if (UNLIKELY(len > 1 && firstChar == '0' && array_elem)) { return false; } // Now 'x' is the usigned absolute value of a naively parsed integer, but // potentially overflowed mod 2^64. if (LIKELY(len < 19) || (len == 19 && firstChar <= '8')) { int64_t sx = x; pushInt64(neg ? -sx : sx); } else { parseBigInt(len); } return true; } /* * Assuming 'len' characters ('0'-'9', maybe prefix '-') have been read, * re-parse and push as an int64_t if possible, otherwise as a double. */ void parseBigInt(int len) { assertx(*p > '9' || *p < '0'); // Aleady read maximal digit sequence. errno = 0; const int64_t sx = strtoll(p - len, nullptr, 10); if (errno == ERANGE) { const double dval = zend_strtod(p - len, nullptr); assertx(dval == floor(dval)); pushDouble(dval); } else { pushInt64(sx); } } void pushDouble(double data) { auto const tv = top++; tv->m_type = KindOfDouble; tv->m_data.dbl = data; } void pushInt64(int64_t data) { auto const tv = top++; tv->m_type = KindOfInt64; tv->m_data.num = data; } void pushStringData(StringData* data) { auto const tv = top++; tv->m_type = KindOfString; tv->m_data.pstr = data; } void pushArrayData(ArrayData* data) { auto const tv = top++; tv->m_type = data->toDataType(); tv->m_data.parr = data; assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } const char* p; TypedValue* top; int array_depth; JSONContainerType container_type; bool is_tsimplejson; }; /* * String buffer wrapper that does NOT check its capacity in release mode. User * supplies the allocation and must ensure to never append past the end. */ struct UncheckedBuffer { void clear() { p = begin; } // Use given buffer with space for 'cap' chars, including '\0'. void setBuf(char* buf, size_t cap) { begin = p = buf; #ifndef NDEBUG end = begin + cap; #endif } void append(char c) { assertx(p < end); *p++ = c; } void shrinkBy(int decrease) { p -= decrease; assertx(p >= begin); } int size() { return p - begin; } // NUL-terminates the output before returning it, for backward-compatibility. char* data() { assertx(p < end); *p = 0; return begin; } String copy() { return String(data(), size(), CopyString); } char* p{nullptr}; char* begin{nullptr}; #ifndef NDEBUG char* end{nullptr}; #endif }; } /** * A stack maintains the states of nested structures. */ struct json_parser { struct json_state { Mode mode; String key; Variant val; }; folly::fbvector<json_state> stack; // check_non_safepoint_surprise() above will not trigger gc TYPE_SCAN_IGNORE_FIELD(stack); int top; int mark; // the watermark int depth; json_error_codes error_code; // Thread-local buffer; reused on each call. JSON parsing cannot lead to code // execution and is not re-entrant. SimpleParser assumes no surprise checks. union { TypedValue* tv{nullptr}; // SimpleParser's stack. char* raw; // sb_buf/key } tl_buffer; TYPE_SCAN_IGNORE_FIELD(tv); UncheckedBuffer sb_buf; UncheckedBuffer sb_key; int sb_cap{0}; // Capacity of each of sb_buf/key. void initSb(int length) { if (UNLIKELY(length >= sb_cap)) { // No decoded string in the output can use more bytes than input size. const auto new_cap = length + 1; size_t bufSize = length <= RuntimeOption::EvalSimpleJsonMaxLength ? SimpleParser::BufferBytesForLength(length) : new_cap * 2; if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; if (!tl_heap->preAllocOOM(bufSize)) { tl_buffer.raw = (char*)json_malloc(bufSize); if (!tl_buffer.raw) tl_heap->forceOOM(); } check_non_safepoint_surprise(); always_assert(tl_buffer.raw); sb_buf.setBuf(tl_buffer.raw, new_cap); sb_key.setBuf(tl_buffer.raw + new_cap, new_cap); // Set new capacity if and ony if allocations succeed. sb_cap = new_cap; } else { sb_buf.clear(); sb_key.clear(); } } void flushSb() { if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; sb_buf.setBuf(nullptr, 0); sb_key.setBuf(nullptr, 0); } private: static void* json_malloc(size_t size) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_malloc(size); } else { return malloc(size); } } static void json_free(void* ptr) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_free(ptr); } else { return free(ptr); } } }; RDS_LOCAL(json_parser, s_json_parser); // In Zend, the json_parser struct is publicly // accessible. Thus the fields could be accessed // directly. Just using setter/accessor functions // to get around that. json_error_codes json_get_last_error_code() { return s_json_parser->error_code; } void json_set_last_error_code(json_error_codes ec) { s_json_parser->error_code = ec; } const char *json_get_last_error_msg() { switch (s_json_parser->error_code) { case JSON_ERROR_NONE: return "No error"; case JSON_ERROR_DEPTH: return "Maximum stack depth exceeded"; case JSON_ERROR_STATE_MISMATCH: return "State mismatch (invalid or malformed JSON)"; case JSON_ERROR_CTRL_CHAR: return "Control character error, possibly incorrectly encoded"; case JSON_ERROR_SYNTAX: return "Syntax error"; case JSON_ERROR_UTF8: return "Malformed UTF-8 characters, possibly incorrectly encoded"; case json_error_codes::JSON_ERROR_RECURSION: return "Recursion detected"; case json_error_codes::JSON_ERROR_INF_OR_NAN: return "Inf and NaN cannot be JSON encoded"; case json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE: return "Type is not supported"; default: return "Unknown error"; } } // For each request, make sure we start with the default error code. void json_parser_init() { s_json_parser->error_code = JSON_ERROR_NONE; } void json_parser_flush_caches() { s_json_parser->flushSb(); } /** * Push a mode onto the stack. Return false if there is overflow. */ static int push(json_parser *json, Mode mode) { if (json->top + 1 >= json->depth) { return false; } json->top += 1; json->stack[json->top].mode = mode; if (json->top > json->mark) { json->mark = json->top; } return true; } /** * Pop the stack, assuring that the current mode matches the expectation. * Return false if there is underflow or if the modes mismatch. */ static int pop(json_parser *json, Mode mode) { if (json->top < 0 || json->stack[json->top].mode != mode) { return false; } json->stack[json->top].mode = Mode::INVALID; json->top -= 1; return true; } static String copy_and_clear(UncheckedBuffer &buf) { auto ret = buf.size() > 0 ? buf.copy() : empty_string(); buf.clear(); return ret; } static Variant to_double(UncheckedBuffer &buf) { auto data = buf.data(); auto ret = data ? zend_strtod(data, nullptr) : 0.0; buf.clear(); return ret; } static void json_create_zval(Variant &z, UncheckedBuffer &buf, DataType type, int64_t options) { switch (type) { case KindOfBoolean: z = (buf.data() && (*buf.data() == 't')); return; case KindOfInt64: { bool bigint = false; const char *p = buf.data(); assertx(p); if (p == NULL) { z = int64_t(0); return; } bool neg = *buf.data() == '-'; int len = buf.size(); if (neg) len--; if (len >= MAX_LENGTH_OF_LONG - 1) { if (len == MAX_LENGTH_OF_LONG - 1) { int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits); if (!(cmp < 0 || (cmp == 0 && neg))) { bigint = true; } } else { bigint = true; } } if (bigint) { if (!(options & k_JSON_BIGINT_AS_STRING)) { // See KindOfDouble (below) z = to_double(buf); } else { z = copy_and_clear(buf); } } else { z = fast_strtoll_base10(buf.data()); } return; } case KindOfDouble: // Use zend_strtod() instead of strtod() here since JSON specifies using // a '.' for decimal separators regardless of locale. z = to_double(buf); return; case KindOfString: z = copy_and_clear(buf); return; case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfPersistentArray: case KindOfArray: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfObject: case KindOfResource: case KindOfFunc: case KindOfClass: case KindOfClsMeth: case KindOfRecord: z = uninit_null(); return; } not_reached(); } NEVER_INLINE void utf16_to_utf8_tail(UncheckedBuffer &buf, unsigned short utf16) { if (utf16 < 0x800) { buf.append((char)(0xc0 | (utf16 >> 6))); buf.append((char)(0x80 | (utf16 & 0x3f))); } else if ((utf16 & 0xfc00) == 0xdc00 && buf.size() >= 3 && ((unsigned char)buf.data()[buf.size() - 3]) == 0xed && ((unsigned char)buf.data()[buf.size() - 2] & 0xf0) == 0xa0 && ((unsigned char)buf.data()[buf.size() - 1] & 0xc0) == 0x80) { /* found surrogate pair */ unsigned long utf32; utf32 = (((buf.data()[buf.size() - 2] & 0xf) << 16) | ((buf.data()[buf.size() - 1] & 0x3f) << 10) | (utf16 & 0x3ff)) + 0x10000; buf.shrinkBy(3); buf.append((char)(0xf0 | (utf32 >> 18))); buf.append((char)(0x80 | ((utf32 >> 12) & 0x3f))); buf.append((char)(0x80 | ((utf32 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf32 & 0x3f))); } else { buf.append((char)(0xe0 | (utf16 >> 12))); buf.append((char)(0x80 | ((utf16 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf16 & 0x3f))); } } ALWAYS_INLINE void utf16_to_utf8(UncheckedBuffer &buf, unsigned short utf16) { if (LIKELY(utf16 < 0x80)) { buf.append((char)utf16); return; } return utf16_to_utf8_tail(buf, utf16); } StaticString s__empty_("_empty_"); static void object_set(const json_parser* json, Variant &var, const String& key, const Variant& value, int assoc, JSONContainerType container_type) { if (!assoc) { // We know it is stdClass, and everything is public (and dynamic). if (key.empty()) { var.getObjectData()->setProp(nullptr, s__empty_.get(), *value.asTypedValue()); } else { var.getObjectData()->o_set(key, value); } } else { if (container_type == JSONContainerType::COLLECTIONS) { auto keyTV = make_tv<KindOfString>(key.get()); collections::set(var.getObjectData(), &keyTV, value.asTypedValue()); } else if (container_type == JSONContainerType::HACK_ARRAYS || container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { forceToDict(var).set(key, value); } else { int64_t i; if (key.get()->isStrictlyInteger(i)) { forceToDArray(var).set(i, value); } else { forceToDArray(var).set(key, value); } } if (var.isArray()) { DEBUG_ONLY auto const data = var.getArrayData(); assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } } } static void attach_zval(json_parser *json, const String& key, int assoc, JSONContainerType container_type) { if (json->top < 1) { return; } auto& root = json->stack[json->top - 1].val; auto& child = json->stack[json->top].val; auto up_mode = json->stack[json->top - 1].mode; if (up_mode == Mode::ARRAY) { if (container_type == JSONContainerType::COLLECTIONS) { collections::append(root.getObjectData(), child.asTypedValue()); } else { root.asArrRef().append(child); } } else if (up_mode == Mode::OBJECT) { object_set(json, root, key, child, assoc, container_type); } } JSONContainerType get_container_type_from_options(int64_t options) { if ((options & k_JSON_FB_STABLE_MAPS) || (options & k_JSON_FB_COLLECTIONS)) { return JSONContainerType::COLLECTIONS; } if (options & k_JSON_FB_HACK_ARRAYS) { return JSONContainerType::HACK_ARRAYS; } if (options & k_JSON_FB_DARRAYS) { return JSONContainerType::DARRAYS; } if (options & k_JSON_FB_DARRAYS_AND_VARRAYS) { return JSONContainerType::DARRAYS_AND_VARRAYS; } if (options & k_JSON_FB_LEGACY_HACK_ARRAYS) { return JSONContainerType::LEGACY_HACK_ARRAYS; } return JSONContainerType::DARRAYS; } /** * The JSON_parser takes a UTF-8 encoded string and determines if it is a * syntactically correct JSON text. Along the way, it creates a PHP variable. * * It is implemented as a Pushdown Automaton; that means it is a finite state * machine with a stack. * * The behavior is as follows: * Container Type | is_assoc | JSON input => output type * * COLLECTIONS | true | "{}" => c_Map * COLLECTIONS | false | "{}" => c_Map * COLLECTIONS | true | "[]" => c_Vector * COLLECTIONS | false | "[]" => c_Vector * * HACK_ARRAYS | true | "{}" => dict * HACK_ARRAYS | false | "{}" => stdClass * HACK_ARRAYS | true | "[]" => vec * HACK_ARRAYS | false | "[]" => stdClass * * DARRAYS | true | "{}" => darray * DARRAYS | false | "{}" => stdClass * DARRAYS | true | "[]" => darray * DARRAYS | false | "[]" => stdClass * * DARRAYS_AND_VARRAYS | true | "{}" => darray * DARRAYS_AND_VARRAYS | false | "{}" => stdClass * DARRAYS_AND_VARRAYS | true | "[]" => varray * DARRAYS_AND_VARRAYS | false | "[]" => stdClass */ bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } #endif /* HAVE_JSONC */
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_4252_0
crossvul-cpp_data_bad_94_2
/* -*- C++ -*- * File: libraw_cxx.cpp * Copyright 2008-2018 LibRaw LLC (info@libraw.org) * Created: Sat Mar 8 , 2008 * * LibRaw C++ interface (implementation) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). */ #include <math.h> #include <errno.h> #include <float.h> #include <new> #include <exception> #include <sys/types.h> #include <sys/stat.h> #if !defined(_WIN32) && !defined(__MINGW32__) #include <netinet/in.h> #else #include <winsock2.h> #endif #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #ifdef USE_ZLIB #include <zlib.h> #endif #ifdef USE_RAWSPEED #include "../RawSpeed/rawspeed_xmldata.cpp" #include <RawSpeed/StdAfx.h> #include <RawSpeed/FileMap.h> #include <RawSpeed/RawParser.h> #include <RawSpeed/RawDecoder.h> #include <RawSpeed/CameraMetaData.h> #include <RawSpeed/ColorFilterArray.h> #endif #ifdef USE_DNGSDK #include "dng_host.h" #include "dng_negative.h" #include "dng_simple_image.h" #include "dng_info.h" #endif #include "libraw_fuji_compressed.cpp" #ifdef __cplusplus extern "C" { #endif void default_memory_callback(void *, const char *file, const char *where) { fprintf(stderr, "%s: Out of memory in %s\n", file ? file : "unknown file", where); } void default_data_callback(void *, const char *file, const int offset) { if (offset < 0) fprintf(stderr, "%s: Unexpected end of file\n", file ? file : "unknown file"); else fprintf(stderr, "%s: data corrupted at %d\n", file ? file : "unknown file", offset); } const char *libraw_strerror(int e) { enum LibRaw_errors errorcode = (LibRaw_errors)e; switch (errorcode) { case LIBRAW_SUCCESS: return "No error"; case LIBRAW_UNSPECIFIED_ERROR: return "Unspecified error"; case LIBRAW_FILE_UNSUPPORTED: return "Unsupported file format or not RAW file"; case LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE: return "Request for nonexisting image number"; case LIBRAW_OUT_OF_ORDER_CALL: return "Out of order call of libraw function"; case LIBRAW_NO_THUMBNAIL: return "No thumbnail in file"; case LIBRAW_UNSUPPORTED_THUMBNAIL: return "Unsupported thumbnail format"; case LIBRAW_INPUT_CLOSED: return "No input stream, or input stream closed"; case LIBRAW_UNSUFFICIENT_MEMORY: return "Unsufficient memory"; case LIBRAW_DATA_ERROR: return "Corrupted data or unexpected EOF"; case LIBRAW_IO_ERROR: return "Input/output error"; case LIBRAW_CANCELLED_BY_CALLBACK: return "Cancelled by user callback"; case LIBRAW_BAD_CROP: return "Bad crop box"; default: return "Unknown error code"; } } #ifdef __cplusplus } #endif #define Sigma_X3F 22 const double LibRaw_constants::xyz_rgb[3][3] = { {0.4124564, 0.3575761, 0.1804375}, {0.2126729, 0.7151522, 0.0721750}, {0.0193339, 0.1191920, 0.9503041}}; const float LibRaw_constants::d65_white[3] = {0.95047f, 1.0f, 1.08883f}; #define P1 imgdata.idata #define S imgdata.sizes #define O imgdata.params #define C imgdata.color #define T imgdata.thumbnail #define IO libraw_internal_data.internal_output_params #define ID libraw_internal_data.internal_data #define EXCEPTION_HANDLER(e) \ do \ { \ /* fprintf(stderr,"Exception %d caught\n",e);*/ \ switch (e) \ { \ case LIBRAW_EXCEPTION_ALLOC: \ recycle(); \ return LIBRAW_UNSUFFICIENT_MEMORY; \ case LIBRAW_EXCEPTION_DECODE_RAW: \ case LIBRAW_EXCEPTION_DECODE_JPEG: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_DECODE_JPEG2000: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_IO_EOF: \ case LIBRAW_EXCEPTION_IO_CORRUPT: \ recycle(); \ return LIBRAW_IO_ERROR; \ case LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK: \ recycle(); \ return LIBRAW_CANCELLED_BY_CALLBACK; \ case LIBRAW_EXCEPTION_BAD_CROP: \ recycle(); \ return LIBRAW_BAD_CROP; \ default: \ return LIBRAW_UNSPECIFIED_ERROR; \ } \ } while (0) const char *LibRaw::version() { return LIBRAW_VERSION_STR; } int LibRaw::versionNumber() { return LIBRAW_VERSION; } const char *LibRaw::strerror(int p) { return libraw_strerror(p); } unsigned LibRaw::capabilities() { unsigned ret = 0; #ifdef USE_RAWSPEED ret |= LIBRAW_CAPS_RAWSPEED; #endif #ifdef USE_DNGSDK ret |= LIBRAW_CAPS_DNGSDK; #endif return ret; } unsigned LibRaw::parse_custom_cameras(unsigned limit, libraw_custom_camera_t table[], char **list) { if (!list) return 0; unsigned index = 0; for (int i = 0; i < limit; i++) { if (!list[i]) break; if (strlen(list[i]) < 10) continue; char *string = (char *)malloc(strlen(list[i]) + 1); strcpy(string, list[i]); char *start = string; memset(&table[index], 0, sizeof(table[0])); for (int j = 0; start && j < 14; j++) { char *end = strchr(start, ','); if (end) { *end = 0; end++; } // move to next char while (isspace(*start) && *start) start++; // skip leading spaces? unsigned val = strtol(start, 0, 10); switch (j) { case 0: table[index].fsize = val; break; case 1: table[index].rw = val; break; case 2: table[index].rh = val; break; case 3: table[index].lm = val; break; case 4: table[index].tm = val; break; case 5: table[index].rm = val; break; case 6: table[index].bm = val; break; case 7: table[index].lf = val; break; case 8: table[index].cf = val; break; case 9: table[index].max = val; break; case 10: table[index].flags = val; break; case 11: strncpy(table[index].t_make, start, sizeof(table[index].t_make) - 1); break; case 12: strncpy(table[index].t_model, start, sizeof(table[index].t_model) - 1); break; case 13: table[index].offset = val; break; default: break; } start = end; } free(string); if (table[index].t_make[0]) index++; } return index; } void LibRaw::derror() { if (!libraw_internal_data.unpacker_data.data_error && libraw_internal_data.internal_data.input) { if (libraw_internal_data.internal_data.input->eof()) { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), -1); throw LIBRAW_EXCEPTION_IO_EOF; } else { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), libraw_internal_data.internal_data.input->tell()); // throw LIBRAW_EXCEPTION_IO_CORRUPT; } } libraw_internal_data.unpacker_data.data_error++; } void LibRaw::dcraw_clear_mem(libraw_processed_image_t *p) { if (p) ::free(p); } int LibRaw::is_sraw() { return load_raw == &LibRaw::canon_sraw_load_raw || load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::is_coolscan_nef() { return load_raw == &LibRaw::nikon_coolscan_load_raw; } int LibRaw::is_jpeg_thumb() { return thumb_load_raw == 0 && write_thumb == &LibRaw::jpeg_thumb; } int LibRaw::is_nikon_sraw() { return load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::sraw_midpoint() { if (load_raw == &LibRaw::canon_sraw_load_raw) return 8192; else if (load_raw == &LibRaw::nikon_load_sraw) return 2048; else return 0; } #ifdef USE_RAWSPEED using namespace RawSpeed; class CameraMetaDataLR : public CameraMetaData { public: CameraMetaDataLR() : CameraMetaData() {} CameraMetaDataLR(char *filename) : CameraMetaData(filename) {} CameraMetaDataLR(char *data, int sz); }; CameraMetaDataLR::CameraMetaDataLR(char *data, int sz) : CameraMetaData() { ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { ThrowCME("CameraMetaData:Could not initialize context."); } xmlResetLastError(); doc = xmlCtxtReadMemory(ctxt, data, sz, "", NULL, XML_PARSE_DTDVALID); if (doc == NULL) { ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s", ctxt->lastError.message); } if (ctxt->valid == 0) { if (ctxt->lastError.code == 0x5e) { // printf("CameraMetaData: Unable to locate DTD, attempting to ignore."); } else { ThrowCME("CameraMetaData: XML file does not validate. DTD Error was: %s", ctxt->lastError.message); } } xmlNodePtr cur; cur = xmlDocGetRootElement(doc); if (xmlStrcmp(cur->name, (const xmlChar *)"Cameras")) { ThrowCME("CameraMetaData: XML document of the wrong type, root node is not cameras."); return; } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"Camera"))) { Camera *camera = new Camera(doc, cur); addCamera(camera); // Create cameras for aliases. for (unsigned int i = 0; i < camera->aliases.size(); i++) { addCamera(new Camera(camera, i)); } } cur = cur->next; } if (doc) xmlFreeDoc(doc); doc = 0; if (ctxt) xmlFreeParserCtxt(ctxt); ctxt = 0; } #define RAWSPEED_DATA_COUNT (sizeof(_rawspeed_data_xml) / sizeof(_rawspeed_data_xml[0])) static CameraMetaDataLR *make_camera_metadata() { int len = 0, i; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { len += strlen(_rawspeed_data_xml[i]); } char *rawspeed_xml = (char *)calloc(len + 1, sizeof(_rawspeed_data_xml[0][0])); if (!rawspeed_xml) return NULL; int offt = 0; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { int ll = strlen(_rawspeed_data_xml[i]); if (offt + ll > len) break; memmove(rawspeed_xml + offt, _rawspeed_data_xml[i], ll); offt += ll; } rawspeed_xml[offt] = 0; CameraMetaDataLR *ret = NULL; try { ret = new CameraMetaDataLR(rawspeed_xml, offt); } catch (...) { // Mask all exceptions } free(rawspeed_xml); return ret; } #endif #define ZERO(a) memset(&a, 0, sizeof(a)) static void cleargps(libraw_gps_info_t *q) { for (int i = 0; i < 3; i++) q->latitude[i] = q->longtitude[i] = q->gpstimestamp[i] = 0.f; q->altitude = 0.f; q->altref = q->latref = q->longref = q->gpsstatus = q->gpsparsed = 0; } LibRaw::LibRaw(unsigned int flags) : memmgr(1024) { double aber[4] = {1, 1, 1, 1}; double gamm[6] = {0.45, 4.5, 0, 0, 0, 0}; unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX}; unsigned cropbox[4] = {0, 0, UINT_MAX, UINT_MAX}; #ifdef DCRAW_VERBOSE verbose = 1; #else verbose = 0; #endif ZERO(imgdata); cleargps(&imgdata.other.parsed_gps); ZERO(libraw_internal_data); ZERO(callbacks); _rawspeed_camerameta = _rawspeed_decoder = NULL; dnghost = NULL; _x3f_data = NULL; #ifdef USE_RAWSPEED CameraMetaDataLR *camerameta = make_camera_metadata(); // May be NULL in case of exception in make_camera_metadata() _rawspeed_camerameta = static_cast<void *>(camerameta); #endif callbacks.mem_cb = (flags & LIBRAW_OPIONS_NO_MEMERR_CALLBACK) ? NULL : &default_memory_callback; callbacks.data_cb = (flags & LIBRAW_OPIONS_NO_DATAERR_CALLBACK) ? NULL : &default_data_callback; callbacks.exif_cb = NULL; // no default callback callbacks.pre_identify_cb = NULL; callbacks.post_identify_cb = NULL; callbacks.pre_subtractblack_cb = callbacks.pre_scalecolors_cb = callbacks.pre_preinterpolate_cb = callbacks.pre_interpolate_cb = callbacks.interpolate_bayer_cb = callbacks.interpolate_xtrans_cb = callbacks.post_interpolate_cb = callbacks.pre_converttorgb_cb = callbacks.post_converttorgb_cb = NULL; memmove(&imgdata.params.aber, &aber, sizeof(aber)); memmove(&imgdata.params.gamm, &gamm, sizeof(gamm)); memmove(&imgdata.params.greybox, &greybox, sizeof(greybox)); memmove(&imgdata.params.cropbox, &cropbox, sizeof(cropbox)); imgdata.params.bright = 1; imgdata.params.use_camera_matrix = 1; imgdata.params.user_flip = -1; imgdata.params.user_black = -1; imgdata.params.user_cblack[0] = imgdata.params.user_cblack[1] = imgdata.params.user_cblack[2] = imgdata.params.user_cblack[3] = -1000001; imgdata.params.user_sat = -1; imgdata.params.user_qual = -1; imgdata.params.output_color = 1; imgdata.params.output_bps = 8; imgdata.params.use_fuji_rotate = 1; imgdata.params.exp_shift = 1.0; imgdata.params.auto_bright_thr = LIBRAW_DEFAULT_AUTO_BRIGHTNESS_THRESHOLD; imgdata.params.adjust_maximum_thr = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; imgdata.params.use_rawspeed = 1; imgdata.params.use_dngsdk = LIBRAW_DNG_DEFAULT; imgdata.params.no_auto_scale = 0; imgdata.params.no_interpolation = 0; imgdata.params.raw_processing_options = LIBRAW_PROCESSING_DP2Q_INTERPOLATERG | LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF | LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT; imgdata.params.sony_arw2_posterization_thr = 0; imgdata.params.green_matching = 0; imgdata.params.custom_camera_strings = 0; imgdata.params.coolscan_nef_gamma = 1.0f; imgdata.parent_class = this; imgdata.progress_flags = 0; imgdata.color.baseline_exposure = -999.f; _exitflag = 0; tls = new LibRaw_TLS; tls->init(); } int LibRaw::set_rawspeed_camerafile(char *filename) { #ifdef USE_RAWSPEED try { CameraMetaDataLR *camerameta = new CameraMetaDataLR(filename); if (_rawspeed_camerameta) { CameraMetaDataLR *d = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete d; } _rawspeed_camerameta = static_cast<void *>(camerameta); } catch (...) { // just return error code return -1; } #endif return 0; } LibRaw::~LibRaw() { recycle(); delete tls; #ifdef USE_RAWSPEED if (_rawspeed_camerameta) { CameraMetaDataLR *cmeta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete cmeta; _rawspeed_camerameta = NULL; } #endif } void *LibRaw::malloc(size_t t) { void *p = memmgr.malloc(t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::realloc(void *q, size_t t) { void *p = memmgr.realloc(q, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::calloc(size_t n, size_t t) { void *p = memmgr.calloc(n, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void LibRaw::free(void *p) { memmgr.free(p); } void LibRaw::recycle_datastream() { if (libraw_internal_data.internal_data.input && libraw_internal_data.internal_data.input_internal) { delete libraw_internal_data.internal_data.input; libraw_internal_data.internal_data.input = NULL; } libraw_internal_data.internal_data.input_internal = 0; } void x3f_clear(void *); void LibRaw::recycle() { recycle_datastream(); #define FREE(a) \ do \ { \ if (a) \ { \ free(a); \ a = NULL; \ } \ } while (0) FREE(imgdata.image); FREE(imgdata.thumbnail.thumb); FREE(libraw_internal_data.internal_data.meta_data); FREE(libraw_internal_data.output_data.histogram); FREE(libraw_internal_data.output_data.oprof); FREE(imgdata.color.profile); FREE(imgdata.rawdata.ph1_cblack); FREE(imgdata.rawdata.ph1_rblack); FREE(imgdata.rawdata.raw_alloc); FREE(imgdata.idata.xmpdata); #undef FREE ZERO(imgdata.sizes); imgdata.sizes.raw_crop.cleft = 0xffff; imgdata.sizes.raw_crop.ctop = 0xffff; ZERO(imgdata.idata); ZERO(imgdata.makernotes); ZERO(imgdata.color); ZERO(imgdata.other); ZERO(imgdata.thumbnail); ZERO(imgdata.rawdata); imgdata.makernotes.olympus.OlympusCropID = -1; imgdata.makernotes.sony.raw_crop.cleft = 0xffff; imgdata.makernotes.sony.raw_crop.ctop = 0xffff; cleargps(&imgdata.other.parsed_gps); imgdata.color.baseline_exposure = -999.f; imgdata.makernotes.fuji.FujiExpoMidPointShift = -999.f; imgdata.makernotes.fuji.FujiDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiFilmMode = 0xffff; imgdata.makernotes.fuji.FujiDynamicRangeSetting = 0xffff; imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiAutoDynamicRange = 0xffff; imgdata.makernotes.fuji.FocusMode = 0xffff; imgdata.makernotes.fuji.AFMode = 0xffff; imgdata.makernotes.fuji.FocusPixel[0] = imgdata.makernotes.fuji.FocusPixel[1] = 0xffff; imgdata.makernotes.fuji.ImageStabilization[0] = imgdata.makernotes.fuji.ImageStabilization[1] = imgdata.makernotes.fuji.ImageStabilization[2] = 0xffff; imgdata.makernotes.sony.SonyCameraType = 0xffff; imgdata.makernotes.sony.real_iso_offset = 0xffff; imgdata.makernotes.sony.ImageCount3_offset = 0xffff; imgdata.makernotes.sony.ElectronicFrontCurtainShutter = 0xffff; imgdata.makernotes.kodak.BlackLevelTop = 0xffff; imgdata.makernotes.kodak.BlackLevelBottom = 0xffff; imgdata.color.dng_color[0].illuminant = imgdata.color.dng_color[1].illuminant = 0xffff; for (int i = 0; i < 4; i++) imgdata.color.dng_levels.analogbalance[i] = 1.0f; ZERO(libraw_internal_data); ZERO(imgdata.lens); imgdata.lens.makernotes.CanonFocalUnits = 1; imgdata.lens.makernotes.LensID = 0xffffffffffffffffULL; ZERO(imgdata.shootinginfo); imgdata.shootinginfo.DriveMode = -1; imgdata.shootinginfo.FocusMode = -1; imgdata.shootinginfo.MeteringMode = -1; imgdata.shootinginfo.AFPoint = -1; imgdata.shootinginfo.ExposureMode = -1; imgdata.shootinginfo.ImageStabilization = -1; _exitflag = 0; #ifdef USE_RAWSPEED if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); delete d; } _rawspeed_decoder = 0; #endif if (_x3f_data) { x3f_clear(_x3f_data); _x3f_data = 0; } memmgr.cleanup(); imgdata.thumbnail.tformat = LIBRAW_THUMBNAIL_UNKNOWN; imgdata.progress_flags = 0; load_raw = thumb_load_raw = 0; tls->init(); } const char *LibRaw::unpack_function_name() { libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); return decoder_info.decoder_name; } int LibRaw::get_decoder_info(libraw_decoder_info_t *d_info) { if (!d_info) return LIBRAW_UNSPECIFIED_ERROR; d_info->decoder_name = 0; d_info->decoder_flags = 0; if (!load_raw) return LIBRAW_OUT_OF_ORDER_CALL; int rawdata = (imgdata.idata.filters || P1.colors == 1); // dcraw.c names order if (load_raw == &LibRaw::android_tight_load_raw) { d_info->decoder_name = "android_tight_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::android_loose_load_raw) { d_info->decoder_name = "android_loose_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_600_load_raw) { d_info->decoder_name = "canon_600_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::fuji_compressed_load_raw) { d_info->decoder_name = "fuji_compressed_load_raw()"; } else if (load_raw == &LibRaw::fuji_14bit_load_raw) { d_info->decoder_name = "fuji_14bit_load_raw()"; } else if (load_raw == &LibRaw::canon_load_raw) { d_info->decoder_name = "canon_load_raw()"; } else if (load_raw == &LibRaw::lossless_jpeg_load_raw) { d_info->decoder_name = "lossless_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::canon_sraw_load_raw) { d_info->decoder_name = "canon_sraw_load_raw()"; // d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::lossless_dng_load_raw) { d_info->decoder_name = "lossless_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::packed_dng_load_raw) { d_info->decoder_name = "packed_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::pentax_load_raw) { d_info->decoder_name = "pentax_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_load_raw) { d_info->decoder_name = "nikon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_coolscan_load_raw) { d_info->decoder_name = "nikon_coolscan_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_load_sraw) { d_info->decoder_name = "nikon_load_sraw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_yuv_load_raw) { d_info->decoder_name = "nikon_load_yuv_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::rollei_load_raw) { // UNTESTED d_info->decoder_name = "rollei_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::phase_one_load_raw) { d_info->decoder_name = "phase_one_load_raw()"; } else if (load_raw == &LibRaw::phase_one_load_raw_c) { d_info->decoder_name = "phase_one_load_raw_c()"; } else if (load_raw == &LibRaw::hasselblad_load_raw) { d_info->decoder_name = "hasselblad_load_raw()"; } else if (load_raw == &LibRaw::leaf_hdr_load_raw) { d_info->decoder_name = "leaf_hdr_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw) { d_info->decoder_name = "unpacked_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw_reversed) { d_info->decoder_name = "unpacked_load_raw_reversed()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sinar_4shot_load_raw) { // UNTESTED d_info->decoder_name = "sinar_4shot_load_raw()"; } else if (load_raw == &LibRaw::imacon_full_load_raw) { d_info->decoder_name = "imacon_full_load_raw()"; } else if (load_raw == &LibRaw::hasselblad_full_load_raw) { d_info->decoder_name = "hasselblad_full_load_raw()"; } else if (load_raw == &LibRaw::packed_load_raw) { d_info->decoder_name = "packed_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::broadcom_load_raw) { // UNTESTED d_info->decoder_name = "broadcom_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nokia_load_raw) { // UNTESTED d_info->decoder_name = "nokia_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_rmf_load_raw) { // UNTESTED d_info->decoder_name = "canon_rmf_load_raw()"; } else if (load_raw == &LibRaw::panasonic_load_raw) { d_info->decoder_name = "panasonic_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::olympus_load_raw) { d_info->decoder_name = "olympus_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::minolta_rd175_load_raw) { // UNTESTED d_info->decoder_name = "minolta_rd175_load_raw()"; } else if (load_raw == &LibRaw::quicktake_100_load_raw) { // UNTESTED d_info->decoder_name = "quicktake_100_load_raw()"; } else if (load_raw == &LibRaw::kodak_radc_load_raw) { d_info->decoder_name = "kodak_radc_load_raw()"; } else if (load_raw == &LibRaw::kodak_jpeg_load_raw) { // UNTESTED + RBAYER d_info->decoder_name = "kodak_jpeg_load_raw()"; } else if (load_raw == &LibRaw::lossy_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossy_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_dc120_load_raw) { d_info->decoder_name = "kodak_dc120_load_raw()"; } else if (load_raw == &LibRaw::eight_bit_load_raw) { d_info->decoder_name = "eight_bit_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c330_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c603_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_262_load_raw) { d_info->decoder_name = "kodak_262_load_raw()"; // UNTESTED! d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_65000_load_raw) { d_info->decoder_name = "kodak_65000_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { // UNTESTED d_info->decoder_name = "kodak_ycbcr_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_rgb_load_raw) { // UNTESTED d_info->decoder_name = "kodak_rgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sony_load_raw) { d_info->decoder_name = "sony_load_raw()"; } else if (load_raw == &LibRaw::sony_arw_load_raw) { d_info->decoder_name = "sony_arw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::sony_arw2_load_raw) { d_info->decoder_name = "sony_arw2_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_SONYARW2; } else if (load_raw == &LibRaw::sony_arq_load_raw) { d_info->decoder_name = "sony_arq_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::samsung_load_raw) { d_info->decoder_name = "samsung_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::samsung2_load_raw) { d_info->decoder_name = "samsung2_load_raw()"; } else if (load_raw == &LibRaw::samsung3_load_raw) { d_info->decoder_name = "samsung3_load_raw()"; } else if (load_raw == &LibRaw::smal_v6_load_raw) { // UNTESTED d_info->decoder_name = "smal_v6_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::smal_v9_load_raw) { // UNTESTED d_info->decoder_name = "smal_v9_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::redcine_load_raw) { d_info->decoder_name = "redcine_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::x3f_load_raw) { d_info->decoder_name = "x3f_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC | LIBRAW_DECODER_FIXEDMAXC | LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::pentax_4shot_load_raw) { d_info->decoder_name = "pentax_4shot_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::deflate_dng_load_raw) { d_info->decoder_name = "deflate_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::nikon_load_striped_packed_raw) { d_info->decoder_name = "nikon_load_striped_packed_raw()"; } else { d_info->decoder_name = "Unknown unpack function"; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; } return LIBRAW_SUCCESS; } int LibRaw::adjust_maximum() { ushort real_max; float auto_threshold; if (O.adjust_maximum_thr < 0.00001) return LIBRAW_SUCCESS; else if (O.adjust_maximum_thr > 0.99999) auto_threshold = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; else auto_threshold = O.adjust_maximum_thr; real_max = C.data_maximum; if (real_max > 0 && real_max < C.maximum && real_max > C.maximum * auto_threshold) { C.maximum = real_max; } return LIBRAW_SUCCESS; } void LibRaw::merror(void *ptr, const char *where) { if (ptr) return; if (callbacks.mem_cb) (*callbacks.mem_cb)( callbacks.memcb_data, libraw_internal_data.internal_data.input ? libraw_internal_data.internal_data.input->fname() : NULL, where); throw LIBRAW_EXCEPTION_ALLOC; } int LibRaw::open_file(const char *fname, INT64 max_buf_size) { #ifndef WIN32 struct stat st; if (stat(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #else struct _stati64 st; if (_stati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #endif LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) int LibRaw::open_file(const wchar_t *fname, INT64 max_buf_size) { struct _stati64 st; if (_wstati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #endif int LibRaw::open_buffer(void *buffer, size_t size) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, size); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } int LibRaw::open_bayer(unsigned char *buffer, unsigned datalen, ushort _raw_width, ushort _raw_height, ushort _left_margin, ushort _top_margin, ushort _right_margin, ushort _bottom_margin, unsigned char procflags, unsigned char bayer_pattern, unsigned unused_bits, unsigned otherflags, unsigned black_level) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, datalen); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); // From identify initdata(); strcpy(imgdata.idata.make, "BayerDump"); snprintf(imgdata.idata.model, sizeof(imgdata.idata.model) - 1, "%u x %u pixels", _raw_width, _raw_height); S.flip = procflags >> 2; libraw_internal_data.internal_output_params.zero_is_bad = procflags & 2; libraw_internal_data.unpacker_data.data_offset = 0; S.raw_width = _raw_width; S.raw_height = _raw_height; S.left_margin = _left_margin; S.top_margin = _top_margin; S.width = S.raw_width - S.left_margin - _right_margin; S.height = S.raw_height - S.top_margin - _bottom_margin; imgdata.idata.filters = 0x1010101 * bayer_pattern; imgdata.idata.colors = 4 - !((imgdata.idata.filters & imgdata.idata.filters >> 1) & 0x5555); libraw_internal_data.unpacker_data.load_flags = otherflags; switch (libraw_internal_data.unpacker_data.tiff_bps = (datalen)*8 / (S.raw_width * S.raw_height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((datalen) / S.raw_height * 3 >= S.raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (libraw_internal_data.unpacker_data.load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: libraw_internal_data.unpacker_data.load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: libraw_internal_data.unpacker_data.order = 0x4949 | 0x404 * (libraw_internal_data.unpacker_data.load_flags & 1); libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags >> 4; libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags = libraw_internal_data.unpacker_data.load_flags >> 1 & 7; load_raw = &CLASS unpacked_load_raw; } C.maximum = (1 << libraw_internal_data.unpacker_data.tiff_bps) - (1 << unused_bits); C.black = black_level; S.iwidth = S.width; S.iheight = S.height; imgdata.idata.colors = 3; imgdata.idata.filters |= ((imgdata.idata.filters >> 2 & 0x22222222) | (imgdata.idata.filters << 2 & 0x88888888)) & imgdata.idata.filters << 1; imgdata.idata.raw_count = 1; for (int i = 0; i < 4; i++) imgdata.color.pre_mul[i] = 1.0; strcpy(imgdata.idata.cdesc, "RGBG"); ID.input_internal = 1; SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); return LIBRAW_SUCCESS; } #ifdef USE_ZLIB inline unsigned int __DNG_HalfToFloat(ushort halfValue) { int sign = (halfValue >> 15) & 0x00000001; int exponent = (halfValue >> 10) & 0x0000001f; int mantissa = halfValue & 0x000003ff; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00000400)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00000400; } } else if (exponent == 31) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x1eL + 127 - 15) << 23) | (0x3ffL << 13)); } else { return 0; } } exponent += (127 - 15); mantissa <<= 13; return (unsigned int)((sign << 31) | (exponent << 23) | mantissa); } inline unsigned int __DNG_FP24ToFloat(const unsigned char *input) { int sign = (input[0] >> 7) & 0x01; int exponent = (input[0]) & 0x7F; int mantissa = (((int)input[1]) << 8) | input[2]; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00010000)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00010000; } } else if (exponent == 127) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x7eL + 128 - 64) << 23) | (0xffffL << 7)); } else { // Nan -- Just set to zero. return 0; } } exponent += (128 - 64); mantissa <<= 7; return (uint32_t)((sign << 31) | (exponent << 23) | mantissa); } inline void DecodeDeltaBytes(unsigned char *bytePtr, int cols, int channels) { if (channels == 1) { unsigned char b0 = bytePtr[0]; bytePtr += 1; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; bytePtr[0] = b0; bytePtr += 1; } } else if (channels == 3) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; bytePtr += 3; for (int col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr += 3; } } else if (channels == 4) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; unsigned char b3 = bytePtr[3]; bytePtr += 4; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; b3 += bytePtr[3]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr[3] = b3; bytePtr += 4; } } else { for (int col = 1; col < cols; ++col) { for (int chan = 0; chan < channels; ++chan) { bytePtr[chan + channels] += bytePtr[chan]; } bytePtr += channels; } } } static void DecodeFPDelta(unsigned char *input, unsigned char *output, int cols, int channels, int bytesPerSample) { DecodeDeltaBytes(input, cols * bytesPerSample, channels); int32_t rowIncrement = cols * channels; if (bytesPerSample == 2) { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; #else const unsigned char *input1 = input; const unsigned char *input0 = input + rowIncrement; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output += 2; } } else if (bytesPerSample == 3) { const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output += 3; } } else { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; const unsigned char *input3 = input + rowIncrement * 3; #else const unsigned char *input3 = input; const unsigned char *input2 = input + rowIncrement; const unsigned char *input1 = input + rowIncrement * 2; const unsigned char *input0 = input + rowIncrement * 3; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output[3] = input3[col]; output += 4; } } } static float expandFloats(unsigned char *dst, int tileWidth, int bytesps) { float max = 0.f; if (bytesps == 2) { uint16_t *dst16 = (ushort *)dst; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index) { dst32[index] = __DNG_HalfToFloat(dst16[index]); max = MAX(max, f32[index]); } } else if (bytesps == 3) { uint8_t *dst8 = ((unsigned char *)dst) + (tileWidth - 1) * 3; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index, dst8 -= 3) { dst32[index] = __DNG_FP24ToFloat(dst8); max = MAX(max, f32[index]); } } else if (bytesps == 4) { float *f32 = (float *)dst; for (int index = 0; index < tileWidth; index++) max = MAX(max, f32[index]); } return max; } void LibRaw::deflate_dng_load_raw() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) { throw LIBRAW_EXCEPTION_DECODE_RAW; } float *float_raw_image = 0; float max = 0.f; if (ifd->samples != 1 && ifd->samples != 3 && ifd->samples != 4) throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported if (libraw_internal_data.unpacker_data.tiff_samples != ifd->samples) throw LIBRAW_EXCEPTION_DECODE_RAW; // Wrong IFD size_t tilesH = (imgdata.sizes.raw_width + libraw_internal_data.unpacker_data.tile_width - 1) / libraw_internal_data.unpacker_data.tile_width; size_t tilesV = (imgdata.sizes.raw_height + libraw_internal_data.unpacker_data.tile_length - 1) / libraw_internal_data.unpacker_data.tile_length; size_t tileCnt = tilesH * tilesV; if (ifd->sample_format == 3) { // Floating point data float_raw_image = (float *)calloc(tileCnt * libraw_internal_data.unpacker_data.tile_length * libraw_internal_data.unpacker_data.tile_width * ifd->samples, sizeof(float)); // imgdata.color.maximum = 65535; // imgdata.color.black = 0; // memset(imgdata.color.cblack,0,sizeof(imgdata.color.cblack)); } else throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported int xFactor; switch (ifd->predictor) { case 3: default: xFactor = 1; break; case 34894: xFactor = 2; break; case 34895: xFactor = 4; break; } if (libraw_internal_data.unpacker_data.tile_length < INT_MAX) { if (tileCnt < 1 || tileCnt > 1000000) throw LIBRAW_EXCEPTION_DECODE_RAW; size_t *tOffsets = (size_t *)malloc(tileCnt * sizeof(size_t)); for (int t = 0; t < tileCnt; ++t) tOffsets[t] = get4(); size_t *tBytes = (size_t *)malloc(tileCnt * sizeof(size_t)); unsigned long maxBytesInTile = 0; if (tileCnt == 1) tBytes[0] = maxBytesInTile = ifd->bytes; else { libraw_internal_data.internal_data.input->seek(ifd->bytes, SEEK_SET); for (size_t t = 0; t < tileCnt; ++t) { tBytes[t] = get4(); maxBytesInTile = MAX(maxBytesInTile, tBytes[t]); } } unsigned tilePixels = libraw_internal_data.unpacker_data.tile_width * libraw_internal_data.unpacker_data.tile_length; unsigned pixelSize = sizeof(float) * ifd->samples; unsigned tileBytes = tilePixels * pixelSize; unsigned tileRowBytes = libraw_internal_data.unpacker_data.tile_width * pixelSize; unsigned char *cBuffer = (unsigned char *)malloc(maxBytesInTile); unsigned char *uBuffer = (unsigned char *)malloc(tileBytes + tileRowBytes); // extra row for decoding for (size_t y = 0, t = 0; y < imgdata.sizes.raw_height; y += libraw_internal_data.unpacker_data.tile_length) { for (size_t x = 0; x < imgdata.sizes.raw_width; x += libraw_internal_data.unpacker_data.tile_width, ++t) { libraw_internal_data.internal_data.input->seek(tOffsets[t], SEEK_SET); libraw_internal_data.internal_data.input->read(cBuffer, 1, tBytes[t]); unsigned long dstLen = tileBytes; int err = uncompress(uBuffer + tileRowBytes, &dstLen, cBuffer, tBytes[t]); if (err != Z_OK) { free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); throw LIBRAW_EXCEPTION_DECODE_RAW; return; } else { int bytesps = ifd->bps >> 3; size_t rowsInTile = y + libraw_internal_data.unpacker_data.tile_length > imgdata.sizes.raw_height ? imgdata.sizes.raw_height - y : libraw_internal_data.unpacker_data.tile_length; size_t colsInTile = x + libraw_internal_data.unpacker_data.tile_width > imgdata.sizes.raw_width ? imgdata.sizes.raw_width - x : libraw_internal_data.unpacker_data.tile_width; for (size_t row = 0; row < rowsInTile; ++row) // do not process full tile if not needed { unsigned char *dst = uBuffer + row * libraw_internal_data.unpacker_data.tile_width * bytesps * ifd->samples; unsigned char *src = dst + tileRowBytes; DecodeFPDelta(src, dst, libraw_internal_data.unpacker_data.tile_width / xFactor, ifd->samples * xFactor, bytesps); float lmax = expandFloats(dst, libraw_internal_data.unpacker_data.tile_width * ifd->samples, bytesps); max = MAX(max, lmax); unsigned char *dst2 = (unsigned char *)&float_raw_image[((y + row) * imgdata.sizes.raw_width + x) * ifd->samples]; memmove(dst2, dst, colsInTile * ifd->samples * sizeof(float)); } } } } free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); } imgdata.color.fmaximum = max; // Set fields according to data format imgdata.rawdata.raw_alloc = float_raw_image; if (ifd->samples == 1) { imgdata.rawdata.float_image = float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 4; } else if (ifd->samples == 3) { imgdata.rawdata.float3_image = (float(*)[3])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 12; } else if (ifd->samples == 4) { imgdata.rawdata.float4_image = (float(*)[4])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 16; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT) convertFloatToInt(); // with default settings } #else void LibRaw::deflate_dng_load_raw() { throw LIBRAW_EXCEPTION_DECODE_RAW; } #endif int LibRaw::is_floating_point() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) return 0; return ifd->sample_format == 3; } int LibRaw::have_fpdata() { return imgdata.rawdata.float_image || imgdata.rawdata.float3_image || imgdata.rawdata.float4_image; } void LibRaw::convertFloatToInt(float dmin /* =4096.f */, float dmax /* =32767.f */, float dtarget /*= 16383.f */) { int samples = 0; float *data = 0; if (imgdata.rawdata.float_image) { samples = 1; data = imgdata.rawdata.float_image; } else if (imgdata.rawdata.float3_image) { samples = 3; data = (float *)imgdata.rawdata.float3_image; } else if (imgdata.rawdata.float4_image) { samples = 4; data = (float *)imgdata.rawdata.float4_image; } else return; ushort *raw_alloc = (ushort *)malloc(imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples * sizeof(ushort)); float tmax = MAX(imgdata.color.maximum, 1); float datamax = imgdata.color.fmaximum; tmax = MAX(tmax, datamax); tmax = MAX(tmax, 1.f); float multip = 1.f; if (tmax < dmin || tmax > dmax) { imgdata.rawdata.color.fnorm = imgdata.color.fnorm = multip = dtarget / tmax; imgdata.rawdata.color.maximum = imgdata.color.maximum = dtarget; imgdata.rawdata.color.black = imgdata.color.black = (float)imgdata.color.black * multip; for (int i = 0; i < sizeof(imgdata.color.cblack) / sizeof(imgdata.color.cblack[0]); i++) if (i != 4 && i != 5) imgdata.rawdata.color.cblack[i] = imgdata.color.cblack[i] = (float)imgdata.color.cblack[i] * multip; } else imgdata.rawdata.color.fnorm = imgdata.color.fnorm = 0.f; for (size_t i = 0; i < imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples; ++i) { float val = MAX(data[i], 0.f); raw_alloc[i] = (ushort)(val * multip); } if (samples == 1) { imgdata.rawdata.raw_alloc = imgdata.rawdata.raw_image = raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 2; } else if (samples == 3) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color3_image = (ushort(*)[3])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; } else if (samples == 4) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = (ushort(*)[4])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; } free(data); // remove old allocation imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; imgdata.rawdata.float4_image = 0; } void LibRaw::sony_arq_load_raw() { int row, col; read_shorts(imgdata.rawdata.raw_image, imgdata.sizes.raw_width * imgdata.sizes.raw_height * 4); for (row = 0; row < imgdata.sizes.raw_height; row++) { unsigned short(*rowp)[4] = (unsigned short(*)[4]) & imgdata.rawdata.raw_image[row * imgdata.sizes.raw_width * 4]; for (col = 0; col < imgdata.sizes.raw_width; col++) { unsigned short g2 = rowp[col][2]; rowp[col][2] = rowp[col][3]; rowp[col][3] = g2; if (((unsigned)(row - imgdata.sizes.top_margin) < imgdata.sizes.height) && ((unsigned)(col - imgdata.sizes.left_margin) < imgdata.sizes.width) && (MAX(MAX(rowp[col][0], rowp[col][1]), MAX(rowp[col][2], rowp[col][3])) > imgdata.color.maximum)) derror(); } } } void LibRaw::pentax_4shot_load_raw() { ushort *plane = (ushort *)malloc(imgdata.sizes.raw_width * imgdata.sizes.raw_height * sizeof(ushort)); int alloc_sz = imgdata.sizes.raw_width * (imgdata.sizes.raw_height + 16) * 4 * sizeof(ushort); ushort(*result)[4] = (ushort(*)[4])malloc(alloc_sz); struct movement_t { int row, col; } _move[4] = { {1, 1}, {0, 1}, {0, 0}, {1, 0}, }; int tidx = 0; for (int i = 0; i < 4; i++) { int move_row, move_col; if (imgdata.params.p4shot_order[i] >= '0' && imgdata.params.p4shot_order[i] <= '3') { move_row = (imgdata.params.p4shot_order[i] - '0' & 2) ? 1 : 0; move_col = (imgdata.params.p4shot_order[i] - '0' & 1) ? 1 : 0; } else { move_row = _move[i].row; move_col = _move[i].col; } for (; tidx < 16; tidx++) if (tiff_ifd[tidx].t_width == imgdata.sizes.raw_width && tiff_ifd[tidx].t_height == imgdata.sizes.raw_height && tiff_ifd[tidx].bps > 8 && tiff_ifd[tidx].samples == 1) break; if (tidx >= 16) break; imgdata.rawdata.raw_image = plane; ID.input->seek(tiff_ifd[tidx].offset, SEEK_SET); imgdata.idata.filters = 0xb4b4b4b4; libraw_internal_data.unpacker_data.data_offset = tiff_ifd[tidx].offset; (this->*pentax_component_load_raw)(); for (int row = 0; row < imgdata.sizes.raw_height - move_row; row++) { int colors[2]; for (int c = 0; c < 2; c++) colors[c] = COLOR(row, c); ushort *srcrow = &plane[imgdata.sizes.raw_width * row]; ushort(*dstrow)[4] = &result[(imgdata.sizes.raw_width) * (row + move_row) + move_col]; for (int col = 0; col < imgdata.sizes.raw_width - move_col; col++) dstrow[col][colors[col % 2]] = srcrow[col]; } tidx++; } // assign things back: imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; imgdata.idata.filters = 0; imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = result; free(plane); imgdata.rawdata.raw_image = 0; } void LibRaw::hasselblad_full_load_raw() { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) { read_shorts(&imgdata.image[row * S.width + col][2], 1); // B read_shorts(&imgdata.image[row * S.width + col][1], 1); // G read_shorts(&imgdata.image[row * S.width + col][0], 1); // R } } static inline void unpack7bytesto4x16(unsigned char *src, unsigned short *dest) { dest[0] = (src[0] << 6) | (src[1] >> 2); dest[1] = ((src[1] & 0x3) << 12) | (src[2] << 4) | (src[3] >> 4); dest[2] = (src[3] & 0xf) << 10 | (src[4] << 2) | (src[5] >> 6); dest[3] = ((src[5] & 0x3f) << 8) | src[6]; } static inline void unpack28bytesto16x16ns(unsigned char *src, unsigned short *dest) { dest[0] = (src[3] << 6) | (src[2] >> 2); dest[1] = ((src[2] & 0x3) << 12) | (src[1] << 4) | (src[0] >> 4); dest[2] = (src[0] & 0xf) << 10 | (src[7] << 2) | (src[6] >> 6); dest[3] = ((src[6] & 0x3f) << 8) | src[5]; dest[4] = (src[4] << 6) | (src[11] >> 2); dest[5] = ((src[11] & 0x3) << 12) | (src[10] << 4) | (src[9] >> 4); dest[6] = (src[9] & 0xf) << 10 | (src[8] << 2) | (src[15] >> 6); dest[7] = ((src[15] & 0x3f) << 8) | src[14]; dest[8] = (src[13] << 6) | (src[12] >> 2); dest[9] = ((src[12] & 0x3) << 12) | (src[19] << 4) | (src[18] >> 4); dest[10] = (src[18] & 0xf) << 10 | (src[17] << 2) | (src[16] >> 6); dest[11] = ((src[16] & 0x3f) << 8) | src[23]; dest[12] = (src[22] << 6) | (src[21] >> 2); dest[13] = ((src[21] & 0x3) << 12) | (src[20] << 4) | (src[27] >> 4); dest[14] = (src[27] & 0xf) << 10 | (src[26] << 2) | (src[25] >> 6); dest[15] = ((src[25] & 0x3f) << 8) | src[24]; } #define swab32(x) \ ((unsigned int)((((unsigned int)(x) & (unsigned int)0x000000ffUL) << 24) | \ (((unsigned int)(x) & (unsigned int)0x0000ff00UL) << 8) | \ (((unsigned int)(x) & (unsigned int)0x00ff0000UL) >> 8) | \ (((unsigned int)(x) & (unsigned int)0xff000000UL) >> 24))) static inline void swab32arr(unsigned *arr, unsigned len) { for (unsigned i = 0; i < len; i++) arr[i] = swab32(arr[i]); } #undef swab32 void LibRaw::fuji_14bit_load_raw() { const unsigned linelen = S.raw_width * 7 / 4; const unsigned pitch = S.raw_pitch ? S.raw_pitch / 2 : S.raw_width; unsigned char *buf = (unsigned char *)malloc(linelen); merror(buf, "fuji_14bit_load_raw()"); for (int row = 0; row < S.raw_height; row++) { unsigned bytesread = libraw_internal_data.internal_data.input->read(buf, 1, linelen); unsigned short *dest = &imgdata.rawdata.raw_image[pitch * row]; if (bytesread % 28) { swab32arr((unsigned *)buf, bytesread / 4); for (int sp = 0, dp = 0; dp < pitch - 3 && sp < linelen - 6 && sp < bytesread - 6; sp += 7, dp += 4) unpack7bytesto4x16(buf + sp, dest + dp); } else for (int sp = 0, dp = 0; dp < pitch - 15 && sp < linelen - 27 && sp < bytesread - 27; sp += 28, dp += 16) unpack28bytesto16x16ns(buf + sp, dest + dp); } free(buf); } void LibRaw::nikon_load_striped_packed_raw() { int vbits = 0, bwide, rbits, bite, row, col, val, i; UINT64 bitbuf = 0; unsigned load_flags = 24; // libraw_internal_data.unpacker_data.load_flags; unsigned tiff_bps = libraw_internal_data.unpacker_data.tiff_bps; int tiff_compress = libraw_internal_data.unpacker_data.tiff_compress; struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) throw LIBRAW_EXCEPTION_DECODE_RAW; if (!ifd->rows_per_strip || !ifd->strip_offsets_count) return; // not unpacked int stripcnt = 0; bwide = S.raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - S.raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); for (row = 0; row < S.raw_height; row++) { checkCancel(); if (!(row % ifd->rows_per_strip)) { if (stripcnt >= ifd->strip_offsets_count) return; // run out of data libraw_internal_data.internal_data.input->seek(ifd->strip_offsets[stripcnt], SEEK_SET); stripcnt++; } for (col = 0; col < S.raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(libraw_internal_data.internal_data.input->get_char() << i); } imgdata.rawdata.raw_image[(row)*S.raw_width + (col)] = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); } vbits -= rbits; } } struct foveon_data_t { const char *make; const char *model; const int raw_width, raw_height; const int white; const int left_margin, top_margin; const int width, height; } foveon_data[] = { {"Sigma", "SD9", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD9", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD10", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD10", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD14", 2688, 1792, 14000, 18, 12, 2651, 1767}, {"Sigma", "SD14", 2688, 896, 14000, 18, 6, 2651, 883}, // 2/3 {"Sigma", "SD14", 1344, 896, 14000, 9, 6, 1326, 883}, // 1/2 {"Sigma", "SD15", 2688, 1792, 2900, 18, 12, 2651, 1767}, {"Sigma", "SD15", 2688, 896, 2900, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "SD15", 1344, 896, 2900, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1", 2688, 1792, 2100, 18, 12, 2651, 1767}, {"Sigma", "DP1", 2688, 896, 2100, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "DP1", 1344, 896, 2100, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1S", 2688, 1792, 2200, 18, 12, 2651, 1767}, {"Sigma", "DP1S", 2688, 896, 2200, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1S", 1344, 896, 2200, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP1X", 2688, 1792, 3560, 18, 12, 2651, 1767}, {"Sigma", "DP1X", 2688, 896, 3560, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1X", 1344, 896, 3560, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2", 2688, 1792, 2326, 13, 16, 2651, 1767}, {"Sigma", "DP2", 2688, 896, 2326, 13, 8, 2651, 883}, // 2/3 ?? {"Sigma", "DP2", 1344, 896, 2326, 7, 8, 1325, 883}, // 1/2 ?? {"Sigma", "DP2S", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2S", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2S", 1344, 896, 2300, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2X", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2X", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2X", 1344, 896, 2300, 9, 6, 1325, 883}, // 1/2 {"Sigma", "SD1", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "SD1 Merrill", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1 Merrill", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1 Merrill", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP1 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP2 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP2 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP2 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP3 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP3 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP3 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Polaroid", "x530", 1440, 1088, 2700, 10, 13, 1419, 1059}, // dp2 Q {"Sigma", "dp3 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp3 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp2 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp2 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp1 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp1 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp0 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp0 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size // Sigma sd Quattro {"Sigma", "sd Quattro", 5888, 3776, 16383, 204, 76, 5446, 3624}, // full size {"Sigma", "sd Quattro", 2944, 1888, 16383, 102, 38, 2723, 1812}, // half size // Sd Quattro H {"Sigma", "sd Quattro H", 6656, 4480, 16383, 224, 160, 6208, 4160}, // full size {"Sigma", "sd Quattro H", 3328, 2240, 16383, 112, 80, 3104, 2080}, // half size {"Sigma", "sd Quattro H", 5504, 3680, 16383, 0, 4, 5496, 3668}, // full size {"Sigma", "sd Quattro H", 2752, 1840, 16383, 0, 2, 2748, 1834}, // half size }; const int foveon_count = sizeof(foveon_data) / sizeof(foveon_data[0]); int LibRaw::open_datastream(LibRaw_abstract_datastream *stream) { if (!stream) return ENOENT; if (!stream->valid()) return LIBRAW_IO_ERROR; recycle(); if(callbacks.pre_identify_cb) { int r = (callbacks.pre_identify_cb)(this); if(r == 1) goto final; } try { ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); identify(); if(callbacks.post_identify_cb) (callbacks.post_identify_cb)(this); #if 0 if(!strcasecmp(imgdata.idata.make, "Sony") && imgdata.color.maximum > 0 && imgdata.color.linear_max[0] > imgdata.color.maximum*3 && imgdata.color.linear_max[0] <= imgdata.color.maximum*4) for(int c = 0; c<4; c++) imgdata.color.linear_max[c] /= 4; #endif if (!strcasecmp(imgdata.idata.make, "Canon") && (load_raw == &LibRaw::canon_sraw_load_raw) && imgdata.sizes.raw_width > 0) { float ratio = float(imgdata.sizes.raw_height) / float(imgdata.sizes.raw_width); if ((ratio < 0.57 || ratio > 0.75) && imgdata.makernotes.canon.SensorHeight > 1 && imgdata.makernotes.canon.SensorWidth > 1) { imgdata.sizes.raw_width = imgdata.makernotes.canon.SensorWidth; imgdata.sizes.left_margin = imgdata.makernotes.canon.SensorLeftBorder; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.makernotes.canon.SensorRightBorder - imgdata.makernotes.canon.SensorLeftBorder + 1; imgdata.sizes.raw_height = imgdata.makernotes.canon.SensorHeight; imgdata.sizes.top_margin = imgdata.makernotes.canon.SensorTopBorder; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.makernotes.canon.SensorBottomBorder - imgdata.makernotes.canon.SensorTopBorder + 1; libraw_internal_data.unpacker_data.load_flags |= 256; // reset width/height in canon_sraw_load_raw() imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } else if (imgdata.sizes.raw_width == 4032 && imgdata.sizes.raw_height == 3402 && !strcasecmp(imgdata.idata.model, "EOS 80D")) // 80D hardcoded { imgdata.sizes.raw_width = 4536; imgdata.sizes.left_margin = 28; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.sizes.raw_width - imgdata.sizes.left_margin; imgdata.sizes.raw_height = 3024; imgdata.sizes.top_margin = 8; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.sizes.raw_height - imgdata.sizes.top_margin; libraw_internal_data.unpacker_data.load_flags |= 256; imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } } // XTrans Compressed? if (!imgdata.idata.dng_version && !strcasecmp(imgdata.idata.make, "Fujifilm") && (load_raw == &LibRaw::unpacked_load_raw)) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 2 != libraw_internal_data.unpacker_data.data_size) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 7 / 4 == libraw_internal_data.unpacker_data.data_size) load_raw = &LibRaw::fuji_14bit_load_raw; else parse_fuji_compressed_header(); } if (imgdata.idata.filters == 9) { // Adjust top/left margins for X-Trans int newtm = imgdata.sizes.top_margin % 6 ? (imgdata.sizes.top_margin / 6 + 1) * 6 : imgdata.sizes.top_margin; int newlm = imgdata.sizes.left_margin % 6 ? (imgdata.sizes.left_margin / 6 + 1) * 6 : imgdata.sizes.left_margin; if (newtm != imgdata.sizes.top_margin || newlm != imgdata.sizes.left_margin) { imgdata.sizes.height -= (newtm - imgdata.sizes.top_margin); imgdata.sizes.top_margin = newtm; imgdata.sizes.width -= (newlm - imgdata.sizes.left_margin); imgdata.sizes.left_margin = newlm; for (int c1 = 0; c1 < 6; c1++) for (int c2 = 0; c2 < 6; c2++) imgdata.idata.xtrans[c1][c2] = imgdata.idata.xtrans_abs[c1][c2]; } } } // Fix DNG white balance if needed if (imgdata.idata.dng_version && (imgdata.idata.filters == 0) && imgdata.idata.colors > 1 && imgdata.idata.colors < 5) { float delta[4] = {0.f, 0.f, 0.f, 0.f}; int black[4]; for (int c = 0; c < 4; c++) black[c] = imgdata.color.dng_levels.dng_black + imgdata.color.dng_levels.dng_cblack[c]; for (int c = 0; c < imgdata.idata.colors; c++) delta[c] = imgdata.color.dng_levels.dng_whitelevel[c] - black[c]; float mindelta = delta[0], maxdelta = delta[0]; for (int c = 1; c < imgdata.idata.colors; c++) { if (mindelta > delta[c]) mindelta = delta[c]; if (maxdelta < delta[c]) maxdelta = delta[c]; } if (mindelta > 1 && maxdelta < (mindelta * 20)) // safety { for (int c = 0; c < imgdata.idata.colors; c++) { imgdata.color.cam_mul[c] /= (delta[c] / maxdelta); imgdata.color.pre_mul[c] /= (delta[c] / maxdelta); } imgdata.color.maximum = imgdata.color.cblack[0] + maxdelta; } } if (imgdata.idata.dng_version && ((!strcasecmp(imgdata.idata.make, "Leica") && !strcasecmp(imgdata.idata.model, "D-LUX (Typ 109)")) || (!strcasecmp(imgdata.idata.make, "Panasonic") && !strcasecmp(imgdata.idata.model, "LX100")))) imgdata.sizes.width = 4288; if (!strncasecmp(imgdata.idata.make, "Sony", 4) && imgdata.idata.dng_version && !(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)) { if (S.raw_width == 3984) S.width = 3925; else if (S.raw_width == 4288) S.width = S.raw_width - 32; else if (S.raw_width == 4928 && S.height < 3280) S.width = S.raw_width - 8; else if (S.raw_width == 5504) S.width = S.raw_width - (S.height > 3664 ? 8 : 32); } if (!strcasecmp(imgdata.idata.make, "Pentax") && /*!strcasecmp(imgdata.idata.model,"K-3 II") &&*/ imgdata.idata.raw_count == 4 && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_PENTAX_PS_ALLFRAMES)) { imgdata.idata.raw_count = 1; imgdata.idata.filters = 0; imgdata.idata.colors = 4; IO.mix_green = 1; pentax_component_load_raw = load_raw; load_raw = &LibRaw::pentax_4shot_load_raw; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Leaf") && !strcmp(imgdata.idata.model, "Credo 50")) { imgdata.color.pre_mul[0] = 1.f / 0.3984f; imgdata.color.pre_mul[2] = 1.f / 0.7666f; imgdata.color.pre_mul[1] = imgdata.color.pre_mul[3] = 1.0; } // S3Pro DNG patch if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S3Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S5Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && (!strncmp(imgdata.idata.model, "S20Pro", 6) || !strncmp(imgdata.idata.model, "F700", 4))) { imgdata.sizes.raw_width /= 2; load_raw = &LibRaw::unpacked_load_raw_fuji_f700s20; } if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Nikon") && !libraw_internal_data.unpacker_data.load_flags && (!strncasecmp(imgdata.idata.model, "D810", 4) || !strcasecmp(imgdata.idata.model, "D4S")) && libraw_internal_data.unpacker_data.data_size * 2 == imgdata.sizes.raw_height * imgdata.sizes.raw_width * 3) { libraw_internal_data.unpacker_data.load_flags = 80; } // Adjust BL for Sony A900/A850 if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Sony")) // 12 bit sony, but metadata may be for 14-bit range { if (C.maximum > 4095) C.maximum = 4095; if (C.black > 256 || C.cblack[0] > 256) { C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } } if (load_raw == &LibRaw::nikon_yuv_load_raw) // Is it Nikon sRAW? { load_raw = &LibRaw::nikon_load_sraw; C.black = 0; memset(C.cblack, 0, sizeof(C.cblack)); imgdata.idata.filters = 0; libraw_internal_data.unpacker_data.tiff_samples = 3; imgdata.idata.colors = 3; double beta_1 = -5.79342238397656E-02; double beta_2 = 3.28163551282665; double beta_3 = -8.43136004842678; double beta_4 = 1.03533181861023E+01; for (int i = 0; i <= 3072; i++) { double x = (double)i / 3072.; double y = (1. - exp(-beta_1 * x - beta_2 * x * x - beta_3 * x * x * x - beta_4 * x * x * x * x)); if (y < 0.) y = 0.; imgdata.color.curve[i] = (y * 16383.); } for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) imgdata.color.rgb_cam[i][j] = float(i == j); } // Adjust BL for Nikon 12bit if ((load_raw == &LibRaw::nikon_load_raw || load_raw == &LibRaw::packed_load_raw) && !strcasecmp(imgdata.idata.make, "Nikon") && strncmp(imgdata.idata.model, "COOLPIX", 7) // && strncmp(imgdata.idata.model,"1 ",2) && libraw_internal_data.unpacker_data.tiff_bps == 12) { C.maximum = 4095; C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } // Adjust Highlight Linearity limit if (C.linear_max[0] < 0) { if (imgdata.idata.dng_version) { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c + 6]; } else { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c]; } } if (!strcasecmp(imgdata.idata.make, "Nikon") && (!C.linear_max[0]) && (C.maximum > 1024) && (load_raw != &LibRaw::nikon_load_sraw)) { C.linear_max[0] = C.linear_max[1] = C.linear_max[2] = C.linear_max[3] = (long)((float)(C.maximum) / 1.07f); } // Correct WB for Samsung GX20 if (!strcasecmp(imgdata.idata.make, "Samsung") && !strcasecmp(imgdata.idata.model, "GX20")) { C.WB_Coeffs[LIBRAW_WBI_Daylight][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Daylight][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Shade][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Shade][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Cloudy][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Tungsten][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_D][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_D][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_N][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_N][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_W][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_W][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Flash][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Flash][2]) * 2.56f); for (int c = 0; c < 64; c++) { if (imgdata.color.WBCT_Coeffs[c][0] > 0.0f) { imgdata.color.WBCT_Coeffs[c][3] *= 2.56f; } } } // Adjust BL for Panasonic if (load_raw == &LibRaw::panasonic_load_raw && (!strcasecmp(imgdata.idata.make, "Panasonic") || !strcasecmp(imgdata.idata.make, "Leica") || !strcasecmp(imgdata.idata.make, "YUNEEC")) && ID.pana_black[0] && ID.pana_black[1] && ID.pana_black[2]) { if(libraw_internal_data.unpacker_data.pana_encoding == 5) P1.raw_count = 0; // Disable for new decoder C.black = 0; int add = libraw_internal_data.unpacker_data.pana_encoding == 4?15:0; C.cblack[0] = ID.pana_black[0]+add; C.cblack[1] = C.cblack[3] = ID.pana_black[1]+add; C.cblack[2] = ID.pana_black[2]+add; int i = C.cblack[3]; for (int c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (int c = 0; c < 4; c++) C.cblack[c] -= i; C.black = i; } // Adjust sizes for X3F processing if (load_raw == &LibRaw::x3f_load_raw) { for (int i = 0; i < foveon_count; i++) if (!strcasecmp(imgdata.idata.make, foveon_data[i].make) && !strcasecmp(imgdata.idata.model, foveon_data[i].model) && imgdata.sizes.raw_width == foveon_data[i].raw_width && imgdata.sizes.raw_height == foveon_data[i].raw_height) { imgdata.sizes.top_margin = foveon_data[i].top_margin; imgdata.sizes.left_margin = foveon_data[i].left_margin; imgdata.sizes.width = imgdata.sizes.iwidth = foveon_data[i].width; imgdata.sizes.height = imgdata.sizes.iheight = foveon_data[i].height; C.maximum = foveon_data[i].white; break; } } #if 0 size_t bytes = ID.input->size()-libraw_internal_data.unpacker_data.data_offset; float bpp = float(bytes)/float(S.raw_width)/float(S.raw_height); float bpp2 = float(bytes)/float(S.width)/float(S.height); printf("RawSize: %dx%d data offset: %d data size:%d bpp: %g bpp2: %g\n",S.raw_width,S.raw_height,libraw_internal_data.unpacker_data.data_offset,bytes,bpp,bpp2); if(!strcasecmp(imgdata.idata.make,"Hasselblad") && bpp == 6.0f) { load_raw = &LibRaw::hasselblad_full_load_raw; S.width = S.raw_width; S.height = S.raw_height; P1.filters = 0; P1.colors=3; P1.raw_count=1; C.maximum=0xffff; printf("3 channel hassy found\n"); } #endif if (C.profile_length) { if (C.profile) free(C.profile); C.profile = malloc(C.profile_length); merror(C.profile, "LibRaw::open_file()"); ID.input->seek(ID.profile_offset, SEEK_SET); ID.input->read(C.profile, C.profile_length, 1); } SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } final:; if (P1.raw_count < 1) return LIBRAW_FILE_UNSUPPORTED; write_fun = &LibRaw::write_ppm_tiff; if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); if (IO.shrink && P1.filters >= 1000) { S.width &= 65534; S.height &= 65534; } S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_SIZE_ADJUST); return LIBRAW_SUCCESS; } #ifdef USE_RAWSPEED void LibRaw::fix_after_rawspeed(int bl) { if (load_raw == &LibRaw::lossy_dng_load_raw) C.maximum = 0xffff; else if (load_raw == &LibRaw::sony_load_raw) C.maximum = 0x3ff0; } #else void LibRaw::fix_after_rawspeed(int) {} #endif void LibRaw::clearCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 0); #else __sync_fetch_and_and(&_exitflag, 0); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->resumeProcessing(); } #endif } void LibRaw::setCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 1); #else __sync_fetch_and_add(&_exitflag, 1); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->cancelProcessing(); } #endif } void LibRaw::checkCancel() { #ifdef WIN32 if (InterlockedExchange(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #else if (__sync_fetch_and_and(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } int LibRaw::try_rawspeed() { #ifdef USE_RAWSPEED int ret = LIBRAW_SUCCESS; int rawspeed_ignore_errors = 0; if (imgdata.idata.dng_version && imgdata.idata.colors == 3 && !strcasecmp(imgdata.idata.software, "Adobe Photoshop Lightroom 6.1.1 (Windows)")) rawspeed_ignore_errors = 1; // RawSpeed Supported, INT64 spos = ID.input->tell(); void *_rawspeed_buffer = 0; try { // printf("Using rawspeed\n"); ID.input->seek(0, SEEK_SET); INT64 _rawspeed_buffer_sz = ID.input->size() + 32; _rawspeed_buffer = malloc(_rawspeed_buffer_sz); if (!_rawspeed_buffer) throw LIBRAW_EXCEPTION_ALLOC; ID.input->read(_rawspeed_buffer, _rawspeed_buffer_sz, 1); FileMap map((uchar8 *)_rawspeed_buffer, _rawspeed_buffer_sz); RawParser t(&map); RawDecoder *d = 0; CameraMetaDataLR *meta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); d = t.getDecoder(); if (!d) throw "Unable to find decoder"; try { d->checkSupport(meta); } catch (const RawDecoderException &e) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_UNSUPPORTED; throw e; } d->interpolateBadPixels = FALSE; d->applyStage1DngOpcodes = FALSE; _rawspeed_decoder = static_cast<void *>(d); d->decodeRaw(); d->decodeMetaData(meta); RawImage r = d->mRaw; if (r->errors.size() > 0 && !rawspeed_ignore_errors) { delete d; _rawspeed_decoder = 0; throw 1; } if (r->isCFA) { imgdata.rawdata.raw_image = (ushort *)r->getDataUncropped(0, 0); } else if (r->getCpp() == 4) { imgdata.rawdata.color4_image = (ushort(*)[4])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else if (r->getCpp() == 3) { imgdata.rawdata.color3_image = (ushort(*)[3])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else { delete d; _rawspeed_decoder = 0; ret = LIBRAW_UNSPECIFIED_ERROR; } if (_rawspeed_decoder) { // set sizes iPoint2D rsdim = r->getUncroppedDim(); S.raw_pitch = r->pitch; S.raw_width = rsdim.x; S.raw_height = rsdim.y; // C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } free(_rawspeed_buffer); _rawspeed_buffer = 0; imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROCESSED; } catch (const RawDecoderException &RDE) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } const char *p = RDE.what(); if (!strncmp(RDE.what(), "Decoder canceled", strlen("Decoder canceled"))) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; ret = LIBRAW_UNSPECIFIED_ERROR; } catch (...) { // We may get here due to cancellation flag imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } ret = LIBRAW_UNSPECIFIED_ERROR; } ID.input->seek(spos, SEEK_SET); return ret; #else return LIBRAW_NOT_IMPLEMENTED; #endif } int LibRaw::valid_for_dngsdk() { #ifndef USE_DNGSDK return 0; #else if (!imgdata.idata.dng_version) return 0; if (!imgdata.params.use_dngsdk) return 0; if (load_raw == &LibRaw::lossy_dng_load_raw) return 0; if (is_floating_point() && (imgdata.params.use_dngsdk & LIBRAW_DNG_FLOAT)) return 1; if (!imgdata.idata.filters && (imgdata.params.use_dngsdk & LIBRAW_DNG_LINEAR)) return 1; if (libraw_internal_data.unpacker_data.tiff_bps == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_8BIT)) return 1; if (libraw_internal_data.unpacker_data.tiff_compress == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_DEFLATE)) return 1; if (libraw_internal_data.unpacker_data.tiff_samples == 2) return 0; // Always deny 2-samples (old fuji superccd) if (imgdata.idata.filters == 9 && (imgdata.params.use_dngsdk & LIBRAW_DNG_XTRANS)) return 1; if (is_fuji_rotated()) return 0; // refuse if (imgdata.params.use_dngsdk & LIBRAW_DNG_OTHER) return 1; return 0; #endif } int LibRaw::is_curve_linear() { for (int i = 0; i < 0x10000; i++) if (imgdata.color.curve[i] != i) return 0; return 1; } int LibRaw::try_dngsdk() { #ifdef USE_DNGSDK if (!dnghost) return LIBRAW_UNSPECIFIED_ERROR; dng_host *host = static_cast<dng_host *>(dnghost); try { libraw_dng_stream stream(libraw_internal_data.internal_data.input); AutoPtr<dng_negative> negative; negative.Reset(host->Make_dng_negative()); dng_info info; info.Parse(*host, stream); info.PostParse(*host); if (!info.IsValidDNG()) { return LIBRAW_DATA_ERROR; } negative->Parse(*host, stream, info); negative->PostParse(*host, stream, info); negative->ReadStage1Image(*host, stream, info); dng_simple_image *stage2 = (dng_simple_image *)negative->Stage1Image(); if (stage2->Bounds().W() != S.raw_width || stage2->Bounds().H() != S.raw_height) { return LIBRAW_DATA_ERROR; } int pplanes = stage2->Planes(); int ptype = stage2->PixelType(); dng_pixel_buffer buffer; stage2->GetPixelBuffer(buffer); int pixels = stage2->Bounds().H() * stage2->Bounds().W() * pplanes; if (ptype == ttByte) imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ttShort)); else imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ptype)); if (ptype == ttShort && !is_curve_linear()) { ushort *src = (ushort *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } else if (ptype == ttByte) { unsigned char *src = (unsigned char *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; if (is_curve_linear()) { for (int i = 0; i < pixels; i++) dst[i] = src[i]; } else { for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; } S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ttShort); } else { memmove(imgdata.rawdata.raw_alloc, buffer.fData, pixels * TagTypeSize(ptype)); S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } switch (ptype) { case ttFloat: if (pplanes == 1) imgdata.rawdata.float_image = (float *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.float3_image = (float(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.float4_image = (float(*)[4])imgdata.rawdata.raw_alloc; break; case ttByte: case ttShort: if (pplanes == 1) imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; break; default: /* do nothing */ break; } } catch (...) { return LIBRAW_UNSPECIFIED_ERROR; } return imgdata.rawdata.raw_alloc ? LIBRAW_SUCCESS : LIBRAW_UNSPECIFIED_ERROR; #else return LIBRAW_UNSPECIFIED_ERROR; #endif } void LibRaw::set_dng_host(void *p) { #ifdef USE_DNGSDK dnghost = p; #endif } int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 0, 2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if (!load_raw) return LIBRAW_UNSPECIFIED_ERROR; // already allocated ? if (imgdata.image) { free(imgdata.image); imgdata.image = 0; } if (imgdata.rawdata.raw_alloc) { free(imgdata.rawdata.raw_alloc); imgdata.rawdata.raw_alloc = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *)malloc(libraw_internal_data.unpacker_data.meta_length); merror(libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if (!IO.fuji_width) { // adjust non-Fuji allocation if (rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if (rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } if (rwidth > 65535 || rheight > 65535) // No way to make image larger than 64k pix throw LIBRAW_EXCEPTION_IO_CORRUPT; imgdata.rawdata.raw_image = 0; imgdata.rawdata.color4_image = 0; imgdata.rawdata.color3_image = 0; imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; #ifdef USE_DNGSDK if (imgdata.idata.dng_version && dnghost && imgdata.idata.raw_count == 1 && valid_for_dngsdk() && load_raw != &LibRaw::pentax_4shot_load_raw) { int rr = try_dngsdk(); } #endif #ifdef USE_RAWSPEED if (!raw_was_read()) { int rawspeed_enabled = 1; if (imgdata.idata.dng_version && libraw_internal_data.unpacker_data.tiff_samples == 2) rawspeed_enabled = 0; if (imgdata.idata.raw_count > 1) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.software, "Magic", 5)) rawspeed_enabled = 0; // Disable rawspeed for double-sized Oly files if (!strncasecmp(imgdata.idata.make, "Olympus", 7) && ((imgdata.sizes.raw_width > 6000) || !strncasecmp(imgdata.idata.model, "SH-2", 4) || !strncasecmp(imgdata.idata.model, "SH-3", 4) || !strncasecmp(imgdata.idata.model, "TG-4", 4) || !strncasecmp(imgdata.idata.model, "TG-5", 4))) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.make, "Canon", 5) && !strcasecmp(imgdata.idata.model, "EOS 6D Mark II")) rawspeed_enabled = 0; if (imgdata.idata.dng_version && imgdata.idata.filters == 0 && libraw_internal_data.unpacker_data.tiff_bps == 8) // Disable for 8 bit rawspeed_enabled = 0; if (load_raw == &LibRaw::packed_load_raw && !strncasecmp(imgdata.idata.make, "Nikon", 5) && (!strncasecmp(imgdata.idata.model, "E", 1) || !strncasecmp(imgdata.idata.model, "COOLPIX B", 9))) rawspeed_enabled = 0; // RawSpeed Supported, if (O.use_rawspeed && rawspeed_enabled && !(is_sraw() && (O.raw_processing_options & (LIBRAW_PROCESSING_SRAW_NO_RGB | LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE))) && (decoder_info.decoder_flags & LIBRAW_DECODER_TRYRAWSPEED) && _rawspeed_camerameta) { int rr = try_rawspeed(); } } #endif if (!raw_was_read()) // RawSpeed failed or not run { // Not allocated on RawSpeed call, try call LibRaow int zero_rawimage = 0; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder and DNG float // Do nothing! Decoder will allocate data internally } if (decoder_info.decoder_flags & LIBRAW_DECODER_3CHANNEL) { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3 > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3); imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 6; } else if (imgdata.idata.filters || P1.colors == 1) // Bayer image or single color -> decode to raw_image { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 2; // Bayer case, not set before } else // NO LEGACY FLAG if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) { S.raw_pitch = S.raw_width * 8; } else { S.iwidth = S.width; S.iheight = S.height; IO.shrink = 0; if (!S.raw_pitch) S.raw_pitch = (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS) ? S.raw_width * 8 : S.width * 8; } // sRAW and old Foveon decoders only, so extra buffer size is just 1/4 // allocate image as temporary buffer, size if (INT64(MAX(S.width, S.raw_width)) * INT64(MAX(S.height, S.raw_height)) * sizeof(*imgdata.image) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = 0; imgdata.image = (ushort(*)[4])calloc( unsigned(MAX(S.width, S.raw_width)) * unsigned(MAX(S.height, S.raw_height)), sizeof(*imgdata.image)); if (!(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL)) { imgdata.rawdata.raw_image = (ushort *)imgdata.image; zero_rawimage = 1; } } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); unsigned m_save = C.maximum; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = 65535; (this->*load_raw)(); if (zero_rawimage) imgdata.rawdata.raw_image = 0; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = m_save; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder only: do nothing } else if (!(imgdata.idata.filters || P1.colors == 1)) // legacy decoder, ownalloc handled above { // successfully decoded legacy image, attach image to raw_alloc imgdata.rawdata.raw_alloc = imgdata.image; imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; imgdata.image = 0; // Restore saved values. Note: Foveon have masked frame // Other 4-color legacy data: no borders if (!(libraw_internal_data.unpacker_data.load_flags & 256) && !(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) && !(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS)) { S.raw_width = S.width; S.left_margin = 0; S.raw_height = S.height; S.top_margin = 0; } } } if (imgdata.rawdata.raw_image) crop_masked_pixels(); // calculate black levels // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 1, 2); return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } void LibRaw::unpacked_load_raw_fuji_f700s20() { int base_offset = 0; int row_size = imgdata.sizes.raw_width * 2; // in bytes if (imgdata.idata.raw_count == 2 && imgdata.params.shot_select) { libraw_internal_data.internal_data.input->seek(-row_size, SEEK_CUR); base_offset = row_size; // in bytes } unsigned char *buffer = (unsigned char *)malloc(row_size * 2); for (int row = 0; row < imgdata.sizes.raw_height; row++) { read_shorts((ushort *)buffer, imgdata.sizes.raw_width * 2); memmove(&imgdata.rawdata.raw_image[row * imgdata.sizes.raw_pitch / 2], buffer + base_offset, row_size); } free(buffer); } void LibRaw::nikon_load_sraw() { // We're already seeked to data! unsigned char *rd = (unsigned char *)malloc(3 * (imgdata.sizes.raw_width + 2)); if (!rd) throw LIBRAW_EXCEPTION_ALLOC; try { int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); libraw_internal_data.internal_data.input->read(rd, 3, imgdata.sizes.raw_width); for (col = 0; col < imgdata.sizes.raw_width - 1; col += 2) { int bi = col * 3; ushort bits1 = (rd[bi + 1] & 0xf) << 8 | rd[bi]; // 3,0,1 ushort bits2 = rd[bi + 2] << 4 | ((rd[bi + 1] >> 4) & 0xf); // 452 ushort bits3 = ((rd[bi + 4] & 0xf) << 8) | rd[bi + 3]; // 967 ushort bits4 = rd[bi + 5] << 4 | ((rd[bi + 4] >> 4) & 0xf); // ab8 imgdata.image[row * imgdata.sizes.raw_width + col][0] = bits1; imgdata.image[row * imgdata.sizes.raw_width + col][1] = bits3; imgdata.image[row * imgdata.sizes.raw_width + col][2] = bits4; imgdata.image[row * imgdata.sizes.raw_width + col + 1][0] = bits2; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = 2048; imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = 2048; } } } catch (...) { free(rd); throw; } free(rd); C.maximum = 0xfff; // 12 bit? if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { return; // no CbCr interpolation } // Interpolate CC channels int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col += 2) { int col2 = col < imgdata.sizes.raw_width - 2 ? col + 2 : col; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][1] + imgdata.image[row * imgdata.sizes.raw_width + col2][1]) / 2); imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][2] + imgdata.image[row * imgdata.sizes.raw_width + col2][2]) / 2); } } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) return; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col++) { float Y = float(imgdata.image[row * imgdata.sizes.raw_width + col][0]) / 2549.f; float Ch2 = float(imgdata.image[row * imgdata.sizes.raw_width + col][1] - 1280) / 1536.f; float Ch3 = float(imgdata.image[row * imgdata.sizes.raw_width + col][2] - 1280) / 1536.f; if (Y > 1.f) Y = 1.f; if (Y > 0.803f) Ch2 = Ch3 = 0.5f; float r = Y + 1.40200f * (Ch3 - 0.5f); if (r < 0.f) r = 0.f; if (r > 1.f) r = 1.f; float g = Y - 0.34414f * (Ch2 - 0.5f) - 0.71414 * (Ch3 - 0.5f); if (g > 1.f) g = 1.f; if (g < 0.f) g = 0.f; float b = Y + 1.77200 * (Ch2 - 0.5f); if (b > 1.f) b = 1.f; if (b < 0.f) b = 0.f; imgdata.image[row * imgdata.sizes.raw_width + col][0] = imgdata.color.curve[int(r * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][1] = imgdata.color.curve[int(g * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][2] = imgdata.color.curve[int(b * 3072.f)]; } } C.maximum = 16383; } void LibRaw::free_image(void) { if (imgdata.image) { free(imgdata.image); imgdata.image = 0; imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; } } void LibRaw::raw2image_start() { // restore color,sizes and internal data into raw_image fields memmove(&imgdata.color, &imgdata.rawdata.color, sizeof(imgdata.color)); memmove(&imgdata.sizes, &imgdata.rawdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.idata, &imgdata.rawdata.iparams, sizeof(imgdata.idata)); memmove(&libraw_internal_data.internal_output_params, &imgdata.rawdata.ioparams, sizeof(libraw_internal_data.internal_output_params)); if (O.user_flip >= 0) S.flip = O.user_flip; switch ((S.flip + 3600) % 360) { case 270: S.flip = 5; break; case 180: S.flip = 3; break; case 90: S.flip = 6; break; } // adjust for half mode! IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; } int LibRaw::is_phaseone_compressed() { return (load_raw == &LibRaw::phase_one_load_raw_c || load_raw == &LibRaw::phase_one_load_raw); } int LibRaw::is_canon_600() { return load_raw == &LibRaw::canon_600_load_raw; } int LibRaw::raw2image(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // free and re-allocate image bitmap if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, S.iheight * S.iwidth * sizeof(*imgdata.image)); memset(imgdata.image, 0, S.iheight * S.iwidth * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { unsigned r, c; int row, col; for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][FC(r, c)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } } else { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][fcol(row, col)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.width * 8 == S.raw_pitch) memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); else { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } // hack - clear later flags! if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } void LibRaw::phase_one_allocate_tempbuffer() { // Allocate temp raw_image buffer imgdata.rawdata.raw_image = (ushort *)malloc(S.raw_pitch * S.raw_height); merror(imgdata.rawdata.raw_image, "phase_one_prepare_to_correct()"); } void LibRaw::phase_one_free_tempbuffer() { free(imgdata.rawdata.raw_image); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; } int LibRaw::phase_one_subtract_black(ushort *src, ushort *dest) { try { if (O.user_black < 0 && O.user_cblack[0] <= -1000000 && O.user_cblack[1] <= -1000000 && O.user_cblack[2] <= -1000000 && O.user_cblack[3] <= -1000000) { if (!imgdata.rawdata.ph1_cblack || !imgdata.rawdata.ph1_rblack) { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl; dest[idx] = val > 0 ? val : 0; } } } else { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl + imgdata.rawdata.ph1_cblack[row][col >= imgdata.rawdata.color.phase_one_data.split_col] + imgdata.rawdata.ph1_rblack[col][row >= imgdata.rawdata.color.phase_one_data.split_row]; dest[idx] = val > 0 ? val : 0; } } } } else // black set by user interaction { // Black level in cblack! for (int row = 0; row < S.raw_height; row++) { checkCancel(); unsigned short cblk[16]; for (int cc = 0; cc < 16; cc++) cblk[cc] = C.cblack[fcol(row, cc)]; for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; ushort val = src[idx]; ushort bl = cblk[col & 0xf]; dest[idx] = val > bl ? val - bl : 0; } } } return 0; } catch (LibRaw_exceptions err) { return LIBRAW_CANCELLED_BY_CALLBACK; } } void LibRaw::copy_fuji_uncropped(unsigned short cblack[4], unsigned short *dmaxp) { int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { unsigned r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FC(r, c); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][cc] = val; } } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } void LibRaw::copy_bayer(unsigned short cblack[4], unsigned short *dmaxp) { // Both cropped and uncropped int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.height; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < S.width; col++) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = fcol(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][cc] = val; } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } int LibRaw::raw2image_ex(int do_subtract_black) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); // Compressed P1 files with bl data! if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // process cropping int do_crop = 0; unsigned save_width = S.width; if (~O.cropbox[2] && ~O.cropbox[3]) { int crop[4], c, filt; for (int c = 0; c < 4; c++) { crop[c] = O.cropbox[c]; if (crop[c] < 0) crop[c] = 0; } if (IO.fuji_width && imgdata.idata.filters >= 1000) { crop[0] = (crop[0] / 4) * 4; crop[1] = (crop[1] / 4) * 4; if (!libraw_internal_data.unpacker_data.fuji_layout) { crop[2] *= sqrt(2.0); crop[3] /= sqrt(2.0); } crop[2] = (crop[2] / 4 + 1) * 4; crop[3] = (crop[3] / 4 + 1) * 4; } else if (imgdata.idata.filters == 1) { crop[0] = (crop[0] / 16) * 16; crop[1] = (crop[1] / 16) * 16; } else if (imgdata.idata.filters == LIBRAW_XTRANS) { crop[0] = (crop[0] / 6) * 6; crop[1] = (crop[1] / 6) * 6; } do_crop = 1; crop[2] = MIN(crop[2], (signed)S.width - crop[0]); crop[3] = MIN(crop[3], (signed)S.height - crop[1]); if (crop[2] <= 0 || crop[3] <= 0) throw LIBRAW_EXCEPTION_BAD_CROP; // adjust sizes! S.left_margin += crop[0]; S.top_margin += crop[1]; S.width = crop[2]; S.height = crop[3]; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if (!IO.fuji_width && imgdata.idata.filters && imgdata.idata.filters >= 1000) { for (filt = c = 0; c < 16; c++) filt |= FC((c >> 1) + (crop[1]), (c & 1) + (crop[0])) << c * 2; imgdata.idata.filters = filt; } } int alloc_width = S.iwidth; int alloc_height = S.iheight; if (IO.fuji_width && do_crop) { int IO_fw = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int t_alloc_width = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO_fw; int t_alloc_height = t_alloc_width - 1; alloc_height = (t_alloc_height + IO.shrink) >> IO.shrink; alloc_width = (t_alloc_width + IO.shrink) >> IO.shrink; } int alloc_sz = alloc_width * alloc_height; if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, alloc_sz * sizeof(*imgdata.image)); memset(imgdata.image, 0, alloc_sz * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(alloc_sz, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image_ex()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Adjust black levels unsigned short cblack[4] = {0, 0, 0, 0}; unsigned short dmax = 0; if (do_subtract_black) { adjust_bl(); for (int i = 0; i < 4; i++) cblack[i] = (unsigned short)C.cblack[i]; } // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { if (do_crop) { IO.fuji_width = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int IO_fwidth = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO.fuji_width; int IO_fheight = IO_fwidth - 1; int row, col; for (row = 0; row < S.height; row++) { for (col = 0; col < S.width; col++) { int r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FCF(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (dmax < val) dmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * alloc_width + ((c) >> IO.shrink)][cc] = val; } } S.height = IO_fheight; S.width = IO_fwidth; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; S.raw_height -= 2 * S.top_margin; } else { copy_fuji_uncropped(cblack, &dmax); } } // end Fuji else { copy_bayer(cblack, &dmax); } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.raw_pitch != S.width * 8) { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } else { // legacy is always 4channel and not shrinked! memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } if (do_subtract_black) { C.data_maximum = (int)dmax; C.maximum -= C.black; // ZERO(C.cblack); C.cblack[0] = C.cblack[1] = C.cblack[2] = C.cblack[3] = 0; C.black = 0; } // hack - clear later flags! imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #if 1 libraw_processed_image_t *LibRaw::dcraw_make_mem_thumb(int *errcode) { if (!T.thumb) { if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { if (errcode) *errcode = LIBRAW_NO_THUMBNAIL; } else { if (errcode) *errcode = LIBRAW_OUT_OF_ORDER_CALL; } return NULL; } if (T.tformat == LIBRAW_THUMBNAIL_BITMAP) { libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + T.tlength); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_BITMAP; ret->height = T.theight; ret->width = T.twidth; ret->colors = 3; ret->bits = 8; ret->data_size = T.tlength; memmove(ret->data, T.thumb, T.tlength); if (errcode) *errcode = 0; return ret; } else if (T.tformat == LIBRAW_THUMBNAIL_JPEG) { ushort exif[5]; int mk_exif = 0; if (strcmp(T.thumb + 6, "Exif")) mk_exif = 1; int dsize = T.tlength + mk_exif * (sizeof(exif) + sizeof(tiff_hdr)); libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + dsize); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_JPEG; ret->data_size = dsize; ret->data[0] = 0xff; ret->data[1] = 0xd8; if (mk_exif) { struct tiff_hdr th; memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); memmove(ret->data + 2, exif, sizeof(exif)); tiff_head(&th, 0); memmove(ret->data + (2 + sizeof(exif)), &th, sizeof(th)); memmove(ret->data + (2 + sizeof(exif) + sizeof(th)), T.thumb + 2, T.tlength - 2); } else { memmove(ret->data + 2, T.thumb + 2, T.tlength - 2); } if (errcode) *errcode = 0; return ret; } else { if (errcode) *errcode = LIBRAW_UNSUPPORTED_THUMBNAIL; return NULL; } } // jlb // macros for copying pixels to either BGR or RGB formats #define FORBGR for (c = P1.colors - 1; c >= 0; c--) #define FORRGB for (c = 0; c < P1.colors; c++) void LibRaw::get_mem_image_format(int *width, int *height, int *colors, int *bps) const { if (S.flip & 4) { *width = S.height; *height = S.width; } else { *width = S.width; *height = S.height; } *colors = P1.colors; *bps = O.output_bps; } int LibRaw::copy_mem_image(void *scan0, int stride, int bgr) { // the image memory pointed to by scan0 is assumed to be in the format returned by get_mem_image_format if ((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) < LIBRAW_PROGRESS_PRE_INTERPOLATE) return LIBRAW_OUT_OF_ORDER_CALL; if (libraw_internal_data.output_data.histogram) { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * O.auto_bright_thr; if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } int s_iheight = S.iheight; int s_iwidth = S.iwidth; int s_width = S.width; int s_hwight = S.height; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, S.width); for (row = 0; row < S.height; row++, soff += rstep) { uchar *bufp = ((uchar *)scan0) + row * stride; ppm2 = (ushort *)(ppm = bufp); // keep trivial decisions in the outer loop for speed if (bgr) { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } else { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } // bufp += stride; // go to the next line } S.iheight = s_iheight; S.iwidth = s_iwidth; S.width = s_width; S.height = s_hwight; return 0; } #undef FORBGR #undef FORRGB libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode) { int width, height, colors, bps; get_mem_image_format(&width, &height, &colors, &bps); int stride = width * (bps / 8) * colors; unsigned ds = height * stride; libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + ds); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); // metadata init ret->type = LIBRAW_IMAGE_BITMAP; ret->height = height; ret->width = width; ret->colors = colors; ret->bits = bps; ret->data_size = ds; copy_mem_image(ret->data, stride, 0); return ret; } #undef FORC #undef FORCC #undef SWAP #endif int LibRaw::dcraw_ppm_tiff_writer(const char *filename) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); if (!imgdata.image) return LIBRAW_OUT_OF_ORDER_CALL; if (!filename) return ENOENT; FILE *f = fopen(filename, "wb"); if (!f) return errno; try { if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_ppm_tiff_writer()"); } libraw_internal_data.internal_data.output = f; write_ppm_tiff(); SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); libraw_internal_data.internal_data.output = NULL; fclose(f); return 0; } catch (LibRaw_exceptions err) { fclose(f); EXCEPTION_HANDLER(err); } } #define THUMB_READ_BEYOND 16384 void LibRaw::kodak_thumb_loader() { INT64 est_datasize = T.theight * T.twidth / 3; // is 0.3 bytes per pixel good estimate? if (ID.toffset < 0) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (ID.toffset + est_datasize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; // some kodak cameras ushort s_height = S.height, s_width = S.width, s_iwidth = S.iwidth, s_iheight = S.iheight; ushort s_flags = libraw_internal_data.unpacker_data.load_flags; libraw_internal_data.unpacker_data.load_flags = 12; int s_colors = P1.colors; unsigned s_filters = P1.filters; ushort(*s_image)[4] = imgdata.image; S.height = T.theight; S.width = T.twidth; P1.filters = 0; if (thumb_load_raw == &CLASS kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "LibRaw::kodak_thumb_loader()"); ID.input->seek(ID.toffset, SEEK_SET); // read kodak thumbnail into T.image[] try { (this->*thumb_load_raw)(); } catch (...) { free(imgdata.image); imgdata.image = s_image; T.twidth = 0; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = 0; S.height = s_height; T.tcolors = 0; P1.colors = s_colors; P1.filters = s_filters; T.tlength = 0; libraw_internal_data.unpacker_data.load_flags = s_flags; return; } // copy-n-paste from image pipe #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #ifndef CLIP #define CLIP(x) LIM(x, 0, 65535) #endif #define SWAP(a, b) \ { \ a ^= b; \ a ^= (b ^= a); \ } // from scale_colors { double dmax; float scale_mul[4]; int c, val; for (dmax = DBL_MAX, c = 0; c < 3; c++) if (dmax > C.pre_mul[c]) dmax = C.pre_mul[c]; for (c = 0; c < 3; c++) scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum; scale_mul[3] = scale_mul[1]; size_t size = S.height * S.width; for (unsigned i = 0; i < size * 4; i++) { val = imgdata.image[0][i]; if (!val) continue; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } // from convert_to_rgb ushort *img; int row, col; int(*t_hist)[LIBRAW_HISTOGRAM_SIZE] = (int(*)[LIBRAW_HISTOGRAM_SIZE])calloc(sizeof(*t_hist), 4); merror(t_hist, "LibRaw::kodak_thumb_loader()"); float out[3], out_cam[3][4] = {{2.81761312, -1.98369181, 0.166078627, 0}, {-0.111855984, 1.73688626, -0.625030339, 0}, {-0.0379119813, -0.891268849, 1.92918086, 0}}; for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { out[0] = out[1] = out[2] = 0; int c; for (c = 0; c < 3; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); for (c = 0; c < P1.colors; c++) t_hist[c][img[c] >> 3]++; } // from gamma_lut int(*save_hist)[LIBRAW_HISTOGRAM_SIZE] = libraw_internal_data.output_data.histogram; libraw_internal_data.output_data.histogram = t_hist; // make curve output curve! ushort(*t_curve) = (ushort *)calloc(sizeof(C.curve), 1); merror(t_curve, "LibRaw::kodak_thumb_loader()"); memmove(t_curve, C.curve, sizeof(C.curve)); memset(C.curve, 0, sizeof(C.curve)); { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } libraw_internal_data.output_data.histogram = save_hist; free(t_hist); // from write_ppm_tiff - copy pixels into bitmap int s_flip = imgdata.sizes.flip; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = 0; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); if (T.thumb) free(T.thumb); T.thumb = (char *)calloc(S.width * S.height, P1.colors); merror(T.thumb, "LibRaw::kodak_thumb_loader()"); T.tlength = S.width * S.height * P1.colors; // from write_tiff_ppm { int soff = flip_index(0, 0); int cstep = flip_index(0, 1) - soff; int rstep = flip_index(1, 0) - flip_index(0, S.width); for (int row = 0; row < S.height; row++, soff += rstep) { char *ppm = T.thumb + row * S.width * P1.colors; for (int col = 0; col < S.width; col++, soff += cstep) for (int c = 0; c < P1.colors; c++) ppm[col * P1.colors + c] = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } } memmove(C.curve, t_curve, sizeof(C.curve)); free(t_curve); // restore variables free(imgdata.image); imgdata.image = s_image; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = s_flip; T.twidth = S.width; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = S.height; S.height = s_height; T.tcolors = P1.colors; P1.colors = s_colors; P1.filters = s_filters; libraw_internal_data.unpacker_data.load_flags = s_flags; } #undef MIN #undef MAX #undef LIM #undef CLIP #undef SWAP // ������� thumbnail �� �����, ������ thumb_format � ������������ � �������� int LibRaw::thumbOK(INT64 maxsz) { if (!ID.input) return 0; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) return 0; INT64 fsize = ID.input->size(); if (fsize > 0x7fffffffU) return 0; // No thumb for raw > 2Gb int tsize = 0; int tcol = (T.tcolors > 0 && T.tcolors < 4) ? T.tcolors : 3; if (write_thumb == &LibRaw::jpeg_thumb) tsize = T.tlength; else if (write_thumb == &LibRaw::ppm_thumb) tsize = tcol * T.twidth * T.theight; else if (write_thumb == &LibRaw::ppm16_thumb) tsize = tcol * T.twidth * T.theight * ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1); else if (write_thumb == &LibRaw::x3f_thumb_loader) { tsize = x3f_thumb_size(); } else // Kodak => no check tsize = 1; if (tsize < 0) return 0; if (maxsz > 0 && tsize > maxsz) return 0; return (tsize + ID.toffset <= fsize) ? 1 : 0; } #ifndef NO_JPEG struct jpegErrorManager { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; longjmp(myerr->setjmp_buffer, 1); } #endif int LibRaw::unpack_thumb(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7; int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { return LIBRAW_NO_THUMBNAIL; } else if (thumb_load_raw) { kodak_thumb_loader(); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { if (write_thumb == &LibRaw::x3f_thumb_loader) { INT64 tsize = x3f_thumb_size(); if (tsize < 2048 || INT64(ID.toffset) + tsize < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } else { if (INT64(ID.toffset) + INT64(T.tlength) < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + INT64(T.tlength) > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } ID.input->seek(ID.toffset, SEEK_SET); if (write_thumb == &LibRaw::jpeg_thumb) { if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "jpeg_thumb()"); ID.input->read(T.thumb, 1, T.tlength); unsigned char *tthumb = (unsigned char *)T.thumb; tthumb[0] = 0xff; tthumb[1] = 0xd8; #ifdef NO_JPEG T.tcolors = 3; #else { jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; if (setjmp(jerr.setjmp_buffer)) { err2: jpeg_destroy_decompress(&cinfo); T.tcolors = 3; } jpeg_create_decompress(&cinfo); jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) goto err2; T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3) ? cinfo.num_components : 3; jpeg_destroy_decompress(&cinfo); } #endif T.tformat = LIBRAW_THUMBNAIL_JPEG; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm_thumb) { if (t_bytesps > 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more bits int t_length = T.twidth * T.theight * t_colors; if (T.tlength && T.tlength < t_length) // try to find tiff ifd with needed offset { int pifd = -1; for (int ii = 0; ii < libraw_internal_data.identify_data.tiff_nifds && ii < LIBRAW_IFD_MAXCOUNT; ii++) if (tiff_ifd[ii].offset == libraw_internal_data.internal_data.toffset) // found { pifd = ii; break; } if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count && tiff_ifd[pifd].strip_byte_counts_count) { // We found it, calculate final size unsigned total_size = 0; for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++) total_size += tiff_ifd[pifd].strip_byte_counts[i]; if (total_size != t_length) // recalculate colors { if (total_size == T.twidth * T.tlength * 3) T.tcolors = 3; else if (total_size == T.twidth * T.tlength) T.tcolors = 1; } T.tlength = total_size; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "ppm_thumb()"); char *dest = T.thumb; INT64 pos = ID.input->tell(); for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count && i < tiff_ifd[pifd].strip_offsets_count; i++) { int remain = T.tlength; int sz = tiff_ifd[pifd].strip_byte_counts[i]; int off = tiff_ifd[pifd].strip_offsets[i]; if (off >= 0 && off + sz <= ID.input->size() && sz <= remain) { ID.input->seek(off, SEEK_SET); ID.input->read(dest, sz, 1); remain -= sz; dest += sz; } } ID.input->seek(pos, SEEK_SET); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } } if (!T.tlength) T.tlength = t_length; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); if (!T.tcolors) T.tcolors = t_colors; merror(T.thumb, "ppm_thumb()"); ID.input->read(T.thumb, 1, T.tlength); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm16_thumb) { if (t_bytesps > 2) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for more bits int o_bps = (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1; int o_length = T.twidth * T.theight * t_colors * o_bps; int i_length = T.twidth * T.theight * t_colors * 2; if (!T.tlength) T.tlength = o_length; ushort *t_thumb = (ushort *)calloc(i_length, 1); ID.input->read(t_thumb, 1, i_length); if ((libraw_internal_data.unpacker_data.order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)t_thumb, (char *)t_thumb, i_length); if (T.thumb) free(T.thumb); if ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS)) { T.thumb = (char *)t_thumb; T.tformat = LIBRAW_THUMBNAIL_BITMAP16; } else { T.thumb = (char *)malloc(o_length); merror(T.thumb, "ppm_thumb()"); for (int i = 0; i < o_length; i++) T.thumb[i] = t_thumb[i] >> 8; free(t_thumb); T.tformat = LIBRAW_THUMBNAIL_BITMAP; } SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::x3f_thumb_loader) { x3f_thumb_loader(); SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { return LIBRAW_UNSUPPORTED_THUMBNAIL; } } // last resort return LIBRAW_UNSUPPORTED_THUMBNAIL; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } int LibRaw::dcraw_thumb_writer(const char *fname) { // CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD); if (!fname) return ENOENT; FILE *tfp = fopen(fname, "wb"); if (!tfp) return errno; if (!T.thumb) { fclose(tfp); return LIBRAW_OUT_OF_ORDER_CALL; } try { switch (T.tformat) { case LIBRAW_THUMBNAIL_JPEG: jpeg_thumb_writer(tfp, T.thumb, T.tlength); break; case LIBRAW_THUMBNAIL_BITMAP: fprintf(tfp, "P6\n%d %d\n255\n", T.twidth, T.theight); fwrite(T.thumb, 1, T.tlength, tfp); break; default: fclose(tfp); return LIBRAW_UNSUPPORTED_THUMBNAIL; } fclose(tfp); return 0; } catch (LibRaw_exceptions err) { fclose(tfp); EXCEPTION_HANDLER(err); } } int LibRaw::adjust_sizes_info_only(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); raw2image_start(); if (O.use_fuji_rotate) { if (IO.fuji_width) { IO.fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink; S.iwidth = (ushort)(IO.fuji_width / sqrt(0.5)); S.iheight = (ushort)((S.iheight - IO.fuji_width) / sqrt(0.5)); } else { if (S.pixel_aspect < 0.995) S.iheight = (ushort)(S.iheight / S.pixel_aspect + 0.5); if (S.pixel_aspect > 1.005) S.iwidth = (ushort)(S.iwidth * S.pixel_aspect + 0.5); } } SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); if (S.flip & 4) { unsigned short t = S.iheight; S.iheight = S.iwidth; S.iwidth = t; SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); } return 0; } int LibRaw::subtract_black() { adjust_bl(); return subtract_black_internal(); } int LibRaw::subtract_black_internal() { CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE); try { if (!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3] || (C.cblack[4] && C.cblack[5]))) { #define BAYERC(row, col, c) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][c] int cblk[4], i; for (i = 0; i < 4; i++) cblk[i] = C.cblack[i]; int size = S.iheight * S.iwidth; #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define CLIP(x) LIM(x, 0, 65535) int dmax = 0; if (C.cblack[4] && C.cblack[5]) { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } else { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } C.data_maximum = dmax & 0xffff; #undef MIN #undef MAX #undef LIM #undef CLIP C.maximum -= C.black; ZERO(C.cblack); // Yeah, we used cblack[6+] values too! C.black = 0; #undef BAYERC } else { // Nothing to Do, maximum is already calculated, black level is 0, so no change // only calculate channel maximum; int idx; ushort *p = (ushort *)imgdata.image; int dmax = 0; for (idx = 0; idx < S.iheight * S.iwidth * 4; idx++) if (dmax < p[idx]) dmax = p[idx]; C.data_maximum = dmax; } return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #define TBLN 65535 void LibRaw::exp_bef(float shift, float smooth) { // params limits if (shift > 8) shift = 8; if (shift < 0.25) shift = 0.25; if (smooth < 0.0) smooth = 0.0; if (smooth > 1.0) smooth = 1.0; unsigned short *lut = (ushort *)malloc((TBLN + 1) * sizeof(unsigned short)); if (shift <= 1.0) { for (int i = 0; i <= TBLN; i++) lut[i] = (unsigned short)((float)i * shift); } else { float x1, x2, y1, y2; float cstops = log(shift) / log(2.0f); float room = cstops * 2; float roomlin = powf(2.0f, room); x2 = (float)TBLN; x1 = (x2 + 1) / roomlin - 1; y1 = x1 * shift; y2 = x2 * (1 + (1 - smooth) * (shift - 1)); float sq3x = powf(x1 * x1 * x2, 1.0f / 3.0f); float B = (y2 - y1 + shift * (3 * x1 - 3.0f * sq3x)) / (x2 + 2.0f * x1 - 3.0f * sq3x); float A = (shift - B) * 3.0f * powf(x1 * x1, 1.0f / 3.0f); float CC = y2 - A * powf(x2, 1.0f / 3.0f) - B * x2; for (int i = 0; i <= TBLN; i++) { float X = (float)i; float Y = A * powf(X, 1.0f / 3.0f) + B * X + CC; if (i < x1) lut[i] = (unsigned short)((float)i * shift); else lut[i] = Y < 0 ? 0 : (Y > TBLN ? TBLN : (unsigned short)(Y)); } } for (int i = 0; i < S.height * S.width; i++) { imgdata.image[i][0] = lut[imgdata.image[i][0]]; imgdata.image[i][1] = lut[imgdata.image[i][1]]; imgdata.image[i][2] = lut[imgdata.image[i][2]]; imgdata.image[i][3] = lut[imgdata.image[i][3]]; } if (C.data_maximum <= TBLN) C.data_maximum = lut[C.data_maximum]; if (C.maximum <= TBLN) C.maximum = lut[C.maximum]; free(lut); } #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y)) #define CLIP(x) LIM(x, 0, 65535) void LibRaw::convert_to_rgb_loop(float out_cam[3][4]) { int row, col, c; float out[3]; ushort *img; memset(libraw_internal_data.output_data.histogram, 0, sizeof(int) * LIBRAW_HISTOGRAM_SIZE * 4); for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { if (!libraw_internal_data.internal_output_params.raw_color) { out[0] = out[1] = out[2] = 0; for (c = 0; c < imgdata.idata.colors; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); } for (c = 0; c < imgdata.idata.colors; c++) libraw_internal_data.output_data.histogram[c][img[c] >> 3]++; } } void LibRaw::scale_colors_loop(float scale_mul[4]) { unsigned size = S.iheight * S.iwidth; if (C.cblack[4] && C.cblack[5]) { int val; for (unsigned i = 0; i < size * 4; i++) { if (!(val = imgdata.image[0][i])) continue; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else if (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3]) { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; if (!val) continue; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else // BL is zero { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } } void LibRaw::adjust_bl() { int clear_repeat = 0; if (O.user_black >= 0) { C.black = O.user_black; clear_repeat = 1; } for (int i = 0; i < 4; i++) if (O.user_cblack[i] > -1000000) { C.cblack[i] = O.user_cblack[i]; clear_repeat = 1; } if (clear_repeat) C.cblack[4] = C.cblack[5] = 0; // Add common part to cblack[] early if (imgdata.idata.filters > 1000 && (C.cblack[4] + 1) / 2 == 1 && (C.cblack[5] + 1) / 2 == 1) { int clrs[4]; int lastg = -1, gcnt = 0; for (int c = 0; c < 4; c++) { clrs[c] = FC(c / 2, c % 2); if (clrs[c] == 1) { gcnt++; lastg = c; } } if (gcnt > 1 && lastg >= 0) clrs[lastg] = 3; for (int c = 0; c < 4; c++) C.cblack[clrs[c]] += C.cblack[6 + c / 2 % C.cblack[4] * C.cblack[5] + c % 2 % C.cblack[5]]; C.cblack[4] = C.cblack[5] = 0; // imgdata.idata.filters = sfilters; } else if (imgdata.idata.filters <= 1000 && C.cblack[4] == 1 && C.cblack[5] == 1) // Fuji RAF dng { for (int c = 0; c < 4; c++) C.cblack[c] += C.cblack[6]; C.cblack[4] = C.cblack[5] = 0; } // remove common part from C.cblack[] int i = C.cblack[3]; int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; // remove common part C.black += i; // Now calculate common part for cblack[6+] part and move it to C.black if (C.cblack[4] && C.cblack[5]) { i = C.cblack[6]; for (c = 1; c < C.cblack[4] * C.cblack[5]; c++) if (i > C.cblack[6 + c]) i = C.cblack[6 + c]; // Remove i from cblack[6+] int nonz = 0; for (c = 0; c < C.cblack[4] * C.cblack[5]; c++) { C.cblack[6 + c] -= i; if (C.cblack[6 + c]) nonz++; } C.black += i; if (!nonz) C.cblack[4] = C.cblack[5] = 0; } for (c = 0; c < 4; c++) C.cblack[c] += C.black; } int LibRaw::dcraw_process(void) { int quality, i; int iterations = -1, dcb_enhance = 1, noiserd = 0; int eeci_refine_fl = 0, es_med_passes_fl = 0; float cared = 0, cablue = 0; float linenoise = 0; float lclean = 0, cclean = 0; float thresh = 0; float preser = 0; float expos = 1.0; CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); // CHECK_ORDER_HIGH(LIBRAW_PROGRESS_PRE_INTERPOLATE); try { int no_crop = 1; if (~O.cropbox[2] && ~O.cropbox[3]) no_crop = 0; libraw_decoder_info_t di; get_decoder_info(&di); bool is_bayer = (imgdata.idata.filters || P1.colors == 1); int subtract_inline = !O.bad_pixels && !O.dark_frame && is_bayer && !IO.zero_is_bad; raw2image_ex(subtract_inline); // allocate imgdata.image and copy data! // Adjust sizes int save_4color = O.four_color_rgb; if (IO.zero_is_bad) { remove_zeroes(); SET_PROC_FLAG(LIBRAW_PROGRESS_REMOVE_ZEROES); } if (O.bad_pixels && no_crop) { bad_pixels(O.bad_pixels); SET_PROC_FLAG(LIBRAW_PROGRESS_BAD_PIXELS); } if (O.dark_frame && no_crop) { subtract(O.dark_frame); SET_PROC_FLAG(LIBRAW_PROGRESS_DARK_FRAME); } /* pre subtract black callback: check for it above to disable subtract inline */ if(callbacks.pre_subtractblack_cb) (callbacks.pre_subtractblack_cb)(this); quality = 2 + !IO.fuji_width; if (O.user_qual >= 0) quality = O.user_qual; if (!subtract_inline || !C.data_maximum) { adjust_bl(); subtract_black_internal(); } if (!(di.decoder_flags & LIBRAW_DECODER_FIXEDMAXC)) adjust_maximum(); if (O.user_sat > 0) C.maximum = O.user_sat; if (P1.is_foveon) { if (load_raw == &LibRaw::x3f_load_raw) { // Filter out zeroes for (int i = 0; i < S.height * S.width * 4; i++) if ((short)imgdata.image[0][i] < 0) imgdata.image[0][i] = 0; } SET_PROC_FLAG(LIBRAW_PROGRESS_FOVEON_INTERPOLATE); } if (O.green_matching && !O.half_size) { green_matching(); } if(callbacks.pre_scalecolors_cb) (callbacks.pre_scalecolors_cb)(this); if (!O.no_auto_scale) { scale_colors(); SET_PROC_FLAG(LIBRAW_PROGRESS_SCALE_COLORS); } if(callbacks.pre_preinterpolate_cb) (callbacks.pre_preinterpolate_cb)(this); pre_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_PRE_INTERPOLATE); if (O.dcb_iterations >= 0) iterations = O.dcb_iterations; if (O.dcb_enhance_fl >= 0) dcb_enhance = O.dcb_enhance_fl; if (O.fbdd_noiserd >= 0) noiserd = O.fbdd_noiserd; /* pre-exposure correction callback */ if (O.exp_correc > 0) { expos = O.exp_shift; preser = O.exp_preser; exp_bef(expos, preser); } if(callbacks.pre_interpolate_cb) (callbacks.pre_interpolate_cb)(this); /* post-exposure correction fallback */ if (P1.filters && !O.no_interpolation) { if (noiserd > 0 && P1.colors == 3 && P1.filters) fbdd(noiserd); if (P1.filters > 1000 && callbacks.interpolate_bayer_cb) (callbacks.interpolate_bayer_cb)(this); else if (P1.filters == 9 && callbacks.interpolate_xtrans_cb) (callbacks.interpolate_xtrans_cb)(this); else if (quality == 0) lin_interpolate(); else if (quality == 1 || P1.colors > 3) vng_interpolate(); else if (quality == 2 && P1.filters > 1000) ppg_interpolate(); else if (P1.filters == LIBRAW_XTRANS) { // Fuji X-Trans xtrans_interpolate(quality > 2 ? 3 : 1); } else if (quality == 3) ahd_interpolate(); // really don't need it here due to fallback op else if (quality == 4) dcb(iterations, dcb_enhance); else if (quality == 11) dht_interpolate(); else if (quality == 12) aahd_interpolate(); // fallback to AHD else { ahd_interpolate(); imgdata.process_warnings |= LIBRAW_WARN_FALLBACK_TO_AHD; } SET_PROC_FLAG(LIBRAW_PROGRESS_INTERPOLATE); } if (IO.mix_green) { for (P1.colors = 3, i = 0; i < S.height * S.width; i++) imgdata.image[i][1] = (imgdata.image[i][1] + imgdata.image[i][3]) >> 1; SET_PROC_FLAG(LIBRAW_PROGRESS_MIX_GREEN); } if(callbacks.post_interpolate_cb) (callbacks.post_interpolate_cb)(this); if (!P1.is_foveon) { if (P1.colors == 3) { /* median filter callback, if not set use own */ median_filter(); SET_PROC_FLAG(LIBRAW_PROGRESS_MEDIAN_FILTER); } } if (O.highlight == 2) { blend_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.highlight > 2) { recover_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.use_fuji_rotate) { fuji_rotate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); } if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_process()"); } #ifndef NO_LCMS if (O.camera_profile) { apply_profile(O.camera_profile, O.output_profile); SET_PROC_FLAG(LIBRAW_PROGRESS_APPLY_PROFILE); } #endif if(callbacks.pre_converttorgb_cb) (callbacks.pre_converttorgb_cb)(this); convert_to_rgb(); SET_PROC_FLAG(LIBRAW_PROGRESS_CONVERT_RGB); if(callbacks.post_converttorgb_cb) (callbacks.post_converttorgb_cb)(this); if (O.use_fuji_rotate) { stretch(); SET_PROC_FLAG(LIBRAW_PROGRESS_STRETCH); } O.four_color_rgb = save_4color; // also, restore return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } // clang-format off // Supported cameras: static const char *static_camera_list[] = { "Adobe Digital Negative (DNG)", "AgfaPhoto DC-833m", "Alcatel 5035D", "Apple iPad Pro", "Apple iPhone SE", "Apple iPhone 6s", "Apple iPhone 6 plus", "Apple iPhone 7", "Apple iPhone 7 plus", "Apple iPhone 8", "Apple iPhone 8 plus", "Apple iPhone X", "Apple QuickTake 100", "Apple QuickTake 150", "Apple QuickTake 200", "ARRIRAW format", "AVT F-080C", "AVT F-145C", "AVT F-201C", "AVT F-510C", "AVT F-810C", "Baumer TXG14", "BlackMagic Cinema Camera", "BlackMagic Micro Cinema Camera", "BlackMagic Pocket Cinema Camera", "BlackMagic Production Camera 4k", "BlackMagic URSA", "BlackMagic URSA Mini 4k", "BlackMagic URSA Mini 4.6k", "BlackMagic URSA Mini Pro 4.6k", "Canon PowerShot 600", "Canon PowerShot A5", "Canon PowerShot A5 Zoom", "Canon PowerShot A50", "Canon PowerShot A410 (CHDK hack)", "Canon PowerShot A460 (CHDK hack)", "Canon PowerShot A470 (CHDK hack)", "Canon PowerShot A530 (CHDK hack)", "Canon PowerShot A540 (CHDK hack)", "Canon PowerShot A550 (CHDK hack)", "Canon PowerShot A570 (CHDK hack)", "Canon PowerShot A590 (CHDK hack)", "Canon PowerShot A610 (CHDK hack)", "Canon PowerShot A620 (CHDK hack)", "Canon PowerShot A630 (CHDK hack)", "Canon PowerShot A640 (CHDK hack)", "Canon PowerShot A650 (CHDK hack)", "Canon PowerShot A710 IS (CHDK hack)", "Canon PowerShot A720 IS (CHDK hack)", "Canon PowerShot A3300 IS (CHDK hack)", "Canon PowerShot D10 (CHDK hack)", "Canon PowerShot ELPH 130 IS (CHDK hack)", "Canon PowerShot ELPH 160 IS (CHDK hack)", "Canon PowerShot Pro70", "Canon PowerShot Pro90 IS", "Canon PowerShot Pro1", "Canon PowerShot G1", "Canon PowerShot G1 X", "Canon PowerShot G1 X Mark II", "Canon PowerShot G1 X Mark III", "Canon PowerShot G2", "Canon PowerShot G3", "Canon PowerShot G3 X", "Canon PowerShot G5", "Canon PowerShot G5 X", "Canon PowerShot G6", "Canon PowerShot G7 (CHDK hack)", "Canon PowerShot G7 X", "Canon PowerShot G7 X Mark II", "Canon PowerShot G9", "Canon PowerShot G9 X", "Canon PowerShot G9 X Mark II", "Canon PowerShot G10", "Canon PowerShot G11", "Canon PowerShot G12", "Canon PowerShot G15", "Canon PowerShot G16", "Canon PowerShot S2 IS (CHDK hack)", "Canon PowerShot S3 IS (CHDK hack)", "Canon PowerShot S5 IS (CHDK hack)", "Canon PowerShot SD300 (CHDK hack)", "Canon PowerShot SD750 (CHDK hack)", "Canon PowerShot SD950 (CHDK hack)", "Canon PowerShot S30", "Canon PowerShot S40", "Canon PowerShot S45", "Canon PowerShot S50", "Canon PowerShot S60", "Canon PowerShot S70", "Canon PowerShot S90", "Canon PowerShot S95", "Canon PowerShot S100", "Canon PowerShot S110", "Canon PowerShot S120", "Canon PowerShot SX1 IS", "Canon PowerShot SX50 HS", "Canon PowerShot SX60 HS", "Canon PowerShot SX100 IS (CHDK hack)", "Canon PowerShot SX110 IS (CHDK hack)", "Canon PowerShot SX120 IS (CHDK hack)", "Canon PowerShot SX130 IS (CHDK hack)", "Canon PowerShot SX160 IS (CHDK hack)", "Canon PowerShot SX220 HS (CHDK hack)", "Canon PowerShot SX510 HS (CHDK hack)", "Canon PowerShot SX10 IS (CHDK hack)", "Canon PowerShot SX20 IS (CHDK hack)", "Canon PowerShot SX30 IS (CHDK hack)", "Canon PowerShot IXUS 160 (CHDK hack)", "Canon PowerShot IXUS 900Ti (CHDK hack)", "Canon EOS D30", "Canon EOS D60", "Canon EOS 5D", "Canon EOS 5DS", "Canon EOS 5DS R", "Canon EOS 5D Mark II", "Canon EOS 5D Mark III", "Canon EOS 5D Mark IV", "Canon EOS 6D", "Canon EOS 6D Mark II", "Canon EOS 7D", "Canon EOS 7D Mark II", "Canon EOS 10D", "Canon EOS 20D", "Canon EOS 20Da", "Canon EOS 30D", "Canon EOS 40D", "Canon EOS 50D", "Canon EOS 60D", "Canon EOS 60Da", "Canon EOS 70D", "Canon EOS 77D", "Canon EOS 80D", "Canon EOS 200D", "Canon EOS 300D / Digital Rebel / Kiss Digital", "Canon EOS 350D / Digital Rebel XT / Kiss Digital N", "Canon EOS 400D / Digital Rebel XTi / Kiss Digital X", "Canon EOS 450D / Digital Rebel XSi / Kiss Digital X2", "Canon EOS 500D / Digital Rebel T1i / Kiss Digital X3", "Canon EOS 550D / Digital Rebel T2i / Kiss Digital X4", "Canon EOS 600D / Digital Rebel T3i / Kiss Digital X5", "Canon EOS 650D / Digital Rebel T4i / Kiss Digital X6i", "Canon EOS 700D / Digital Rebel T5i", "Canon EOS 750D / Digital Rebel T6i", "Canon EOS 760D / Digital Rebel T6S", "Canon EOS 800D", "Canon EOS 100D / Digital Rebel SL1", "Canon EOS 1000D / Digital Rebel XS / Kiss Digital F", "Canon EOS 1100D / Digital Rebel T3 / Kiss Digital X50", "Canon EOS 1200D", "Canon EOS 1300D", "Canon EOS C500", "Canon EOS D2000C", "Canon EOS M", "Canon EOS M2", "Canon EOS M3", "Canon EOS M5", "Canon EOS M6", "Canon EOS M10", "Canon EOS M100", "Canon EOS-1D", "Canon EOS-1DS", "Canon EOS-1D C", "Canon EOS-1D X", "Canon EOS-1D Mark II", "Canon EOS-1D Mark II N", "Canon EOS-1D Mark III", "Canon EOS-1D Mark IV", "Canon EOS-1Ds Mark II", "Canon EOS-1Ds Mark III", "Canon EOS-1D X Mark II", "Casio QV-2000UX", "Casio QV-3000EX", "Casio QV-3500EX", "Casio QV-4000", "Casio QV-5700", "Casio QV-R41", "Casio QV-R51", "Casio QV-R61", "Casio EX-F1", "Casio EX-FC300S", "Casio EX-FC400S", "Casio EX-FH20", "Casio EX-FH25", "Casio EX-FH100", "Casio EX-P600", "Casio EX-S20", "Casio EX-S100", "Casio EX-Z4", "Casio EX-Z50", "Casio EX-Z500", "Casio EX-Z55", "Casio EX-Z60", "Casio EX-Z75", "Casio EX-Z750", "Casio EX-Z8", "Casio EX-Z850", "Casio EX-Z1050", "Casio EX-ZR100", "Casio EX-Z1080", "Casio EX-ZR700", "Casio EX-ZR710", "Casio EX-ZR750", "Casio EX-ZR800", "Casio EX-ZR850", "Casio EX-ZR1000", "Casio EX-ZR1100", "Casio EX-ZR1200", "Casio EX-ZR1300", "Casio EX-ZR1500", "Casio EX-ZR3000", "Casio EX-ZR4000/5000", "Casio EX-ZR4100/5100", "Casio EX-100", "Casio EX-100F", "Casio EX-10", "Casio Exlim Pro 505", "Casio Exlim Pro 600", "Casio Exlim Pro 700", "Contax N Digital", "Creative PC-CAM 600", "Digital Bolex D16", "Digital Bolex D16M", "DJI 4384x3288", "DJI Phantom4 Pro/Pro+", "DJI Zenmuse X5", "DJI Zenmuse X5R", "DXO One", "Epson R-D1", "Epson R-D1s", "Epson R-D1x", "Foculus 531C", "FujiFilm E505", "FujiFilm E550", "FujiFilm E900", "FujiFilm F700", "FujiFilm F710", "FujiFilm F800", "FujiFilm F810", "FujiFilm S2Pro", "FujiFilm S3Pro", "FujiFilm S5Pro", "FujiFilm S20Pro", "FujiFilm S1", "FujiFilm S100FS", "FujiFilm S5000", "FujiFilm S5100/S5500", "FujiFilm S5200/S5600", "FujiFilm S6000fd", "FujiFilm S6500fd", "FujiFilm S7000", "FujiFilm S9000/S9500", "FujiFilm S9100/S9600", "FujiFilm S200EXR", "FujiFilm S205EXR", "FujiFilm SL1000", "FujiFilm HS10/HS11", "FujiFilm HS20EXR", "FujiFilm HS22EXR", "FujiFilm HS30EXR", "FujiFilm HS33EXR", "FujiFilm HS35EXR", "FujiFilm HS50EXR", "FujiFilm F505EXR", "FujiFilm F550EXR", "FujiFilm F600EXR", "FujiFilm F605EXR", "FujiFilm F770EXR", "FujiFilm F775EXR", "FujiFilm F800EXR", "FujiFilm F900EXR", "FujiFilm GFX 50S", "FujiFilm X-Pro1", "FujiFilm X-Pro2", "FujiFilm X-S1", "FujiFilm XQ1", "FujiFilm XQ2", "FujiFilm X100", "FujiFilm X100f", "FujiFilm X100S", "FujiFilm X100T", "FujiFilm X10", "FujiFilm X20", "FujiFilm X30", "FujiFilm X70", "FujiFilm X-A1", "FujiFilm X-A2", "FujiFilm X-A3", "FujiFilm X-A5", "FujiFilm X-A10", "FujiFilm X-A20", "FujiFilm X-E1", "FujiFilm X-E2", "FujiFilm X-E2S", "FujiFilm X-E3", "FujiFilm X-M1", "FujiFilm XF1", "FujiFilm X-H1", "FujiFilm X-T1", "FujiFilm X-T1 Graphite Silver", "FujiFilm X-T2", "FujiFilm X-T10", "FujiFilm X-T20", "FujiFilm IS-1", "Gione E7", "GITUP GIT2", "GITUP GIT2P", "Google Pixel", "Google Pixel XL", "Hasselblad H2D-22", "Hasselblad H2D-39", "Hasselblad H3DII-22", "Hasselblad H3DII-31", "Hasselblad H3DII-39", "Hasselblad H3DII-50", "Hasselblad H3D-22", "Hasselblad H3D-31", "Hasselblad H3D-39", "Hasselblad H4D-60", "Hasselblad H4D-50", "Hasselblad H4D-40", "Hasselblad H4D-31", "Hasselblad H5D-60", "Hasselblad H5D-50", "Hasselblad H5D-50c", "Hasselblad H5D-40", "Hasselblad H6D-100c", "Hasselblad A6D-100c", // Aerial camera "Hasselblad CFV", "Hasselblad CFV-50", "Hasselblad CFH", "Hasselblad CF-22", "Hasselblad CF-31", "Hasselblad CF-39", "Hasselblad V96C", "Hasselblad Lusso", "Hasselblad Lunar", "Hasselblad True Zoom", "Hasselblad Stellar", "Hasselblad Stellar II", "Hasselblad HV", "Hasselblad X1D", "HTC UltraPixel", "HTC MyTouch 4G", "HTC One (A9)", "HTC One (M9)", "HTC 10", "Huawei P9 (EVA-L09/AL00)", "Huawei Honor6a", "Huawei Honor9", "Huawei Mate10 (BLA-L29)", "Imacon Ixpress 96, 96C", "Imacon Ixpress 384, 384C (single shot only)", "Imacon Ixpress 132C", "Imacon Ixpress 528C (single shot only)", "ISG 2020x1520", "Ikonoskop A-Cam dII Panchromatic", "Ikonoskop A-Cam dII", "Kinefinity KineMINI", "Kinefinity KineRAW Mini", "Kinefinity KineRAW S35", "Kodak DC20", "Kodak DC25", "Kodak DC40", "Kodak DC50", "Kodak DC120", "Kodak DCS200", "Kodak DCS315C", "Kodak DCS330C", "Kodak DCS420", "Kodak DCS460", "Kodak DCS460A", "Kodak DCS460D", "Kodak DCS520C", "Kodak DCS560C", "Kodak DCS620C", "Kodak DCS620X", "Kodak DCS660C", "Kodak DCS660M", "Kodak DCS720X", "Kodak DCS760C", "Kodak DCS760M", "Kodak EOSDCS1", "Kodak EOSDCS3B", "Kodak NC2000F", "Kodak ProBack", "Kodak PB645C", "Kodak PB645H", "Kodak PB645M", "Kodak DCS Pro 14n", "Kodak DCS Pro 14nx", "Kodak DCS Pro SLR/c", "Kodak DCS Pro SLR/n", "Kodak C330", "Kodak C603", "Kodak P850", "Kodak P880", "Kodak S-1", "Kodak Z980", "Kodak Z981", "Kodak Z990", "Kodak Z1015", "Kodak KAI-0340", "Konica KD-400Z", "Konica KD-510Z", "Leaf AFi 5", "Leaf AFi 6", "Leaf AFi 7", "Leaf AFi-II 6", "Leaf AFi-II 7", "Leaf AFi-II 10", "Leaf AFi-II 10R", "Leaf Aptus-II 5", "Leaf Aptus-II 6", "Leaf Aptus-II 7", "Leaf Aptus-II 8", "Leaf Aptus-II 10", "Leaf Aptus-II 12", "Leaf Aptus-II 12R", "Leaf Aptus 17", "Leaf Aptus 22", "Leaf Aptus 54S", "Leaf Aptus 65", "Leaf Aptus 65S", "Leaf Aptus 75", "Leaf Aptus 75S", "Leaf Cantare", "Leaf Cantare XY", "Leaf CatchLight", "Leaf CMost", "Leaf Credo 40", "Leaf Credo 50", "Leaf Credo 60", "Leaf Credo 80 (low compression mode only)", "Leaf DCB-II", "Leaf Valeo 6", "Leaf Valeo 11", "Leaf Valeo 17", "Leaf Valeo 17wi", "Leaf Valeo 22", "Leaf Valeo 22wi", "Leaf Volare", "Lenovo a820", "Leica C (Typ 112)", "Leica CL", "Leica Digilux 2", "Leica Digilux 3", "Leica Digital-Modul-R", "Leica D-LUX2", "Leica D-LUX3", "Leica D-LUX4", "Leica D-LUX5", "Leica D-LUX6", "Leica D-Lux (Typ 109)", "Leica M8", "Leica M8.2", "Leica M9", "Leica M10", "Leica M (Typ 240)", "Leica M (Typ 262)", "Leica Monochrom (Typ 240)", "Leica Monochrom (Typ 246)", "Leica M-D (Typ 262)", "Leica M-E", "Leica M-P", "Leica R8", "Leica Q (Typ 116)", "Leica S", "Leica S2", "Leica S (Typ 007)", "Leica SL (Typ 601)", "Leica T (Typ 701)", "Leica TL", "Leica TL2", "Leica X1", "Leica X (Typ 113)", "Leica X2", "Leica X-E (Typ 102)", "Leica X-U (Typ 113)", "Leica V-LUX1", "Leica V-LUX2", "Leica V-LUX3", "Leica V-LUX4", "Leica V-Lux (Typ 114)", "Leica X VARIO (Typ 107)", "LG G3", "LG G4", "LG V20 (F800K)", "LG VS995", "Logitech Fotoman Pixtura", "Mamiya ZD", "Matrix 4608x3288", "Meizy MX4", "Micron 2010", "Minolta RD175", "Minolta DiMAGE 5", "Minolta DiMAGE 7", "Minolta DiMAGE 7i", "Minolta DiMAGE 7Hi", "Minolta DiMAGE A1", "Minolta DiMAGE A2", "Minolta DiMAGE A200", "Minolta DiMAGE G400", "Minolta DiMAGE G500", "Minolta DiMAGE G530", "Minolta DiMAGE G600", "Minolta DiMAGE Z2", "Minolta Alpha/Dynax/Maxxum 5D", "Minolta Alpha/Dynax/Maxxum 7D", "Motorola PIXL", "Nikon D1", "Nikon D1H", "Nikon D1X", "Nikon D2H", "Nikon D2Hs", "Nikon D2X", "Nikon D2Xs", "Nikon D3", "Nikon D3s", "Nikon D3X", "Nikon D4", "Nikon D4s", "Nikon D40", "Nikon D40X", "Nikon D5", "Nikon D50", "Nikon D60", "Nikon D70", "Nikon D70s", "Nikon D80", "Nikon D90", "Nikon D100", "Nikon D200", "Nikon D300", "Nikon D300s", "Nikon D500", "Nikon D600", "Nikon D610", "Nikon D700", "Nikon D750", "Nikon D800", "Nikon D800E", "Nikon D810", "Nikon D810A", "Nikon D850", "Nikon D3000", "Nikon D3100", "Nikon D3200", "Nikon D3300", "Nikon D3400", "Nikon D5000", "Nikon D5100", "Nikon D5200", "Nikon D5300", "Nikon D5500", "Nikon D5600", "Nikon D7000", "Nikon D7100", "Nikon D7200", "Nikon D7500", "Nikon Df", "Nikon 1 AW1", "Nikon 1 J1", "Nikon 1 J2", "Nikon 1 J3", "Nikon 1 J4", "Nikon 1 J5", "Nikon 1 S1", "Nikon 1 S2", "Nikon 1 V1", "Nikon 1 V2", "Nikon 1 V3", "Nikon E700 (\"DIAG RAW\" hack)", "Nikon E800 (\"DIAG RAW\" hack)", "Nikon E880 (\"DIAG RAW\" hack)", "Nikon E900 (\"DIAG RAW\" hack)", "Nikon E950 (\"DIAG RAW\" hack)", "Nikon E990 (\"DIAG RAW\" hack)", "Nikon E995 (\"DIAG RAW\" hack)", "Nikon E2100 (\"DIAG RAW\" hack)", "Nikon E2500 (\"DIAG RAW\" hack)", "Nikon E3200 (\"DIAG RAW\" hack)", "Nikon E3700 (\"DIAG RAW\" hack)", "Nikon E4300 (\"DIAG RAW\" hack)", "Nikon E4500 (\"DIAG RAW\" hack)", "Nikon E5000", "Nikon E5400", "Nikon E5700", "Nikon E8400", "Nikon E8700", "Nikon E8800", "Nikon Coolpix A", "Nikon Coolpix B700", "Nikon Coolpix P330", "Nikon Coolpix P340", "Nikon Coolpix P6000", "Nikon Coolpix P7000", "Nikon Coolpix P7100", "Nikon Coolpix P7700", "Nikon Coolpix P7800", "Nikon Coolpix S6 (\"DIAG RAW\" hack)", "Nikon Coolscan NEF", "Nokia N95", "Nokia X2", "Nokia 1200x1600", "Nokia Lumia 950 XL", "Nokia Lumia 1020", "Nokia Lumia 1520", "Olympus AIR A01", "Olympus C3030Z", "Olympus C5050Z", "Olympus C5060Z", "Olympus C7070WZ", "Olympus C70Z,C7000Z", "Olympus C740UZ", "Olympus C770UZ", "Olympus C8080WZ", "Olympus X200,D560Z,C350Z", "Olympus E-1", "Olympus E-3", "Olympus E-5", "Olympus E-10", "Olympus E-20", "Olympus E-30", "Olympus E-300", "Olympus E-330", "Olympus E-400", "Olympus E-410", "Olympus E-420", "Olympus E-450", "Olympus E-500", "Olympus E-510", "Olympus E-520", "Olympus E-600", "Olympus E-620", "Olympus E-P1", "Olympus E-P2", "Olympus E-P3", "Olympus E-P5", "Olympus E-PL1", "Olympus E-PL1s", "Olympus E-PL2", "Olympus E-PL3", "Olympus E-PL5", "Olympus E-PL6", "Olympus E-PL7", "Olympus E-PL8", "Olympus E-PL9", "Olympus E-PM1", "Olympus E-PM2", "Olympus E-M1", "Olympus E-M1 Mark II", "Olympus E-M10", "Olympus E-M10 Mark II", "Olympus E-M10 Mark III", "Olympus E-M5", "Olympus E-M5 Mark II", "Olympus Pen F", "Olympus SP310", "Olympus SP320", "Olympus SP350", "Olympus SP500UZ", "Olympus SP510UZ", "Olympus SP550UZ", "Olympus SP560UZ", "Olympus SP565UZ", "Olympus SP570UZ", "Olympus STYLUS1", "Olympus STYLUS1s", "Olympus SH-2", "Olympus SH-3", "Olympus TG-4", "Olympus TG-5", "Olympus XZ-1", "Olympus XZ-2", "Olympus XZ-10", "OmniVision 4688", "OmniVision OV5647", "OmniVision OV5648", "OmniVision OV8850", "OmniVision 13860", "OnePlus One", "OnePlus A3303", "OnePlus A5000", "Panasonic DMC-CM1", "Panasonic DMC-FZ8", "Panasonic DMC-FZ18", "Panasonic DMC-FZ28", "Panasonic DMC-FZ30", "Panasonic DMC-FZ35/FZ38", "Panasonic DMC-FZ40", "Panasonic DMC-FZ45", "Panasonic DMC-FZ50", "Panasonic DMC-FZ7", "Panasonic DMC-FZ70", "Panasonic DMC-FZ72", "Panasonic DC-FZ80/82", "Panasonic DMC-FZ100", "Panasonic DMC-FZ150", "Panasonic DMC-FZ200", "Panasonic DMC-FZ300/330", "Panasonic DMC-FZ1000", "Panasonic DMC-FZ2000/2500/FZH1", "Panasonic DMC-FX150", "Panasonic DMC-G1", "Panasonic DMC-G10", "Panasonic DMC-G2", "Panasonic DMC-G3", "Panasonic DMC-G5", "Panasonic DMC-G6", "Panasonic DMC-G7/G70", "Panasonic DMC-G8/80/81/85", "Panasonic DC-G9", "Panasonic DMC-GF1", "Panasonic DMC-GF2", "Panasonic DMC-GF3", "Panasonic DMC-GF5", "Panasonic DMC-GF6", "Panasonic DMC-GF7", "Panasonic DC-GF10/GF90", "Panasonic DMC-GH1", "Panasonic DMC-GH2", "Panasonic DMC-GH3", "Panasonic DMC-GH4", "Panasonic AG-GH4", "Panasonic DC-GH5", "Panasonic DMC-GM1", "Panasonic DMC-GM1s", "Panasonic DMC-GM5", "Panasonic DMC-GX1", "Panasonic DMC-GX7", "Panasonic DMC-GX8", "Panasonic DC-GX9", "Panasonic DMC-GX80/85", "Panasonic DC-GX800/850/GF9", "Panasonic DMC-L1", "Panasonic DMC-L10", "Panasonic DMC-LC1", "Panasonic DMC-LF1", "Panasonic DMC-LX1", "Panasonic DMC-LX2", "Panasonic DMC-LX3", "Panasonic DMC-LX5", "Panasonic DMC-LX7", "Panasonic DMC-LX9/10/15", "Panasonic DMC-LX100", "Panasonic DMC-TZ60/61/SZ40", "Panasonic DMC-TZ70/71/ZS50", "Panasonic DMC-TZ80/81/85/ZS60", "Panasonic DC-ZS70 (DC-TZ90/91/92, DC-T93)", "Panasonic DC-TZ100/101/ZS100", "Panasonic DC-TZ200/ZS200", "PARROT Bebop 2", "PARROT Bebop Drone", "Pentax *ist D", "Pentax *ist DL", "Pentax *ist DL2", "Pentax *ist DS", "Pentax *ist DS2", "Pentax GR", "Pentax K10D", "Pentax K20D", "Pentax K100D", "Pentax K100D Super", "Pentax K110D", "Pentax K200D", "Pentax K2000/K-m", "Pentax KP", "Pentax K-x", "Pentax K-r", "Pentax K-01", "Pentax K-1", "Pentax K-3", "Pentax K-3 II", "Pentax K-30", "Pentax K-5", "Pentax K-5 II", "Pentax K-5 IIs", "Pentax K-50", "Pentax K-500", "Pentax K-7", "Pentax K-70", "Pentax K-S1", "Pentax K-S2", "Pentax MX-1", "Pentax Q", "Pentax Q7", "Pentax Q10", "Pentax QS-1", "Pentax Optio S", "Pentax Optio S4", "Pentax Optio 33WR", "Pentax Optio 750Z", "Pentax 645D", "Pentax 645Z", "PhaseOne IQ140", "PhaseOne IQ150", "PhaseOne IQ160", "PhaseOne IQ180", "PhaseOne IQ180 IR", "PhaseOne IQ250", "PhaseOne IQ260", "PhaseOne IQ260 Achromatic", "PhaseOne IQ280", "PhaseOne IQ3 50MP", "PhaseOne IQ3 60MP", "PhaseOne IQ3 80MP", "PhaseOne IQ3 100MP", "PhaseOne IQ3 100MP Trichromatic", "PhaseOne LightPhase", "PhaseOne Achromatic+", "PhaseOne H 10", "PhaseOne H 20", "PhaseOne H 25", "PhaseOne P 20", "PhaseOne P 20+", "PhaseOne P 21", "PhaseOne P 25", "PhaseOne P 25+", "PhaseOne P 30", "PhaseOne P 30+", "PhaseOne P 40+", "PhaseOne P 45", "PhaseOne P 45+", "PhaseOne P 65", "PhaseOne P 65+", "Photron BC2-HD", "Pixelink A782", "Polaroid x530", "RaspberryPi Camera", "RaspberryPi Camera V2", "Ricoh GR", "Ricoh GR Digital", "Ricoh GR Digital II", "Ricoh GR Digital III", "Ricoh GR Digital IV", "Ricoh GR II", "Ricoh GX100", "Ricoh GX200", "Ricoh GXR MOUNT A12", "Ricoh GXR MOUNT A16 24-85mm F3.5-5.5", "Ricoh GXR, S10 24-72mm F2.5-4.4 VC", "Ricoh GXR, GR A12 50mm F2.5 MACRO", "Ricoh GXR, GR LENS A12 28mm F2.5", "Ricoh GXR, GXR P10", #ifndef NO_JASPER "Redcode R3D format", #endif "Rollei d530flex", "RoverShot 3320af", "Samsung EX1", "Samsung EX2F", "Samsung GX-1L", "Samsung GX-1S", "Samsung GX10", "Samsung GX20", "Samsung Galaxy Nexus", "Samsung Galaxy NX (EK-GN120)", "Samsung Galaxy S3", "Samsung Galaxy S6 (SM-G920F)", "Samsung Galaxy S7", "Samsung Galaxy S7 Edge", "Samsung Galaxy S8 (SM-G950U)", "Samsung NX1", "Samsung NX5", "Samsung NX10", "Samsung NX11", "Samsung NX100", "Samsung NX1000", "Samsung NX1100", "Samsung NX20", "Samsung NX200", "Samsung NX210", "Samsung NX2000", "Samsung NX30", "Samsung NX300", "Samsung NX300M", "Samsung NX3000", "Samsung NX500", "Samsung NX mini", "Samsung Pro815", "Samsung WB550", "Samsung WB2000", "Samsung S85 (hacked)", "Samsung S850 (hacked)", "Sarnoff 4096x5440", "Seitz 6x17", "Seitz Roundshot D3", "Seitz Roundshot D2X", "Seitz Roundshot D2Xs", "Sigma SD9 (raw decode only)", "Sigma SD10 (raw decode only)", "Sigma SD14 (raw decode only)", "Sigma SD15 (raw decode only)", "Sigma SD1", "Sigma SD1 Merill", "Sigma DP1", "Sigma DP1 Merill", "Sigma DP1S", "Sigma DP1X", "Sigma DP2", "Sigma DP2 Merill", "Sigma DP2S", "Sigma DP2X", "Sigma DP3 Merill", "Sigma dp0 Quattro", "Sigma dp1 Quattro", "Sigma dp2 Quattro", "Sigma dp3 Quattro", "Sigma sd Quattro", "Sigma sd Quattro H", "Sinar eMotion 22", "Sinar eMotion 54", "Sinar eSpirit 65", "Sinar eMotion 75", "Sinar eVolution 75", "Sinar 3072x2048", "Sinar 4080x4080", "Sinar 4080x5440", "Sinar STI format", "Sinar Sinarback 54", "SMaL Ultra-Pocket 3", "SMaL Ultra-Pocket 4", "SMaL Ultra-Pocket 5", "Sony A7", "Sony A7 II", "Sony A7R", "Sony A7R II", "Sony A7R III", "Sony A7S", "Sony A7S II", "Sony A9", "Sony ILCA-68 (A68)", "Sony ILCA-77M2 (A77-II)", "Sony ILCA-99M2 (A99-II)", "Sony ILCE-3000", "Sony ILCE-5000", "Sony ILCE-5100", "Sony ILCE-6000", "Sony ILCE-6300", "Sony ILCE-6500", "Sony ILCE-QX1", "Sony DSC-F828", "Sony DSC-R1", "Sony DSC-RX0", "Sony DSC-RX1", "Sony DSC-RX1R", "Sony DSC-RX1R II", "Sony DSC-RX10", "Sony DSC-RX10II", "Sony DSC-RX10III", "Sony DSC-RX10IV", "Sony DSC-RX100", "Sony DSC-RX100II", "Sony DSC-RX100III", "Sony DSC-RX100IV", "Sony DSC-RX100V", "Sony DSC-V3", "Sony DSLR-A100", "Sony DSLR-A200", "Sony DSLR-A230", "Sony DSLR-A290", "Sony DSLR-A300", "Sony DSLR-A330", "Sony DSLR-A350", "Sony DSLR-A380", "Sony DSLR-A390", "Sony DSLR-A450", "Sony DSLR-A500", "Sony DSLR-A550", "Sony DSLR-A560", "Sony DSLR-A580", "Sony DSLR-A700", "Sony DSLR-A850", "Sony DSLR-A900", "Sony NEX-3", "Sony NEX-3N", "Sony NEX-5", "Sony NEX-5N", "Sony NEX-5R", "Sony NEX-5T", "Sony NEX-6", "Sony NEX-7", "Sony NEX-C3", "Sony NEX-F3", "Sony NEX-VG20", "Sony NEX-VG30", "Sony NEX-VG900", "Sony SLT-A33", "Sony SLT-A35", "Sony SLT-A37", "Sony SLT-A55V", "Sony SLT-A57", "Sony SLT-A58", "Sony SLT-A65V", "Sony SLT-A77V", "Sony SLT-A99V", "Sony XCD-SX910CR", "Sony IMX135-mipi 13mp", "Sony IMX135-QCOM", "Sony IMX072-mipi", "Sony IMX214", "Sony IMX219", "Sony IMX230", "Sony IMX298-mipi 16mp", "Sony IMX219-mipi 8mp", "Sony Xperia L", "STV680 VGA", "PtGrey GRAS-50S5C", "JaiPulnix BB-500CL", "JaiPulnix BB-500GE", "SVS SVS625CL", "Yi M1", "YUNEEC CGO3", "YUNEEC CGO3P", "YUNEEC CGO4", "Xiaomi MI3", "Xiaomi RedMi Note3 Pro", "Xiaoyi YIAC3 (YI 4k)", NULL }; // clang-format on const char **LibRaw::cameraList() { return static_camera_list; } int LibRaw::cameraCount() { return (sizeof(static_camera_list) / sizeof(static_camera_list[0])) - 1; } const char *LibRaw::strprogress(enum LibRaw_progress p) { switch (p) { case LIBRAW_PROGRESS_START: return "Starting"; case LIBRAW_PROGRESS_OPEN: return "Opening file"; case LIBRAW_PROGRESS_IDENTIFY: return "Reading metadata"; case LIBRAW_PROGRESS_SIZE_ADJUST: return "Adjusting size"; case LIBRAW_PROGRESS_LOAD_RAW: return "Reading RAW data"; case LIBRAW_PROGRESS_REMOVE_ZEROES: return "Clearing zero values"; case LIBRAW_PROGRESS_BAD_PIXELS: return "Removing dead pixels"; case LIBRAW_PROGRESS_DARK_FRAME: return "Subtracting dark frame data"; case LIBRAW_PROGRESS_FOVEON_INTERPOLATE: return "Interpolating Foveon sensor data"; case LIBRAW_PROGRESS_SCALE_COLORS: return "Scaling colors"; case LIBRAW_PROGRESS_PRE_INTERPOLATE: return "Pre-interpolating"; case LIBRAW_PROGRESS_INTERPOLATE: return "Interpolating"; case LIBRAW_PROGRESS_MIX_GREEN: return "Mixing green channels"; case LIBRAW_PROGRESS_MEDIAN_FILTER: return "Median filter"; case LIBRAW_PROGRESS_HIGHLIGHTS: return "Highlight recovery"; case LIBRAW_PROGRESS_FUJI_ROTATE: return "Rotating Fuji diagonal data"; case LIBRAW_PROGRESS_FLIP: return "Flipping image"; case LIBRAW_PROGRESS_APPLY_PROFILE: return "ICC conversion"; case LIBRAW_PROGRESS_CONVERT_RGB: return "Converting to RGB"; case LIBRAW_PROGRESS_STRETCH: return "Stretching image"; case LIBRAW_PROGRESS_THUMB_LOAD: return "Loading thumbnail"; default: return "Some strange things"; } } #undef ID #include "../internal/libraw_x3f.cpp" void x3f_clear(void *p) { x3f_delete((x3f_t *)p); } void utf2char(utf16_t *str, char *buffer, unsigned bufsz) { if(bufsz<1) return; buffer[bufsz-1] = 0; char *b = buffer; while (*str != 0x00 && --bufsz>0) { char *chr = (char *)str; *b++ = *chr; str++; } *b = 0; } static void *lr_memmem(const void *l, size_t l_len, const void *s, size_t s_len) { register char *cur, *last; const char *cl = (const char *)l; const char *cs = (const char *)s; /* we need something to compare */ if (l_len == 0 || s_len == 0) return NULL; /* "s" must be smaller or equal to "l" */ if (l_len < s_len) return NULL; /* special case where s_len == 1 */ if (s_len == 1) return (void *)memchr(l, (int)*cs, l_len); /* the last position where its possible to find "s" in "l" */ last = (char *)cl + l_len - s_len; for (cur = (char *)cl; cur <= last; cur++) if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) return cur; return NULL; } void LibRaw::parse_x3f() { x3f_t *x3f = x3f_new_from_file(libraw_internal_data.internal_data.input); if (!x3f) return; _x3f_data = x3f; x3f_header_t *H = NULL; x3f_directory_section_t *DS = NULL; H = &x3f->header; // Parse RAW size from RAW section x3f_directory_entry_t *DE = x3f_get_raw(x3f); if (!DE) return; imgdata.sizes.flip = H->rotation; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.sizes.raw_width = ID->columns; imgdata.sizes.raw_height = ID->rows; // Parse other params from property section DE = x3f_get_prop(x3f); if ((x3f_load_data(x3f, DE) == X3F_OK)) { // Parse property list DEH = &DE->header; x3f_property_list_t *PL = &DEH->data_subsection.property_list; if (PL->property_table.size != 0) { int i; x3f_property_t *P = PL->property_table.element; for (i = 0; i < PL->num_properties; i++) { char name[100], value[100]; utf2char(P[i].name, name,sizeof(name)); utf2char(P[i].value, value,sizeof(value)); if (!strcmp(name, "ISO")) imgdata.other.iso_speed = atoi(value); if (!strcmp(name, "CAMMANUF")) strcpy(imgdata.idata.make, value); if (!strcmp(name, "CAMMODEL")) strcpy(imgdata.idata.model, value); if (!strcmp(name, "CAMSERIAL")) strcpy(imgdata.shootinginfo.BodySerial, value); if (!strcmp(name, "WB_DESC")) strcpy(imgdata.color.model2, value); if (!strcmp(name, "TIME")) imgdata.other.timestamp = atoi(value); if (!strcmp(name, "SHUTTER")) imgdata.other.shutter = atof(value); if (!strcmp(name, "APERTURE")) imgdata.other.aperture = atof(value); if (!strcmp(name, "FLENGTH")) imgdata.other.focal_len = atof(value); if (!strcmp(name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp(name, "IMAGERTEMP")) imgdata.other.SensorTemperature = atof(value); if (!strcmp(name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp(name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp(name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff imgdata.color.maximum = 0x3fff; // To be reset by color table libraw_internal_data.unpacker_data.order = 0x4949; } } else { // No property list if (imgdata.sizes.raw_width == 5888 || imgdata.sizes.raw_width == 2944 || imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328 || imgdata.sizes.raw_width == 5504 || imgdata.sizes.raw_width == 2752) // Quattro { imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff libraw_internal_data.unpacker_data.order = 0x4949; strcpy(imgdata.idata.make, "SIGMA"); #if 1 // Try to find model number in first 2048 bytes; int pos = libraw_internal_data.internal_data.input->tell(); libraw_internal_data.internal_data.input->seek(0, SEEK_SET); unsigned char buf[2048]; libraw_internal_data.internal_data.input->read(buf, 2048, 1); libraw_internal_data.internal_data.input->seek(pos, SEEK_SET); unsigned char *fnd = (unsigned char *)lr_memmem(buf, 2048, "SIGMA dp", 8); unsigned char *fndsd = (unsigned char *)lr_memmem(buf, 2048, "sd Quatt", 8); if (fnd) { unsigned char *nm = fnd + 8; snprintf(imgdata.idata.model, 64, "dp%c Quattro", *nm <= '9' && *nm >= '0' ? *nm : '2'); } else if (fndsd) { snprintf(imgdata.idata.model, 64, "%s", fndsd); } else #endif if (imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328) strcpy(imgdata.idata.model, "sd Quattro H"); else strcpy(imgdata.idata.model, "dp2 Quattro"); } // else } // Try to get thumbnail data LibRaw_thumbnail_formats format = LIBRAW_THUMBNAIL_UNKNOWN; if ((DE = x3f_get_thumb_jpeg(x3f))) { format = LIBRAW_THUMBNAIL_JPEG; } else if ((DE = x3f_get_thumb_plain(x3f))) { format = LIBRAW_THUMBNAIL_BITMAP; } if (DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; imgdata.thumbnail.tformat = format; libraw_internal_data.internal_data.toffset = DE->input.offset; write_thumb = &LibRaw::x3f_thumb_loader; } } INT64 LibRaw::x3f_thumb_size() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return -1; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return -1; int64_t p = x3f_load_data_size(x3f, DE); if (p < 0 || p > 0xffffffff) return -1; return p; } catch (...) { return -1; } } void LibRaw::x3f_thumb_loader() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return; if (X3F_OK != x3f_load_data(x3f, DE)) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_JPEG) { imgdata.thumbnail.thumb = (char *)malloc(ID->data_size); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); memmove(imgdata.thumbnail.thumb, ID->data, ID->data_size); imgdata.thumbnail.tlength = ID->data_size; } else if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_BITMAP) { imgdata.thumbnail.tlength = ID->columns * ID->rows * 3; imgdata.thumbnail.thumb = (char *)malloc(ID->columns * ID->rows * 3); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); char *src0 = (char *)ID->data; for (int row = 0; row < ID->rows; row++) { int offset = row * ID->row_stride; if (offset + ID->columns * 3 > ID->data_size) break; char *dest = &imgdata.thumbnail.thumb[row * ID->columns * 3]; char *src = &src0[offset]; memmove(dest, src, ID->columns * 3); } } } catch (...) { // do nothing } } static inline uint32_t _clampbits(int x, uint32_t n) { uint32_t _y_temp; if ((_y_temp = x >> n)) x = ~_y_temp >> (32 - n); return x; } void LibRaw::x3f_dpq_interpolate_rg() { int w = imgdata.sizes.raw_width / 2; int h = imgdata.sizes.raw_height / 2; unsigned short *image = (ushort *)imgdata.rawdata.color3_image; for (int color = 0; color < 2; color++) { for (int y = 2; y < (h - 2); y++) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * (y * 2) + color]; // dst[1] uint16_t row0_3 = row0[3]; uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y * 2 + 1) + color]; // dst1[1] uint16_t row1_3 = row1[3]; for (int x = 2; x < (w - 2); x++) { row1[0] = row1[3] = row0[3] = row0[0]; row0 += 6; row1 += 6; } } } } #define _ABS(a) ((a) < 0 ? -(a) : (a)) #undef CLIP #define CLIP(value, high) ((value) > (high) ? (high) : (value)) void LibRaw::x3f_dpq_interpolate_af(int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = 0; y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { if (y < imgdata.rawdata.sizes.top_margin) continue; if (y < scale) continue; if (y > imgdata.rawdata.sizes.raw_height - scale) break; uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже for (int x = 0; x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { if (x < imgdata.rawdata.sizes.left_margin) continue; if (x < scale) continue; if (x > imgdata.rawdata.sizes.raw_width - scale) break; uint16_t *pixel0 = &row0[x * 3]; uint16_t *pixel_top = &row_minus[x * 3]; uint16_t *pixel_bottom = &row_plus[x * 3]; uint16_t *pixel_left = &row0[(x - scale) * 3]; uint16_t *pixel_right = &row0[(x + scale) * 3]; uint16_t *pixf = pixel_top; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_bottom[2] - pixel0[2])) pixf = pixel_bottom; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_left[2] - pixel0[2])) pixf = pixel_left; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_right[2] - pixel0[2])) pixf = pixel_right; int blocal = pixel0[2], bnear = pixf[2]; if (blocal < imgdata.color.black + 16 || bnear < imgdata.color.black + 16) { if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; pixel0[0] = CLIP((pixel0[0] - imgdata.color.black) * 4 + imgdata.color.black, 16383); pixel0[1] = CLIP((pixel0[1] - imgdata.color.black) * 4 + imgdata.color.black, 16383); } else { float multip = float(bnear - imgdata.color.black) / float(blocal - imgdata.color.black); if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; float pixf0 = pixf[0]; if (pixf0 < imgdata.color.black) pixf0 = imgdata.color.black; float pixf1 = pixf[1]; if (pixf1 < imgdata.color.black) pixf1 = imgdata.color.black; pixel0[0] = CLIP(((float(pixf0 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[0] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); pixel0[1] = CLIP(((float(pixf1 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[1] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); // pixel0[1] = float(pixf[1]-imgdata.color.black)*multip + imgdata.color.black; } } } } void LibRaw::x3f_dpq_interpolate_af_sd(int xstart, int ystart, int xend, int yend, int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = ystart; y < yend && y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y + 1)]; // Следующая строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже AF-point (scale=2 -> ниже row1 uint16_t *row_minus1 = &image[imgdata.sizes.raw_width * 3 * (y - 1)]; for (int x = xstart; x < xend && x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { uint16_t *pixel00 = &row0[x * 3]; // Current pixel float sumR = 0.f, sumG = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumR += row_minus[(x + xx) * 3]; sumR += row_plus[(x + xx) * 3]; sumG += row_minus[(x + xx) * 3 + 1]; sumG += row_plus[(x + xx) * 3 + 1]; cnt += 1.f; if (xx) { cnt += 1.f; sumR += row0[(x + xx) * 3]; sumG += row0[(x + xx) * 3 + 1]; } } pixel00[0] = sumR / 8.f; pixel00[1] = sumG / 8.f; if (scale == 2) { uint16_t *pixel0B = &row0[x * 3 + 3]; // right pixel uint16_t *pixel1B = &row1[x * 3 + 3]; // right pixel float sumG0 = 0, sumG1 = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumG0 += row_minus1[(x + xx) * 3 + 2]; sumG1 += row_plus[(x + xx) * 3 + 2]; cnt += 1.f; if (xx) { sumG0 += row0[(x + xx) * 3 + 2]; sumG1 += row1[(x + xx) * 3 + 2]; cnt += 1.f; } } pixel0B[2] = sumG0 / cnt; pixel1B[2] = sumG1 / cnt; } // uint16_t* pixel10 = &row1[x*3]; // Pixel below current // uint16_t* pixel_bottom = &row_plus[x*3]; } } } void LibRaw::x3f_load_raw() { // already in try/catch int raise_error = 0; x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set if (X3F_OK == x3f_load_data(x3f, x3f_get_raw(x3f))) { x3f_directory_entry_t *DE = x3f_get_raw(x3f); x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_quattro_t *Q = ID->quattro; x3f_huffman_t *HUF = ID->huffman; x3f_true_t *TRU = ID->tru; uint16_t *data = NULL; if (ID->rows != S.raw_height || ID->columns != S.raw_width) { raise_error = 1; goto end; } if (HUF != NULL) data = HUF->x3rgb16.data; if (TRU != NULL) data = TRU->x3rgb16.data; if (data == NULL) { raise_error = 1; goto end; } size_t datasize = S.raw_height * S.raw_width * 3 * sizeof(unsigned short); S.raw_pitch = S.raw_width * 3 * sizeof(unsigned short); if (!(imgdata.rawdata.raw_alloc = malloc(datasize))) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (HUF) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && (!Q || !Q->quattro_layout)) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && Q) { // Move quattro data in place // R/B plane for (int prow = 0; prow < TRU->x3rgb16.rows && prow < S.raw_height / 2; prow++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[prow * 2 * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow)[3] = (unsigned short(*)[3]) & data[prow * TRU->x3rgb16.row_stride]; for (int pcol = 0; pcol < TRU->x3rgb16.columns && pcol < S.raw_width / 2; pcol++) { destrow[pcol * 2][0] = srcrow[pcol][0]; destrow[pcol * 2][1] = srcrow[pcol][1]; } } for (int row = 0; row < Q->top16.rows && row < S.raw_height; row++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[row * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow) = (unsigned short *)&Q->top16.data[row * Q->top16.columns]; for (int col = 0; col < Q->top16.columns && col < S.raw_width; col++) destrow[col][2] = srcrow[col]; } } #if 1 if (TRU && Q && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF)) { if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3672) // dpN Quattro normal { x3f_dpq_interpolate_af(32, 8, 2); } else if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3776) // sd Quattro normal raw { x3f_dpq_interpolate_af_sd(216, 464, imgdata.sizes.raw_width - 1, 3312, 16, 32, 2); } else if (imgdata.sizes.raw_width == 6656 && imgdata.sizes.raw_height == 4480) // sd Quattro H normal raw { x3f_dpq_interpolate_af_sd(232, 592, imgdata.sizes.raw_width - 1, 3920, 16, 32, 2); } else if (imgdata.sizes.raw_width == 3328 && imgdata.sizes.raw_height == 2240) // sd Quattro H half size { x3f_dpq_interpolate_af_sd(116, 296, imgdata.sizes.raw_width - 1, 2200, 8, 16, 1); } else if (imgdata.sizes.raw_width == 5504 && imgdata.sizes.raw_height == 3680) // sd Quattro H APS-C raw { x3f_dpq_interpolate_af_sd(8, 192, imgdata.sizes.raw_width - 1, 3185, 16, 32, 2); } else if (imgdata.sizes.raw_width == 2752 && imgdata.sizes.raw_height == 1840) // sd Quattro H APS-C half size { x3f_dpq_interpolate_af_sd(4, 96, imgdata.sizes.raw_width - 1, 1800, 8, 16, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1836) // dpN Quattro small raw { x3f_dpq_interpolate_af(16, 4, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1888) // sd Quattro small { x3f_dpq_interpolate_af_sd(108, 232, imgdata.sizes.raw_width - 1, 1656, 8, 16, 1); } } #endif if (TRU && Q && Q->quattro_layout && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATERG)) x3f_dpq_interpolate_rg(); } else raise_error = 1; end: if (raise_error) throw LIBRAW_EXCEPTION_IO_CORRUPT; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_94_2
crossvul-cpp_data_good_2813_1
/***************************************************************** | | AP4 - hvcC Atoms | | Copyright 2002-2016 Axiomatic Systems, LLC | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4HvccAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Utils.h" #include "Ap4Types.h" #include "Ap4HevcParser.h" /*---------------------------------------------------------------------- | dynamic cast support +---------------------------------------------------------------------*/ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_HvccAtom) /*---------------------------------------------------------------------- | AP4_HvccAtom::GetProfileName +---------------------------------------------------------------------*/ const char* AP4_HvccAtom::GetProfileName(AP4_UI08 profile_space, AP4_UI08 profile) { if (profile_space != 0) { return NULL; } switch (profile) { case AP4_HEVC_PROFILE_MAIN: return "Main"; case AP4_HEVC_PROFILE_MAIN_10: return "Main 10"; case AP4_HEVC_PROFILE_MAIN_STILL_PICTURE: return "Main Still Picture"; case AP4_HEVC_PROFILE_REXT: return "Rext"; } return NULL; } /*---------------------------------------------------------------------- | AP4_HvccAtom::GetChromaFormatName +---------------------------------------------------------------------*/ const char* AP4_HvccAtom::GetChromaFormatName(AP4_UI08 chroma_format) { switch (chroma_format) { case AP4_HEVC_CHROMA_FORMAT_MONOCHROME: return "Monochrome"; case AP4_HEVC_CHROMA_FORMAT_420: return "4:2:0"; case AP4_HEVC_CHROMA_FORMAT_422: return "4:2:2"; case AP4_HEVC_CHROMA_FORMAT_444: return "4:4:4"; } return NULL; } /*---------------------------------------------------------------------- | AP4_AvccAtom::Create +---------------------------------------------------------------------*/ AP4_HvccAtom* AP4_HvccAtom::Create(AP4_Size size, AP4_ByteStream& stream) { // read the raw bytes in a buffer unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE; AP4_DataBuffer payload_data(payload_size); AP4_Result result = stream.Read(payload_data.UseData(), payload_size); if (AP4_FAILED(result)) return NULL; return new AP4_HvccAtom(size, payload_data.GetData()); } /*---------------------------------------------------------------------- | AP4_HvccAtom::AP4_HvccAtom +---------------------------------------------------------------------*/ AP4_HvccAtom::AP4_HvccAtom() : AP4_Atom(AP4_ATOM_TYPE_HVCC, AP4_ATOM_HEADER_SIZE), m_ConfigurationVersion(1), m_GeneralProfileSpace(0), m_GeneralTierFlag(0), m_GeneralProfile(0), m_GeneralProfileCompatibilityFlags(0), m_GeneralConstraintIndicatorFlags(0), m_GeneralLevel(0), m_Reserved1(0), m_MinSpatialSegmentation(0), m_Reserved2(0), m_ParallelismType(0), m_Reserved3(0), m_ChromaFormat(0), m_Reserved4(0), m_LumaBitDepth(8), m_Reserved5(0), m_ChromaBitDepth(8), m_AverageFrameRate(0), m_ConstantFrameRate(0), m_NumTemporalLayers(0), m_TemporalIdNested(0), m_NaluLengthSize(4) { UpdateRawBytes(); m_Size32 += m_RawBytes.GetDataSize(); } /*---------------------------------------------------------------------- | AP4_HvccAtom::AP4_HvccAtom +---------------------------------------------------------------------*/ AP4_HvccAtom::AP4_HvccAtom(const AP4_HvccAtom& other) : AP4_Atom(AP4_ATOM_TYPE_HVCC, other.m_Size32), m_ConfigurationVersion(other.m_ConfigurationVersion), m_GeneralProfileSpace(other.m_GeneralProfileSpace), m_GeneralTierFlag(other.m_GeneralTierFlag), m_GeneralProfile(other.m_GeneralProfile), m_GeneralProfileCompatibilityFlags(other.m_GeneralProfileCompatibilityFlags), m_GeneralConstraintIndicatorFlags(other.m_GeneralConstraintIndicatorFlags), m_GeneralLevel(other.m_GeneralLevel), m_Reserved1(other.m_Reserved1), m_MinSpatialSegmentation(other.m_MinSpatialSegmentation), m_Reserved2(other.m_Reserved2), m_ParallelismType(other.m_ParallelismType), m_Reserved3(other.m_Reserved3), m_ChromaFormat(other.m_ChromaFormat), m_Reserved4(other.m_Reserved4), m_LumaBitDepth(other.m_LumaBitDepth), m_Reserved5(other.m_Reserved5), m_ChromaBitDepth(other.m_ChromaBitDepth), m_AverageFrameRate(other.m_AverageFrameRate), m_ConstantFrameRate(other.m_ConstantFrameRate), m_NumTemporalLayers(other.m_NumTemporalLayers), m_TemporalIdNested(other.m_TemporalIdNested), m_NaluLengthSize(other.m_NaluLengthSize), m_RawBytes(other.m_RawBytes) { // deep copy of the parameters unsigned int i = 0; for (i=0; i<other.m_Sequences.ItemCount(); i++) { m_Sequences.Append(other.m_Sequences[i]); } } /*---------------------------------------------------------------------- | AP4_HvccAtom::AP4_HvccAtom +---------------------------------------------------------------------*/ AP4_HvccAtom::AP4_HvccAtom(AP4_UI08 general_profile_space, AP4_UI08 general_tier_flag, AP4_UI08 general_profile, AP4_UI32 general_profile_compatibility_flags, AP4_UI64 general_constraint_indicator_flags, AP4_UI08 general_level, AP4_UI32 min_spatial_segmentation, AP4_UI08 parallelism_type, AP4_UI08 chroma_format, AP4_UI08 luma_bit_depth, AP4_UI08 chroma_bit_depth, AP4_UI16 average_frame_rate, AP4_UI08 constant_frame_rate, AP4_UI08 num_temporal_layers, AP4_UI08 temporal_id_nested, AP4_UI08 nalu_length_size, const AP4_Array<AP4_DataBuffer>& video_parameters, const AP4_Array<AP4_DataBuffer>& sequence_parameters, const AP4_Array<AP4_DataBuffer>& picture_parameters) : AP4_Atom(AP4_ATOM_TYPE_HVCC, AP4_ATOM_HEADER_SIZE), m_ConfigurationVersion(1), m_GeneralProfileSpace(general_profile_space), m_GeneralTierFlag(general_tier_flag), m_GeneralProfile(general_profile), m_GeneralProfileCompatibilityFlags(general_profile_compatibility_flags), m_GeneralConstraintIndicatorFlags(general_constraint_indicator_flags), m_GeneralLevel(general_level), m_Reserved1(0), m_MinSpatialSegmentation(min_spatial_segmentation), m_Reserved2(0), m_ParallelismType(parallelism_type), m_Reserved3(0), m_ChromaFormat(chroma_format), m_Reserved4(0), m_LumaBitDepth(luma_bit_depth), m_Reserved5(0), m_ChromaBitDepth(chroma_bit_depth), m_AverageFrameRate(average_frame_rate), m_ConstantFrameRate(constant_frame_rate), m_NumTemporalLayers(num_temporal_layers), m_TemporalIdNested(temporal_id_nested), m_NaluLengthSize(nalu_length_size) { // deep copy of the parameters AP4_HvccAtom::Sequence vps_sequence; vps_sequence.m_NaluType = AP4_HEVC_NALU_TYPE_VPS_NUT; vps_sequence.m_ArrayCompleteness = 0; for (unsigned int i=0; i<video_parameters.ItemCount(); i++) { vps_sequence.m_Nalus.Append(video_parameters[i]); } if (vps_sequence.m_Nalus.ItemCount()) { m_Sequences.Append(vps_sequence); } AP4_HvccAtom::Sequence sps_sequence; sps_sequence.m_NaluType = AP4_HEVC_NALU_TYPE_SPS_NUT; sps_sequence.m_ArrayCompleteness = 0; for (unsigned int i=0; i<sequence_parameters.ItemCount(); i++) { sps_sequence.m_Nalus.Append(sequence_parameters[i]); } if (sps_sequence.m_Nalus.ItemCount()) { m_Sequences.Append(sps_sequence); } AP4_HvccAtom::Sequence pps_sequence; pps_sequence.m_NaluType = AP4_HEVC_NALU_TYPE_PPS_NUT; pps_sequence.m_ArrayCompleteness = 0; for (unsigned int i=0; i<picture_parameters.ItemCount(); i++) { pps_sequence.m_Nalus.Append(picture_parameters[i]); } if (pps_sequence.m_Nalus.ItemCount()) { m_Sequences.Append(pps_sequence); } UpdateRawBytes(); m_Size32 += m_RawBytes.GetDataSize(); } /*---------------------------------------------------------------------- | AP4_HvccAtom::AP4_HvccAtom +---------------------------------------------------------------------*/ AP4_HvccAtom::AP4_HvccAtom(AP4_UI32 size, const AP4_UI08* payload) : AP4_Atom(AP4_ATOM_TYPE_HVCC, size) { // make a copy of our configuration bytes unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE; // keep a raw copy if (payload_size < 22) return; m_RawBytes.SetData(payload, payload_size); // parse the payload m_ConfigurationVersion = payload[0]; m_GeneralProfileSpace = (payload[1]>>6) & 0x03; m_GeneralTierFlag = (payload[1]>>5) & 0x01; m_GeneralProfile = (payload[1] ) & 0x1F; m_GeneralProfileCompatibilityFlags = AP4_BytesToUInt32BE(&payload[2]); m_GeneralConstraintIndicatorFlags = (((AP4_UI64)AP4_BytesToUInt32BE(&payload[6]))<<16) | AP4_BytesToUInt16BE(&payload[10]); m_GeneralLevel = payload[12]; m_Reserved1 = (payload[13]>>4) & 0x0F; m_MinSpatialSegmentation = AP4_BytesToUInt16BE(&payload[13]) & 0x0FFF; m_Reserved2 = (payload[15]>>2) & 0x3F; m_ParallelismType = payload[15] & 0x03; m_Reserved3 = (payload[16]>>2) & 0x3F; m_ChromaFormat = payload[16] & 0x03; m_Reserved4 = (payload[17]>>3) & 0x1F; m_LumaBitDepth = 8+(payload[17] & 0x07); m_Reserved5 = (payload[18]>>3) & 0x1F; m_ChromaBitDepth = 8+(payload[18] & 0x07); m_AverageFrameRate = AP4_BytesToUInt16BE(&payload[19]); m_ConstantFrameRate = (payload[21]>>6) & 0x03; m_NumTemporalLayers = (payload[21]>>3) & 0x07; m_TemporalIdNested = (payload[21]>>2) & 0x01; m_NaluLengthSize = 1+(payload[21] & 0x03); AP4_UI08 num_seq = payload[22]; m_Sequences.SetItemCount(num_seq); unsigned int cursor = 23; for (unsigned int i=0; i<num_seq; i++) { Sequence& seq = m_Sequences[i]; if (cursor+1 > payload_size) break; seq.m_ArrayCompleteness = (payload[cursor] >> 7) & 0x01; seq.m_Reserved = (payload[cursor] >> 6) & 0x01; seq.m_NaluType = payload[cursor] & 0x3F; cursor += 1; if (cursor+2 > payload_size) break; AP4_UI16 nalu_count = AP4_BytesToUInt16BE(&payload[cursor]); seq.m_Nalus.SetItemCount(nalu_count); cursor += 2; for (unsigned int j=0; j<nalu_count; j++) { if (cursor+2 > payload_size) break; unsigned int nalu_length = AP4_BytesToUInt16BE(&payload[cursor]); cursor += 2; if (cursor + nalu_length > payload_size) break; seq.m_Nalus[j].SetData(&payload[cursor], nalu_length); cursor += nalu_length; } } } /*---------------------------------------------------------------------- | AP4_HvccAtom::UpdateRawBytes +---------------------------------------------------------------------*/ void AP4_HvccAtom::UpdateRawBytes() { AP4_BitWriter bits(23); bits.Write(m_ConfigurationVersion, 8); bits.Write(m_GeneralProfileSpace, 2); bits.Write(m_GeneralTierFlag, 1); bits.Write(m_GeneralProfile, 5); bits.Write(m_GeneralProfileCompatibilityFlags, 32); bits.Write((AP4_UI32)(m_GeneralConstraintIndicatorFlags>>32), 16); bits.Write((AP4_UI32)(m_GeneralConstraintIndicatorFlags), 32); bits.Write(m_GeneralLevel, 8); bits.Write(0xFF, 4); bits.Write(m_MinSpatialSegmentation, 12); bits.Write(0xFF, 6); bits.Write(m_ParallelismType, 2); bits.Write(0xFF, 6); bits.Write(m_ChromaFormat, 2); bits.Write(0xFF, 5); bits.Write(m_LumaBitDepth >= 8 ? m_LumaBitDepth - 8 : 0, 3); bits.Write(0xFF, 5); bits.Write(m_ChromaBitDepth >= 8 ? m_ChromaBitDepth - 8 : 0, 3); bits.Write(m_AverageFrameRate, 16); bits.Write(m_ConstantFrameRate, 2); bits.Write(m_NumTemporalLayers, 3); bits.Write(m_TemporalIdNested, 1); bits.Write(m_NaluLengthSize > 0 ? m_NaluLengthSize - 1 : 0, 2); bits.Write(m_Sequences.ItemCount(), 8); m_RawBytes.SetData(bits.GetData(), 23); for (unsigned int i=0; i<m_Sequences.ItemCount(); i++) { AP4_UI08 bytes[3]; bytes[0] = (m_Sequences[i].m_ArrayCompleteness ? (1<<7) : 0) | m_Sequences[i].m_NaluType; AP4_BytesFromUInt16BE(&bytes[1], m_Sequences[i].m_Nalus.ItemCount()); m_RawBytes.AppendData(bytes, 3); for (unsigned int j=0; j<m_Sequences[i].m_Nalus.ItemCount(); j++) { AP4_UI08 size[2]; AP4_BytesFromUInt16BE(&size[0], (AP4_UI16)m_Sequences[i].m_Nalus[j].GetDataSize()); m_RawBytes.AppendData(size, 2); m_RawBytes.AppendData(m_Sequences[i].m_Nalus[j].GetData(), m_Sequences[i].m_Nalus[j].GetDataSize()); } } } /*---------------------------------------------------------------------- | AP4_HvccAtom::WriteFields +---------------------------------------------------------------------*/ AP4_Result AP4_HvccAtom::WriteFields(AP4_ByteStream& stream) { return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize()); } /*---------------------------------------------------------------------- | AP4_HvccAtom::InspectFields +---------------------------------------------------------------------*/ AP4_Result AP4_HvccAtom::InspectFields(AP4_AtomInspector& inspector) { inspector.AddField("Configuration Version", m_ConfigurationVersion); inspector.AddField("Profile Space", m_GeneralProfileSpace); const char* profile_name = GetProfileName(m_GeneralProfileSpace, m_GeneralProfile); if (profile_name) { inspector.AddField("Profile", profile_name); } else { inspector.AddField("Profile", m_GeneralProfile); } inspector.AddField("Tier", m_GeneralTierFlag); inspector.AddField("Profile Compatibility", m_GeneralProfileCompatibilityFlags, AP4_AtomInspector::HINT_HEX); inspector.AddField("Constraint", m_GeneralConstraintIndicatorFlags, AP4_AtomInspector::HINT_HEX); inspector.AddField("Level", m_GeneralLevel); inspector.AddField("Min Spatial Segmentation", m_MinSpatialSegmentation); inspector.AddField("Parallelism Type", m_ParallelismType); inspector.AddField("Chroma Format", m_ChromaFormat); inspector.AddField("Chroma Depth", m_ChromaBitDepth); inspector.AddField("Luma Depth", m_LumaBitDepth); inspector.AddField("Average Frame Rate", m_AverageFrameRate); inspector.AddField("Constant Frame Rate", m_ConstantFrameRate); inspector.AddField("Number Of Temporal Layers", m_NumTemporalLayers); inspector.AddField("Temporal Id Nested", m_TemporalIdNested); inspector.AddField("NALU Length Size", m_NaluLengthSize); return AP4_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_2813_1
crossvul-cpp_data_bad_3390_1
// zinflate.cpp - originally written and placed in the public domain by Wei Dai // This is a complete reimplementation of the DEFLATE decompression algorithm. // It should not be affected by any security vulnerabilities in the zlib // compression library. In particular it is not affected by the double free bug // (http://www.kb.cert.org/vuls/id/368819). #include "pch.h" #include "zinflate.h" #include "secblock.h" #include "smartptr.h" NAMESPACE_BEGIN(CryptoPP) struct CodeLessThan { inline bool operator()(CryptoPP::HuffmanDecoder::code_t lhs, const CryptoPP::HuffmanDecoder::CodeInfo &rhs) {return lhs < rhs.code;} // needed for MSVC .NET 2005 inline bool operator()(const CryptoPP::HuffmanDecoder::CodeInfo &lhs, const CryptoPP::HuffmanDecoder::CodeInfo &rhs) {return lhs.code < rhs.code;} }; inline bool LowFirstBitReader::FillBuffer(unsigned int length) { while (m_bitsBuffered < length) { byte b; if (!m_store.Get(b)) return false; m_buffer |= (unsigned long)b << m_bitsBuffered; m_bitsBuffered += 8; } CRYPTOPP_ASSERT(m_bitsBuffered <= sizeof(unsigned long)*8); return true; } inline unsigned long LowFirstBitReader::PeekBits(unsigned int length) { bool result = FillBuffer(length); CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result); return m_buffer & (((unsigned long)1 << length) - 1); } inline void LowFirstBitReader::SkipBits(unsigned int length) { CRYPTOPP_ASSERT(m_bitsBuffered >= length); m_buffer >>= length; m_bitsBuffered -= length; } inline unsigned long LowFirstBitReader::GetBits(unsigned int length) { unsigned long result = PeekBits(length); SkipBits(length); return result; } inline HuffmanDecoder::code_t HuffmanDecoder::NormalizeCode(HuffmanDecoder::code_t code, unsigned int codeBits) { return code << (MAX_CODE_BITS - codeBits); } void HuffmanDecoder::Initialize(const unsigned int *codeBits, unsigned int nCodes) { // the Huffman codes are represented in 3 ways in this code: // // 1. most significant code bit (i.e. top of code tree) in the least significant bit position // 2. most significant code bit (i.e. top of code tree) in the most significant bit position // 3. most significant code bit (i.e. top of code tree) in n-th least significant bit position, // where n is the maximum code length for this code tree // // (1) is the way the codes come in from the deflate stream // (2) is used to sort codes so they can be binary searched // (3) is used in this function to compute codes from code lengths // // a code in representation (2) is called "normalized" here // The BitReverse() function is used to convert between (1) and (2) // The NormalizeCode() function is used to convert from (3) to (2) if (nCodes == 0) throw Err("null code"); m_maxCodeBits = *std::max_element(codeBits, codeBits+nCodes); if (m_maxCodeBits > MAX_CODE_BITS) throw Err("code length exceeds maximum"); if (m_maxCodeBits == 0) throw Err("null code"); // count number of codes of each length SecBlockWithHint<unsigned int, 15+1> blCount(m_maxCodeBits+1); std::fill(blCount.begin(), blCount.end(), 0); unsigned int i; for (i=0; i<nCodes; i++) blCount[codeBits[i]]++; // compute the starting code of each length code_t code = 0; SecBlockWithHint<code_t, 15+1> nextCode(m_maxCodeBits+1); nextCode[1] = 0; for (i=2; i<=m_maxCodeBits; i++) { // compute this while checking for overflow: code = (code + blCount[i-1]) << 1 if (code > code + blCount[i-1]) throw Err("codes oversubscribed"); code += blCount[i-1]; if (code > (code << 1)) throw Err("codes oversubscribed"); code <<= 1; nextCode[i] = code; } // MAX_CODE_BITS is 32, m_maxCodeBits may be smaller. const word64 shiftedMaxCode = ((word64)1 << m_maxCodeBits); if (code > shiftedMaxCode - blCount[m_maxCodeBits]) throw Err("codes oversubscribed"); else if (m_maxCodeBits != 1 && code < shiftedMaxCode - blCount[m_maxCodeBits]) throw Err("codes incomplete"); // compute a vector of <code, length, value> triples sorted by code m_codeToValue.resize(nCodes - blCount[0]); unsigned int j=0; for (i=0; i<nCodes; i++) { unsigned int len = codeBits[i]; if (len != 0) { code = NormalizeCode(nextCode[len]++, len); m_codeToValue[j].code = code; m_codeToValue[j].len = len; m_codeToValue[j].value = i; j++; } } std::sort(m_codeToValue.begin(), m_codeToValue.end()); // initialize the decoding cache m_cacheBits = STDMIN(9U, m_maxCodeBits); m_cacheMask = (1 << m_cacheBits) - 1; m_normalizedCacheMask = NormalizeCode(m_cacheMask, m_cacheBits); CRYPTOPP_ASSERT(m_normalizedCacheMask == BitReverse(m_cacheMask)); const word64 shiftedCache = ((word64)1 << m_cacheBits); CRYPTOPP_ASSERT(shiftedCache <= SIZE_MAX); if (m_cache.size() != shiftedCache) m_cache.resize((size_t)shiftedCache); for (i=0; i<m_cache.size(); i++) m_cache[i].type = 0; } void HuffmanDecoder::FillCacheEntry(LookupEntry &entry, code_t normalizedCode) const { normalizedCode &= m_normalizedCacheMask; const CodeInfo &codeInfo = *(std::upper_bound(m_codeToValue.begin(), m_codeToValue.end(), normalizedCode, CodeLessThan())-1); if (codeInfo.len <= m_cacheBits) { entry.type = 1; entry.value = codeInfo.value; entry.len = codeInfo.len; } else { entry.begin = &codeInfo; const CodeInfo *last = & *(std::upper_bound(m_codeToValue.begin(), m_codeToValue.end(), normalizedCode + ~m_normalizedCacheMask, CodeLessThan())-1); if (codeInfo.len == last->len) { entry.type = 2; entry.len = codeInfo.len; } else { entry.type = 3; entry.end = last+1; } } } inline unsigned int HuffmanDecoder::Decode(code_t code, /* out */ value_t &value) const { CRYPTOPP_ASSERT(m_codeToValue.size() > 0); LookupEntry &entry = m_cache[code & m_cacheMask]; code_t normalizedCode = 0; if (entry.type != 1) normalizedCode = BitReverse(code); if (entry.type == 0) FillCacheEntry(entry, normalizedCode); if (entry.type == 1) { value = entry.value; return entry.len; } else { const CodeInfo &codeInfo = (entry.type == 2) ? entry.begin[(normalizedCode << m_cacheBits) >> (MAX_CODE_BITS - (entry.len - m_cacheBits))] : *(std::upper_bound(entry.begin, entry.end, normalizedCode, CodeLessThan())-1); value = codeInfo.value; return codeInfo.len; } } bool HuffmanDecoder::Decode(LowFirstBitReader &reader, value_t &value) const { bool result = reader.FillBuffer(m_maxCodeBits); CRYPTOPP_UNUSED(result); // CRYPTOPP_ASSERT(result); unsigned int codeBits = Decode(reader.PeekBuffer(), value); if (codeBits > reader.BitsBuffered()) return false; reader.SkipBits(codeBits); return true; } // ************************************************************* Inflator::Inflator(BufferedTransformation *attachment, bool repeat, int propagation) : AutoSignaling<Filter>(propagation) , m_state(PRE_STREAM), m_repeat(repeat), m_eof(0), m_wrappedAround(0) , m_blockType(0xff), m_storedLen(0xffff), m_nextDecode(), m_literal(0) , m_distance(0), m_reader(m_inQueue), m_current(0), m_lastFlush(0) { Detach(attachment); } void Inflator::IsolatedInitialize(const NameValuePairs &parameters) { m_state = PRE_STREAM; parameters.GetValue("Repeat", m_repeat); m_inQueue.Clear(); m_reader.SkipBits(m_reader.BitsBuffered()); } void Inflator::OutputByte(byte b) { m_window[m_current++] = b; if (m_current == m_window.size()) { ProcessDecompressedData(m_window + m_lastFlush, m_window.size() - m_lastFlush); m_lastFlush = 0; m_current = 0; m_wrappedAround = true; } } void Inflator::OutputString(const byte *string, size_t length) { while (length) { size_t len = UnsignedMin(length, m_window.size() - m_current); memcpy(m_window + m_current, string, len); m_current += len; if (m_current == m_window.size()) { ProcessDecompressedData(m_window + m_lastFlush, m_window.size() - m_lastFlush); m_lastFlush = 0; m_current = 0; m_wrappedAround = true; } string += len; length -= len; } } void Inflator::OutputPast(unsigned int length, unsigned int distance) { size_t start; if (distance <= m_current) start = m_current - distance; else if (m_wrappedAround && distance <= m_window.size()) start = m_current + m_window.size() - distance; else throw BadBlockErr(); if (start + length > m_window.size()) { for (; start < m_window.size(); start++, length--) OutputByte(m_window[start]); start = 0; } if (start + length > m_current || m_current + length >= m_window.size()) { while (length--) OutputByte(m_window[start++]); } else { memcpy(m_window + m_current, m_window + start, length); m_current += length; } } size_t Inflator::Put2(const byte *inString, size_t length, int messageEnd, bool blocking) { if (!blocking) throw BlockingInputOnly("Inflator"); LazyPutter lp(m_inQueue, inString, length); ProcessInput(messageEnd != 0); if (messageEnd) if (!(m_state == PRE_STREAM || m_state == AFTER_END)) throw UnexpectedEndErr(); Output(0, NULLPTR, 0, messageEnd, blocking); return 0; } bool Inflator::IsolatedFlush(bool hardFlush, bool blocking) { if (!blocking) throw BlockingInputOnly("Inflator"); if (hardFlush) ProcessInput(true); FlushOutput(); return false; } void Inflator::ProcessInput(bool flush) { while (true) { switch (m_state) { case PRE_STREAM: if (!flush && m_inQueue.CurrentSize() < MaxPrestreamHeaderSize()) return; ProcessPrestreamHeader(); m_state = WAIT_HEADER; m_wrappedAround = false; m_current = 0; m_lastFlush = 0; m_window.New(((size_t) 1) << GetLog2WindowSize()); break; case WAIT_HEADER: { // maximum number of bytes before actual compressed data starts const size_t MAX_HEADER_SIZE = BitsToBytes(3+5+5+4+19*7+286*15+19*15); if (m_inQueue.CurrentSize() < (flush ? 1 : MAX_HEADER_SIZE)) return; DecodeHeader(); break; } case DECODING_BODY: if (!DecodeBody()) return; break; case POST_STREAM: if (!flush && m_inQueue.CurrentSize() < MaxPoststreamTailSize()) return; ProcessPoststreamTail(); m_state = m_repeat ? PRE_STREAM : AFTER_END; Output(0, NULLPTR, 0, GetAutoSignalPropagation(), true); // TODO: non-blocking if (m_inQueue.IsEmpty()) return; break; case AFTER_END: m_inQueue.TransferTo(*AttachedTransformation()); return; } } } void Inflator::DecodeHeader() { if (!m_reader.FillBuffer(3)) throw UnexpectedEndErr(); m_eof = m_reader.GetBits(1) != 0; m_blockType = (byte)m_reader.GetBits(2); switch (m_blockType) { case 0: // stored { m_reader.SkipBits(m_reader.BitsBuffered() % 8); if (!m_reader.FillBuffer(32)) throw UnexpectedEndErr(); m_storedLen = (word16)m_reader.GetBits(16); word16 nlen = (word16)m_reader.GetBits(16); if (nlen != (word16)~m_storedLen) throw BadBlockErr(); break; } case 1: // fixed codes m_nextDecode = LITERAL; break; case 2: // dynamic codes { if (!m_reader.FillBuffer(5+5+4)) throw UnexpectedEndErr(); unsigned int hlit = m_reader.GetBits(5); unsigned int hdist = m_reader.GetBits(5); unsigned int hclen = m_reader.GetBits(4); FixedSizeSecBlock<unsigned int, 286+32> codeLengths; unsigned int i; static const unsigned int border[] = { // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; std::fill(codeLengths.begin(), codeLengths+19, 0); for (i=0; i<hclen+4; i++) codeLengths[border[i]] = m_reader.GetBits(3); try { HuffmanDecoder codeLengthDecoder(codeLengths, 19); for (i = 0; i < hlit+257+hdist+1; ) { unsigned int k = 0, count = 0, repeater = 0; bool result = codeLengthDecoder.Decode(m_reader, k); if (!result) throw UnexpectedEndErr(); if (k <= 15) { count = 1; repeater = k; } else switch (k) { case 16: if (!m_reader.FillBuffer(2)) throw UnexpectedEndErr(); count = 3 + m_reader.GetBits(2); if (i == 0) throw BadBlockErr(); repeater = codeLengths[i-1]; break; case 17: if (!m_reader.FillBuffer(3)) throw UnexpectedEndErr(); count = 3 + m_reader.GetBits(3); repeater = 0; break; case 18: if (!m_reader.FillBuffer(7)) throw UnexpectedEndErr(); count = 11 + m_reader.GetBits(7); repeater = 0; break; } if (i + count > hlit+257+hdist+1) throw BadBlockErr(); std::fill(codeLengths + i, codeLengths + i + count, repeater); i += count; } m_dynamicLiteralDecoder.Initialize(codeLengths, hlit+257); if (hdist == 0 && codeLengths[hlit+257] == 0) { if (hlit != 0) // a single zero distance code length means all literals throw BadBlockErr(); } else m_dynamicDistanceDecoder.Initialize(codeLengths+hlit+257, hdist+1); m_nextDecode = LITERAL; } catch (HuffmanDecoder::Err &) { throw BadBlockErr(); } break; } default: throw BadBlockErr(); // reserved block type } m_state = DECODING_BODY; } bool Inflator::DecodeBody() { bool blockEnd = false; switch (m_blockType) { case 0: // stored CRYPTOPP_ASSERT(m_reader.BitsBuffered() == 0); while (!m_inQueue.IsEmpty() && !blockEnd) { size_t size; const byte *block = m_inQueue.Spy(size); size = UnsignedMin(m_storedLen, size); CRYPTOPP_ASSERT(size <= 0xffff); OutputString(block, size); m_inQueue.Skip(size); m_storedLen = m_storedLen - (word16)size; if (m_storedLen == 0) blockEnd = true; } break; case 1: // fixed codes case 2: // dynamic codes static const unsigned int lengthStarts[] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; static const unsigned int lengthExtraBits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; static const unsigned int distanceStarts[] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; static const unsigned int distanceExtraBits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; const HuffmanDecoder& literalDecoder = GetLiteralDecoder(); const HuffmanDecoder& distanceDecoder = GetDistanceDecoder(); switch (m_nextDecode) { case LITERAL: while (true) { if (!literalDecoder.Decode(m_reader, m_literal)) { m_nextDecode = LITERAL; break; } if (m_literal < 256) OutputByte((byte)m_literal); else if (m_literal == 256) // end of block { blockEnd = true; break; } else { if (m_literal > 285) throw BadBlockErr(); unsigned int bits; case LENGTH_BITS: bits = lengthExtraBits[m_literal-257]; if (!m_reader.FillBuffer(bits)) { m_nextDecode = LENGTH_BITS; break; } m_literal = m_reader.GetBits(bits) + lengthStarts[m_literal-257]; case DISTANCE: if (!distanceDecoder.Decode(m_reader, m_distance)) { m_nextDecode = DISTANCE; break; } case DISTANCE_BITS: // TODO: this surfaced during fuzzing. What do we do??? CRYPTOPP_ASSERT(m_distance < COUNTOF(distanceExtraBits)); bits = (m_distance >= COUNTOF(distanceExtraBits)) ? distanceExtraBits[29] : distanceExtraBits[m_distance]; if (!m_reader.FillBuffer(bits)) { m_nextDecode = DISTANCE_BITS; break; } m_distance = m_reader.GetBits(bits) + distanceStarts[m_distance]; OutputPast(m_literal, m_distance); } } break; default: CRYPTOPP_ASSERT(0); } } if (blockEnd) { if (m_eof) { FlushOutput(); m_reader.SkipBits(m_reader.BitsBuffered()%8); if (m_reader.BitsBuffered()) { // undo too much lookahead SecBlockWithHint<byte, 4> buffer(m_reader.BitsBuffered() / 8); for (unsigned int i=0; i<buffer.size(); i++) buffer[i] = (byte)m_reader.GetBits(8); m_inQueue.Unget(buffer, buffer.size()); } m_state = POST_STREAM; } else m_state = WAIT_HEADER; } return blockEnd; } void Inflator::FlushOutput() { if (m_state != PRE_STREAM) { CRYPTOPP_ASSERT(m_current >= m_lastFlush); ProcessDecompressedData(m_window + m_lastFlush, m_current - m_lastFlush); m_lastFlush = m_current; } } struct NewFixedLiteralDecoder { HuffmanDecoder * operator()() const { unsigned int codeLengths[288]; std::fill(codeLengths + 0, codeLengths + 144, 8); std::fill(codeLengths + 144, codeLengths + 256, 9); std::fill(codeLengths + 256, codeLengths + 280, 7); std::fill(codeLengths + 280, codeLengths + 288, 8); member_ptr<HuffmanDecoder> pDecoder(new HuffmanDecoder); pDecoder->Initialize(codeLengths, 288); return pDecoder.release(); } }; struct NewFixedDistanceDecoder { HuffmanDecoder * operator()() const { unsigned int codeLengths[32]; std::fill(codeLengths + 0, codeLengths + 32, 5); member_ptr<HuffmanDecoder> pDecoder(new HuffmanDecoder); pDecoder->Initialize(codeLengths, 32); return pDecoder.release(); } }; const HuffmanDecoder& Inflator::GetLiteralDecoder() const { return m_blockType == 1 ? Singleton<HuffmanDecoder, NewFixedLiteralDecoder>().Ref() : m_dynamicLiteralDecoder; } const HuffmanDecoder& Inflator::GetDistanceDecoder() const { return m_blockType == 1 ? Singleton<HuffmanDecoder, NewFixedDistanceDecoder>().Ref() : m_dynamicDistanceDecoder; } NAMESPACE_END
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_3390_1
crossvul-cpp_data_bad_1380_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/output-file.h" #include "hphp/runtime/base/execution-context.h" #include "hphp/runtime/base/runtime-error.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // constructor and destructor const StaticString s_php_output("php://output"); const StaticString s_php("PHP"); const StaticString s_output("Output"); OutputFile::OutputFile(const String& filename): File(true, s_php, s_output) { if (filename != s_php_output) { raise_fatal_error("not a php://output file "); } setIsLocal(true); } OutputFile::~OutputFile() { OutputFile::closeImpl(); } void OutputFile::sweep() { closeImpl(); File::sweep(); } bool OutputFile::open(const String& /*filename*/, const String& /*mode*/) { raise_fatal_error("cannot open a php://output file "); } bool OutputFile::close() { invokeFiltersOnClose(); return closeImpl(); } bool OutputFile::closeImpl() { *s_pcloseRet = 0; if (!isClosed()) { setIsClosed(true); return true; } return false; } /////////////////////////////////////////////////////////////////////////////// // virtual functions int64_t OutputFile::readImpl(char* /*buffer*/, int64_t /*length*/) { raise_warning("cannot read from a php://output stream"); return -1; } int OutputFile::getc() { raise_warning("cannot read from a php://output stream"); return -1; } int64_t OutputFile::writeImpl(const char *buffer, int64_t length) { assertx(length > 0); if (isClosed()) return 0; g_context->write(buffer, length); return length; } bool OutputFile::seek(int64_t /*offset*/, int /*whence*/ /* = SEEK_SET */) { raise_warning("cannot seek a php://output stream"); return false; } int64_t OutputFile::tell() { raise_warning("cannot tell a php://output stream"); return -1; } bool OutputFile::eof() { return false; } bool OutputFile::rewind() { raise_warning("cannot rewind a php://output stream"); return false; } bool OutputFile::flush() { if (!isClosed()) { g_context->flush(); return true; } return false; } bool OutputFile::truncate(int64_t /*size*/) { raise_warning("cannot truncate a php://output stream"); return false; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_1380_0
crossvul-cpp_data_good_611_1
/* * Load_stp.cpp * ------------ * Purpose: STP (Soundtracker Pro II) module loader * Notes : A few exotic effects aren't supported. * Multiple sample loops are supported, but only the first 10 can be used as cue points * (with 16xx and 18xx). * Fractional speed values and combined auto effects are handled whenever possible, * but some effects may be omitted (and there may be tempo accuracy issues). * Authors: Devin Acker * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. * * Wisdom from the Soundtracker Pro II manual: * "To create shorter patterns, simply create shorter patterns." */ #include "stdafx.h" #include "Loaders.h" OPENMPT_NAMESPACE_BEGIN // File header struct STPFileHeader { char magic[4]; uint16be version; uint8be numOrders; uint8be patternLength; uint8be orderList[128]; uint16be speed; uint16be speedFrac; uint16be timerCount; uint16be flags; uint32be reserved; uint16be midiCount; // always 50 uint8be midi[50]; uint16be numSamples; uint16be sampleStructSize; }; MPT_BINARY_STRUCT(STPFileHeader, 204) // Sample header (common part between all versions) struct STPSampleHeader { uint32be length; uint8be volume; uint8be reserved1; uint32be loopStart; uint32be loopLength; uint16be defaultCommand; // Default command to put next to note when editing patterns; not relevant for playback // The following 4 bytes are reserved in version 0 and 1. uint16be defaultPeriod; uint8be finetune; uint8be reserved2; void ConvertToMPT(ModSample &mptSmp) const { mptSmp.nLength = length; mptSmp.nVolume = 4u * std::min<uint16>(volume, 64); mptSmp.nLoopStart = loopStart; mptSmp.nLoopEnd = loopStart + loopLength; if(mptSmp.nLoopStart >= mptSmp.nLength) { mptSmp.nLoopStart = mptSmp.nLength - 1; } if(mptSmp.nLoopEnd > mptSmp.nLength) { mptSmp.nLoopEnd = mptSmp.nLength; } if(mptSmp.nLoopStart > mptSmp.nLoopEnd) { mptSmp.nLoopStart = 0; mptSmp.nLoopEnd = 0; } else if(mptSmp.nLoopEnd > mptSmp.nLoopStart) { mptSmp.uFlags.set(CHN_LOOP); mptSmp.cues[0] = mptSmp.nLoopStart; } } }; MPT_BINARY_STRUCT(STPSampleHeader, 20) struct STPLoopInfo { SmpLength loopStart; SmpLength loopLength; SAMPLEINDEX looped; SAMPLEINDEX nonLooped; }; typedef std::vector<STPLoopInfo> STPLoopList; static TEMPO ConvertTempo(uint16 ciaSpeed) { // 3546 is the resulting CIA timer value when using 4F7D (tempo 125 bpm) command in STProII return TEMPO((125.0 * 3546.0) / ciaSpeed); } static void ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData() || start >= src.nLength || src.nLength - start < len) { return; } dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } // only preserve cue points if the target sample length is the same if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } } static void ConvertLoopSequence(ModSample &smp, STPLoopList &loopList) { // This should only modify a sample if it has more than one loop // (otherwise, it behaves like a normal sample loop) if(!smp.HasSampleData() || loopList.size() < 2) return; ModSample newSmp = smp; newSmp.nLength = 0; newSmp.pSample = nullptr; size_t numLoops = loopList.size(); // Get the total length of the sample after combining all looped sections for(size_t i = 0; i < numLoops; i++) { STPLoopInfo &info = loopList[i]; // If adding this loop would cause the sample length to exceed maximum, // then limit and bail out if(info.loopStart >= smp.nLength || smp.nLength - info.loopStart < info.loopLength || newSmp.nLength > MAX_SAMPLE_LENGTH - info.loopLength) { numLoops = i; break; } newSmp.nLength += info.loopLength; } if(!newSmp.AllocateSample()) { return; } // start copying the looped sample data parts SmpLength start = 0; for(size_t i = 0; i < numLoops; i++) { STPLoopInfo &info = loopList[i]; memcpy(newSmp.pSample8 + start, smp.pSample8 + info.loopStart, info.loopLength); // update loop info based on position in edited sample info.loopStart = start; if(i > 0 && i <= mpt::size(newSmp.cues)) { newSmp.cues[i - 1] = start; } start += info.loopLength; } // replace old sample with new one smp.FreeSample(); smp = newSmp; smp.nLoopStart = 0; smp.nLoopEnd = smp.nLength; smp.uFlags.set(CHN_LOOP); } static bool ValidateHeader(const STPFileHeader &fileHeader) { if(std::memcmp(fileHeader.magic, "STP3", 4) || fileHeader.version > 2 || fileHeader.numOrders > 128 || fileHeader.numSamples >= MAX_SAMPLES || fileHeader.timerCount == 0 || fileHeader.midiCount != 50) { return false; } return true; } CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderSTP(MemoryFileReader file, const uint64 *pfilesize) { STPFileHeader fileHeader; if(!file.ReadStruct(fileHeader)) { return ProbeWantMoreData; } if(!ValidateHeader(fileHeader)) { return ProbeFailure; } MPT_UNREFERENCED_PARAMETER(pfilesize); return ProbeSuccess; } bool CSoundFile::ReadSTP(FileReader &file, ModLoadingFlags loadFlags) { file.Rewind(); STPFileHeader fileHeader; if(!file.ReadStruct(fileHeader)) { return false; } if(!ValidateHeader(fileHeader)) { return false; } if(loadFlags == onlyVerifyHeader) { return true; } InitializeGlobals(MOD_TYPE_STP); m_nChannels = 4; m_nSamples = 0; m_nDefaultSpeed = fileHeader.speed; m_nDefaultTempo = ConvertTempo(fileHeader.timerCount); m_nMinPeriod = 14 * 4; m_nMaxPeriod = 3424 * 4; ReadOrderFromArray(Order(), fileHeader.orderList, fileHeader.numOrders); std::vector<STPLoopList> loopInfo; // Non-looped versions of samples with loops (when needed) std::vector<SAMPLEINDEX> nonLooped; // Load sample headers SAMPLEINDEX samplesInFile = 0; for(SAMPLEINDEX smp = 0; smp < fileHeader.numSamples; smp++) { SAMPLEINDEX actualSmp = file.ReadUint16BE(); if(actualSmp == 0 || actualSmp >= MAX_SAMPLES) return false; uint32 chunkSize = fileHeader.sampleStructSize; if(fileHeader.version == 2) chunkSize = file.ReadUint32BE() - 2; FileReader chunk = file.ReadChunk(chunkSize); samplesInFile = m_nSamples = std::max(m_nSamples, actualSmp); ModSample &mptSmp = Samples[actualSmp]; mptSmp.Initialize(MOD_TYPE_MOD); if(fileHeader.version < 2) { // Read path chunk.ReadString<mpt::String::maybeNullTerminated>(mptSmp.filename, 31); // Ignore flags, they are all not relevant for us chunk.Skip(1); // Read filename / sample text chunk.ReadString<mpt::String::maybeNullTerminated>(m_szNames[actualSmp], 30); } else { std::string str; // Read path chunk.ReadNullString(str, 257); mpt::String::Copy(mptSmp.filename, str); // Ignore flags, they are all not relevant for us chunk.Skip(1); // Read filename / sample text chunk.ReadNullString(str, 31); mpt::String::Copy(m_szNames[actualSmp], str); // Seek to even boundary if(chunk.GetPosition() % 2u) chunk.Skip(1); } STPSampleHeader sampleHeader; chunk.ReadStruct(sampleHeader); sampleHeader.ConvertToMPT(mptSmp); if(fileHeader.version == 2) { mptSmp.nFineTune = static_cast<int8>(sampleHeader.finetune << 3); } if(fileHeader.version >= 1) { nonLooped.resize(samplesInFile); loopInfo.resize(samplesInFile); STPLoopList &loopList = loopInfo[actualSmp - 1]; loopList.clear(); uint16 numLoops = file.ReadUint16BE(); loopList.reserve(numLoops); STPLoopInfo loop; loop.looped = loop.nonLooped = 0; if(numLoops == 0 && mptSmp.uFlags[CHN_LOOP]) { loop.loopStart = mptSmp.nLoopStart; loop.loopLength = mptSmp.nLoopEnd - mptSmp.nLoopStart; loopList.push_back(loop); } else for(uint16 i = 0; i < numLoops; i++) { loop.loopStart = file.ReadUint32BE(); loop.loopLength = file.ReadUint32BE(); loopList.push_back(loop); } } } // Load patterns uint16 numPatterns = 128; if(fileHeader.version == 0) numPatterns = file.ReadUint16BE(); uint16 patternLength = fileHeader.patternLength; CHANNELINDEX channels = 4; if(fileHeader.version > 0) { // Scan for total number of channels FileReader::off_t patOffset = file.GetPosition(); for(uint16 pat = 0; pat < numPatterns; pat++) { PATTERNINDEX actualPat = file.ReadUint16BE(); if(actualPat == 0xFFFF) break; patternLength = file.ReadUint16BE(); channels = file.ReadUint16BE(); m_nChannels = std::max(m_nChannels, channels); file.Skip(channels * patternLength * 4u); } file.Seek(patOffset); if(m_nChannels > MAX_BASECHANNELS) return false; } struct ChannelMemory { uint8 autoFinePorta, autoPortaUp, autoPortaDown, autoVolSlide, autoVibrato; uint8 vibratoMem, autoTremolo, autoTonePorta, tonePortaMem; }; std::vector<ChannelMemory> channelMemory(m_nChannels); uint8 globalVolSlide = 0; uint8 speedFrac = static_cast<uint8>(fileHeader.speedFrac); for(uint16 pat = 0; pat < numPatterns; pat++) { PATTERNINDEX actualPat = pat; if(fileHeader.version > 0) { actualPat = file.ReadUint16BE(); if(actualPat == 0xFFFF) break; patternLength = file.ReadUint16BE(); channels = file.ReadUint16BE(); } if(!(loadFlags & loadPatternData) || !Patterns.Insert(actualPat, patternLength)) { file.Skip(channels * patternLength * 4u); continue; } for(ROWINDEX row = 0; row < patternLength; row++) { auto rowBase = Patterns[actualPat].GetRow(row); bool didGlobalVolSlide = false; // if a fractional speed value is in use then determine if we should stick a fine pattern delay somewhere bool shouldDelay; switch(speedFrac & 3) { default: shouldDelay = false; break; // 1/4 case 1: shouldDelay = (row & 3) == 0; break; // 1/2 case 2: shouldDelay = (row & 1) == 0; break; // 3/4 case 3: shouldDelay = (row & 3) != 3; break; } for(CHANNELINDEX chn = 0; chn < channels; chn++) { ChannelMemory &chnMem = channelMemory[chn]; ModCommand &m = rowBase[chn]; uint8 data[4]; file.ReadArray(data); m.instr = data[0]; m.note = data[1]; m.command = data[2]; m.param = data[3]; if(m.note) { m.note += 24 + NOTE_MIN; chnMem = ChannelMemory(); } // this is a nibble-swapped param value used for auto fine volside // and auto global fine volside uint8 swapped = (m.param >> 4) | (m.param << 4); if((m.command & 0xF0) == 0xF0) { // 12-bit CIA tempo uint16 ciaTempo = (static_cast<uint16>(m.command & 0x0F) << 8) | m.param; if(ciaTempo) { m.param = mpt::saturate_cast<ModCommand::PARAM>(Util::Round(ConvertTempo(ciaTempo).ToDouble())); m.command = CMD_TEMPO; } else { m.command = CMD_NONE; } } else switch(m.command) { case 0x00: // arpeggio if(m.param) m.command = CMD_ARPEGGIO; break; case 0x01: // portamento up m.command = CMD_PORTAMENTOUP; break; case 0x02: // portamento down m.command = CMD_PORTAMENTODOWN; break; case 0x03: // auto fine portamento up chnMem.autoFinePorta = 0x10 | std::min(m.param, ModCommand::PARAM(15)); chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = CMD_NONE; break; case 0x04: // auto fine portamento down chnMem.autoFinePorta = 0x20 | std::min(m.param, ModCommand::PARAM(15)); chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = CMD_NONE; break; case 0x05: // auto portamento up chnMem.autoFinePorta = 0; chnMem.autoPortaUp = m.param; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = CMD_NONE; break; case 0x06: // auto portamento down chnMem.autoFinePorta = 0; chnMem.autoPortaUp = 0; chnMem.autoPortaDown = m.param; chnMem.autoTonePorta = 0; m.command = CMD_NONE; break; case 0x07: // set global volume m.command = CMD_GLOBALVOLUME; globalVolSlide = 0; break; case 0x08: // auto global fine volume slide globalVolSlide = swapped; m.command = CMD_NONE; break; case 0x09: // fine portamento up m.command = CMD_MODCMDEX; m.param = 0x10 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x0A: // fine portamento down m.command = CMD_MODCMDEX; m.param = 0x20 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x0B: // auto fine volume slide chnMem.autoVolSlide = swapped; m.command = CMD_NONE; break; case 0x0C: // set volume m.volcmd = VOLCMD_VOLUME; m.vol = m.param; chnMem.autoVolSlide = 0; m.command = CMD_NONE; break; case 0x0D: // volume slide (param is swapped compared to .mod) if(m.param & 0xF0) { m.volcmd = VOLCMD_VOLSLIDEDOWN; m.vol = m.param >> 4; } else if(m.param & 0x0F) { m.volcmd = VOLCMD_VOLSLIDEUP; m.vol = m.param & 0xF; } chnMem.autoVolSlide = 0; m.command = CMD_NONE; break; case 0x0E: // set filter (also uses opposite value compared to .mod) m.command = CMD_MODCMDEX; m.param = 1 ^ (m.param ? 1 : 0); break; case 0x0F: // set speed m.command = CMD_SPEED; speedFrac = m.param & 0x0F; m.param >>= 4; break; case 0x10: // auto vibrato chnMem.autoVibrato = m.param; chnMem.vibratoMem = 0; m.command = CMD_NONE; break; case 0x11: // auto tremolo if(m.param & 0xF) chnMem.autoTremolo = m.param; else chnMem.autoTremolo = 0; m.command = CMD_NONE; break; case 0x12: // pattern break m.command = CMD_PATTERNBREAK; break; case 0x13: // auto tone portamento chnMem.autoFinePorta = 0; chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = m.param; chnMem.tonePortaMem = 0; m.command = CMD_NONE; break; case 0x14: // position jump m.command = CMD_POSITIONJUMP; break; case 0x16: // start loop sequence if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < std::min(mpt::size(ModSample().cues), loopList.size())) { m.volcmd = VOLCMD_OFFSET; m.vol = m.param; } } m.command = CMD_NONE; break; case 0x17: // play only loop nn if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < loopList.size()) { if(!loopList[m.param].looped && m_nSamples < MAX_SAMPLES - 1) loopList[m.param].looped = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].looped); } } m.command = CMD_NONE; break; case 0x18: // play sequence without loop if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < std::min(mpt::size(ModSample().cues), loopList.size())) { m.volcmd = VOLCMD_OFFSET; m.vol = m.param; } // switch to non-looped version of sample and create it if needed if(!nonLooped[m.instr - 1] && m_nSamples < MAX_SAMPLES - 1) nonLooped[m.instr - 1] = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(nonLooped[m.instr - 1]); } m.command = CMD_NONE; break; case 0x19: // play only loop nn without loop if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < loopList.size()) { if(!loopList[m.param].nonLooped && m_nSamples < MAX_SAMPLES-1) loopList[m.param].nonLooped = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].nonLooped); } } m.command = CMD_NONE; break; case 0x1D: // fine volume slide (nibble order also swapped) m.command = CMD_VOLUMESLIDE; m.param = swapped; if(m.param & 0xF0) // slide down m.param |= 0x0F; else if(m.param & 0x0F) m.param |= 0xF0; break; case 0x20: // "delayed fade" // just behave like either a normal fade or a notecut // depending on the speed if(m.param & 0xF0) { chnMem.autoVolSlide = m.param >> 4; m.command = CMD_NONE; } else { m.command = CMD_MODCMDEX; m.param = 0xC0 | (m.param & 0xF); } break; case 0x21: // note delay m.command = CMD_MODCMDEX; m.param = 0xD0 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x22: // retrigger note m.command = CMD_MODCMDEX; m.param = 0x90 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x49: // set sample offset m.command = CMD_OFFSET; break; case 0x4E: // other protracker commands (pattern loop / delay) if((m.param & 0xF0) == 0x60 || (m.param & 0xF0) == 0xE0) m.command = CMD_MODCMDEX; else m.command = CMD_NONE; break; case 0x4F: // set speed/tempo if(m.param < 0x20) { m.command = CMD_SPEED; speedFrac = 0; } else { m.command = CMD_TEMPO; } break; default: m.command = CMD_NONE; break; } bool didVolSlide = false; // try to put volume slide in volume command if(chnMem.autoVolSlide && m.volcmd == VOLCMD_NONE) { if(chnMem.autoVolSlide & 0xF0) { m.volcmd = VOLCMD_FINEVOLUP; m.vol = chnMem.autoVolSlide >> 4; } else { m.volcmd = VOLCMD_FINEVOLDOWN; m.vol = chnMem.autoVolSlide & 0xF; } didVolSlide = true; } // try to place/combine all remaining running effects. if(m.command == CMD_NONE) { if(chnMem.autoPortaUp) { m.command = CMD_PORTAMENTOUP; m.param = chnMem.autoPortaUp; } else if(chnMem.autoPortaDown) { m.command = CMD_PORTAMENTODOWN; m.param = chnMem.autoPortaDown; } else if(chnMem.autoFinePorta) { m.command = CMD_MODCMDEX; m.param = chnMem.autoFinePorta; } else if(chnMem.autoTonePorta) { m.command = CMD_TONEPORTAMENTO; m.param = chnMem.tonePortaMem = chnMem.autoTonePorta; } else if(chnMem.autoVibrato) { m.command = CMD_VIBRATO; m.param = chnMem.vibratoMem = chnMem.autoVibrato; } else if(!didVolSlide && chnMem.autoVolSlide) { m.command = CMD_VOLUMESLIDE; m.param = chnMem.autoVolSlide; // convert to a "fine" value by setting the other nibble to 0xF if(m.param & 0x0F) m.param |= 0xF0; else if(m.param & 0xF0) m.param |= 0x0F; didVolSlide = true; } else if(chnMem.autoTremolo) { m.command = CMD_TREMOLO; m.param = chnMem.autoTremolo; } else if(shouldDelay) { // insert a fine pattern delay here m.command = CMD_S3MCMDEX; m.param = 0x61; shouldDelay = false; } else if(!didGlobalVolSlide && globalVolSlide) { m.command = CMD_GLOBALVOLSLIDE; m.param = globalVolSlide; // convert to a "fine" value by setting the other nibble to 0xF if(m.param & 0x0F) m.param |= 0xF0; else if(m.param & 0xF0) m.param |= 0x0F; didGlobalVolSlide = true; } } } // TODO: create/use extra channels for global volslide/delay if needed } } // after we know how many channels there really are... m_nSamplePreAmp = 256 / m_nChannels; // Setup channel pan positions and volume SetupMODPanning(true); // Skip over scripts and drumpad info if(fileHeader.version > 0) { while(file.CanRead(2)) { uint16 scriptNum = file.ReadUint16BE(); if(scriptNum == 0xFFFF) break; file.Skip(2); uint32 length = file.ReadUint32BE(); file.Skip(length); } // Skip drumpad stuff file.Skip(17 * 2); } // Reading samples if(loadFlags & loadSampleData) { for(SAMPLEINDEX smp = 1; smp <= samplesInFile; smp++) if(Samples[smp].nLength) { SampleIO( SampleIO::_8bit, SampleIO::mono, SampleIO::littleEndian, SampleIO::signedPCM) .ReadSample(Samples[smp], file); if(smp > loopInfo.size()) continue; ConvertLoopSequence(Samples[smp], loopInfo[smp - 1]); // make a non-looping duplicate of this sample if needed if(nonLooped[smp - 1]) { ConvertLoopSlice(Samples[smp], Samples[nonLooped[smp - 1]], 0, Samples[smp].nLength, false); } for(const auto &info : loopInfo[smp - 1]) { // make duplicate samples for this individual section if needed if(info.looped) { ConvertLoopSlice(Samples[smp], Samples[info.looped], info.loopStart, info.loopLength, true); } if(info.nonLooped) { ConvertLoopSlice(Samples[smp], Samples[info.nonLooped], info.loopStart, info.loopLength, false); } } } } return true; } OPENMPT_NAMESPACE_END
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_611_1
crossvul-cpp_data_good_4259_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/JSObject.h" #include "hermes/VM/BuildMetadata.h" #include "hermes/VM/Callable.h" #include "hermes/VM/HostModel.h" #include "hermes/VM/InternalProperty.h" #include "hermes/VM/JSArray.h" #include "hermes/VM/JSDate.h" #include "hermes/VM/JSProxy.h" #include "hermes/VM/Operations.h" #include "llvh/ADT/SmallSet.h" namespace hermes { namespace vm { ObjectVTable JSObject::vt{ VTable( CellKind::ObjectKind, cellSize<JSObject>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{HeapSnapshot::NodeType::Object, JSObject::_snapshotNameImpl, JSObject::_snapshotAddEdgesImpl, nullptr, JSObject::_snapshotAddLocationsImpl}), JSObject::_getOwnIndexedRangeImpl, JSObject::_haveOwnIndexedImpl, JSObject::_getOwnIndexedPropertyFlagsImpl, JSObject::_getOwnIndexedImpl, JSObject::_setOwnIndexedImpl, JSObject::_deleteOwnIndexedImpl, JSObject::_checkAllOwnIndexedImpl, }; void ObjectBuildMeta(const GCCell *cell, Metadata::Builder &mb) { // This call is just for debugging and consistency purposes. mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSObject>()); const auto *self = static_cast<const JSObject *>(cell); mb.addField("parent", &self->parent_); mb.addField("class", &self->clazz_); mb.addField("propStorage", &self->propStorage_); // Declare the direct properties. static const char *directPropName[JSObject::DIRECT_PROPERTY_SLOTS] = { "directProp0", "directProp1", "directProp2", "directProp3"}; for (unsigned i = mb.getJSObjectOverlapSlots(); i < JSObject::DIRECT_PROPERTY_SLOTS; ++i) { mb.addField(directPropName[i], self->directProps() + i); } } #ifdef HERMESVM_SERIALIZE void JSObject::serializeObjectImpl( Serializer &s, const GCCell *cell, unsigned overlapSlots) { auto *self = vmcast<const JSObject>(cell); s.writeData(&self->flags_, sizeof(ObjectFlags)); s.writeRelocation(self->parent_.get(s.getRuntime())); s.writeRelocation(self->clazz_.get(s.getRuntime())); // propStorage_ : GCPointer<PropStorage> is also ArrayStorage. Serialize // *propStorage_ with this JSObject. bool hasArray = (bool)self->propStorage_; s.writeInt<uint8_t>(hasArray); if (hasArray) { ArrayStorage::serializeArrayStorage( s, self->propStorage_.get(s.getRuntime())); } // Record the number of overlap slots, so that the deserialization code // doesn't need to keep track of it. s.writeInt<uint8_t>(overlapSlots); for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) { s.writeHermesValue(self->directProps()[i]); } } void ObjectSerialize(Serializer &s, const GCCell *cell) { JSObject::serializeObjectImpl(s, cell, JSObject::numOverlapSlots<JSObject>()); s.endObject(cell); } void ObjectDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::ObjectKind && "Expected JSObject"); void *mem = d.getRuntime()->alloc</*fixedSize*/ true>(cellSize<JSObject>()); auto *obj = new (mem) JSObject(d, &JSObject::vt.base); d.endObject(obj); } JSObject::JSObject(Deserializer &d, const VTable *vtp) : GCCell(&d.getRuntime()->getHeap(), vtp) { d.readData(&flags_, sizeof(ObjectFlags)); d.readRelocation(&parent_, RelocationKind::GCPointer); d.readRelocation(&clazz_, RelocationKind::GCPointer); if (d.readInt<uint8_t>()) { propStorage_.set( d.getRuntime(), ArrayStorage::deserializeArrayStorage(d), &d.getRuntime()->getHeap()); } auto overlapSlots = d.readInt<uint8_t>(); for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) { d.readHermesValue(&directProps()[i]); } } #endif PseudoHandle<JSObject> JSObject::create( Runtime *runtime, Handle<JSObject> parentHandle) { JSObjectAlloc<JSObject> mem{runtime}; return mem.initToPseudoHandle(new (mem) JSObject( runtime, &vt.base, *parentHandle, runtime->getHiddenClassForPrototypeRaw( *parentHandle, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS), GCPointerBase::NoBarriers())); } PseudoHandle<JSObject> JSObject::create(Runtime *runtime) { JSObjectAlloc<JSObject> mem{runtime}; JSObject *objProto = runtime->objectPrototypeRawPtr; return mem.initToPseudoHandle(new (mem) JSObject( runtime, &vt.base, objProto, runtime->getHiddenClassForPrototypeRaw( objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS), GCPointerBase::NoBarriers())); } PseudoHandle<JSObject> JSObject::create( Runtime *runtime, unsigned propertyCount) { JSObjectAlloc<JSObject> mem{runtime}; JSObject *objProto = runtime->objectPrototypeRawPtr; auto self = mem.initToPseudoHandle(new (mem) JSObject( runtime, &vt.base, objProto, runtime->getHiddenClassForPrototypeRaw( objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS), GCPointerBase::NoBarriers())); return runtime->ignoreAllocationFailure( JSObject::allocatePropStorage(std::move(self), runtime, propertyCount)); } PseudoHandle<JSObject> JSObject::create( Runtime *runtime, Handle<HiddenClass> clazz) { auto obj = JSObject::create(runtime, clazz->getNumProperties()); obj->clazz_.set(runtime, *clazz, &runtime->getHeap()); // If the hidden class has index like property, we need to clear the fast path // flag. if (LLVM_UNLIKELY(obj->clazz_.get(runtime)->getHasIndexLikeProperties())) obj->flags_.fastIndexProperties = false; return obj; } void JSObject::initializeLazyObject( Runtime *runtime, Handle<JSObject> lazyObject) { assert(lazyObject->flags_.lazyObject && "object must be lazy"); // object is now assumed to be a regular object. lazyObject->flags_.lazyObject = 0; // only functions can be lazy. assert(vmisa<Callable>(lazyObject.get()) && "unexpected lazy object"); Callable::defineLazyProperties(Handle<Callable>::vmcast(lazyObject), runtime); } ObjectID JSObject::getObjectID(JSObject *self, Runtime *runtime) { if (LLVM_LIKELY(self->flags_.objectID)) return self->flags_.objectID; // Object ID does not yet exist, get next unique global ID.. self->flags_.objectID = runtime->generateNextObjectID(); // Make sure it is not zero. if (LLVM_UNLIKELY(!self->flags_.objectID)) --self->flags_.objectID; return self->flags_.objectID; } CallResult<PseudoHandle<JSObject>> JSObject::getPrototypeOf( PseudoHandle<JSObject> selfHandle, Runtime *runtime) { if (LLVM_LIKELY(!selfHandle->isProxyObject())) { return createPseudoHandle(selfHandle->getParent(runtime)); } return JSProxy::getPrototypeOf( runtime->makeHandle(std::move(selfHandle)), runtime); } namespace { CallResult<bool> proxyOpFlags( Runtime *runtime, PropOpFlags opFlags, const char *msg, CallResult<bool> res) { if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*res && opFlags.getThrowOnError()) { return runtime->raiseTypeError(msg); } return res; } } // namespace CallResult<bool> JSObject::setParent( JSObject *self, Runtime *runtime, JSObject *parent, PropOpFlags opFlags) { if (LLVM_UNLIKELY(self->isProxyObject())) { return proxyOpFlags( runtime, opFlags, "Object is not extensible.", JSProxy::setPrototypeOf( runtime->makeHandle(self), runtime, runtime->makeHandle(parent))); } // ES9 9.1.2 // 4. if (self->parent_.get(runtime) == parent) return true; // 5. if (!self->isExtensible()) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError("Object is not extensible."); } else { return false; } } // 6-8. Check for a prototype cycle. for (JSObject *cur = parent; cur; cur = cur->parent_.get(runtime)) { if (cur == self) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError("Prototype cycle detected"); } else { return false; } } else if (LLVM_UNLIKELY(cur->isProxyObject())) { // TODO this branch should also be used for module namespace and // immutable prototype exotic objects. break; } } // 9. self->parent_.set(runtime, parent, &runtime->getHeap()); // 10. return true; } void JSObject::allocateNewSlotStorage( Handle<JSObject> selfHandle, Runtime *runtime, SlotIndex newSlotIndex, Handle<> valueHandle) { // If it is a direct property, just store the value and we are done. if (LLVM_LIKELY(newSlotIndex < DIRECT_PROPERTY_SLOTS)) { selfHandle->directProps()[newSlotIndex].set( *valueHandle, &runtime->getHeap()); return; } // Make the slot index relative to the indirect storage. newSlotIndex -= DIRECT_PROPERTY_SLOTS; // Allocate a new property storage if not already allocated. if (LLVM_UNLIKELY(!selfHandle->propStorage_)) { // Allocate new storage. assert(newSlotIndex == 0 && "allocated slot must be at end"); auto arrRes = runtime->ignoreAllocationFailure( PropStorage::create(runtime, DEFAULT_PROPERTY_CAPACITY)); selfHandle->propStorage_.set( runtime, vmcast<PropStorage>(arrRes), &runtime->getHeap()); } else if (LLVM_UNLIKELY( newSlotIndex >= selfHandle->propStorage_.get(runtime)->capacity())) { // Reallocate the existing one. assert( newSlotIndex == selfHandle->propStorage_.get(runtime)->size() && "allocated slot must be at end"); auto hnd = runtime->makeMutableHandle(selfHandle->propStorage_); PropStorage::resize(hnd, runtime, newSlotIndex + 1); selfHandle->propStorage_.set(runtime, *hnd, &runtime->getHeap()); } { NoAllocScope scope{runtime}; auto *const propStorage = selfHandle->propStorage_.getNonNull(runtime); if (newSlotIndex >= propStorage->size()) { assert( newSlotIndex == propStorage->size() && "allocated slot must be at end"); PropStorage::resizeWithinCapacity(propStorage, runtime, newSlotIndex + 1); } // If we don't need to resize, just store it directly. propStorage->at(newSlotIndex).set(*valueHandle, &runtime->getHeap()); } } CallResult<PseudoHandle<>> JSObject::getNamedPropertyValue_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<JSObject> propObj, NamedPropertyDescriptor desc) { assert( !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject && "getNamedPropertyValue_RJS cannot be used with proxy objects"); if (LLVM_LIKELY(!desc.flags.accessor)) return createPseudoHandle(getNamedSlotValue(propObj.get(), runtime, desc)); auto *accessor = vmcast<PropertyAccessor>(getNamedSlotValue(propObj.get(), runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return accessor->getter.get(runtime)->executeCall0( runtime->makeHandle(accessor->getter), runtime, selfHandle); } CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<JSObject> propObj, ComputedPropertyDescriptor desc) { assert( !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject && "getComputedPropertyValue_RJS cannot be used with proxy objects"); if (LLVM_LIKELY(!desc.flags.accessor)) return createPseudoHandle( getComputedSlotValue(propObj.get(), runtime, desc)); auto *accessor = vmcast<PropertyAccessor>( getComputedSlotValue(propObj.get(), runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return accessor->getter.get(runtime)->executeCall0( runtime->makeHandle(accessor->getter), runtime, selfHandle); } CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<JSObject> propObj, ComputedPropertyDescriptor desc, Handle<> nameValHandle) { if (!propObj) { return createPseudoHandle(HermesValue::encodeEmptyValue()); } if (LLVM_LIKELY(!desc.flags.proxyObject)) { return JSObject::getComputedPropertyValue_RJS( selfHandle, runtime, propObj, desc); } CallResult<Handle<>> keyRes = toPropertyKey(runtime, nameValHandle); if (LLVM_UNLIKELY(keyRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } CallResult<bool> hasRes = JSProxy::hasComputed(propObj, runtime, *keyRes); if (LLVM_UNLIKELY(hasRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*hasRes) { return createPseudoHandle(HermesValue::encodeEmptyValue()); } return JSProxy::getComputed(propObj, runtime, *keyRes, selfHandle); } CallResult<Handle<JSArray>> JSObject::getOwnPropertyKeys( Handle<JSObject> selfHandle, Runtime *runtime, OwnKeysFlags okFlags) { assert( (okFlags.getIncludeNonSymbols() || okFlags.getIncludeSymbols()) && "Can't exclude symbols and strings"); if (LLVM_UNLIKELY( selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) { if (selfHandle->flags_.proxyObject) { CallResult<PseudoHandle<JSArray>> proxyRes = JSProxy::ownPropertyKeys(selfHandle, runtime, okFlags); if (LLVM_UNLIKELY(proxyRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return runtime->makeHandle(std::move(*proxyRes)); } assert(selfHandle->flags_.lazyObject && "descriptor flags are impossible"); initializeLazyObject(runtime, selfHandle); } auto range = getOwnIndexedRange(selfHandle.get(), runtime); // Estimate the capacity of the output array. This estimate is only // reasonable for the non-symbol case. uint32_t capacity = okFlags.getIncludeNonSymbols() ? (selfHandle->clazz_.get(runtime)->getNumProperties() + range.second - range.first) : 0; auto arrayRes = JSArray::create(runtime, capacity, 0); if (LLVM_UNLIKELY(arrayRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto array = runtime->makeHandle(std::move(*arrayRes)); // Optional array of SymbolIDs reported via host object API llvh::Optional<Handle<JSArray>> hostObjectSymbols; size_t hostObjectSymbolCount = 0; // If current object is a host object we need to deduplicate its properties llvh::SmallSet<SymbolID::RawType, 16> dedupSet; // Output index. uint32_t index = 0; // Avoid allocating a new handle per element. MutableHandle<> tmpHandle{runtime}; // Number of indexed properties. uint32_t numIndexed = 0; // Regular properties with names that are array indexes are stashed here, if // encountered. llvh::SmallVector<uint32_t, 8> indexNames{}; // Iterate the named properties excluding those which use Symbols. if (okFlags.getIncludeNonSymbols()) { // Get host object property names if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) { assert( range.first == range.second && "Host objects cannot own indexed range"); auto hostSymbolsRes = vmcast<HostObject>(selfHandle.get())->getHostPropertyNames(); if (hostSymbolsRes == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } if ((hostObjectSymbolCount = (**hostSymbolsRes)->getEndIndex()) != 0) { Handle<JSArray> hostSymbols = *hostSymbolsRes; hostObjectSymbols = std::move(hostSymbols); capacity += hostObjectSymbolCount; } } // Iterate the indexed properties. GCScopeMarkerRAII marker{runtime}; for (auto i = range.first; i != range.second; ++i) { auto res = getOwnIndexedPropertyFlags(selfHandle.get(), runtime, i); if (!res) continue; // If specified, check whether it is enumerable. if (!okFlags.getIncludeNonEnumerable() && !res->enumerable) continue; tmpHandle = HermesValue::encodeDoubleValue(i); JSArray::setElementAt(array, runtime, index++, tmpHandle); marker.flush(); } numIndexed = index; HiddenClass::forEachProperty( runtime->makeHandle(selfHandle->clazz_), runtime, [runtime, okFlags, array, hostObjectSymbolCount, &index, &indexNames, &tmpHandle, &dedupSet](SymbolID id, NamedPropertyDescriptor desc) { if (!isPropertyNamePrimitive(id)) { return; } // If specified, check whether it is enumerable. if (!okFlags.getIncludeNonEnumerable()) { if (!desc.flags.enumerable) return; } // Host properties might overlap with the ones recognized by the // hidden class. If we're dealing with a host object then keep track // of hidden class properties for the deduplication purposes. if (LLVM_UNLIKELY(hostObjectSymbolCount > 0)) { dedupSet.insert(id.unsafeGetRaw()); } // Check if this property is an integer index. If it is, we stash it // away to deal with it later. This check should be fast since most // property names don't start with a digit. auto propNameAsIndex = toArrayIndex( runtime->getIdentifierTable().getStringView(runtime, id)); if (LLVM_UNLIKELY(propNameAsIndex)) { indexNames.push_back(*propNameAsIndex); return; } tmpHandle = HermesValue::encodeStringValue( runtime->getStringPrimFromSymbolID(id)); JSArray::setElementAt(array, runtime, index++, tmpHandle); }); // Iterate over HostObject properties and append them to the array. Do not // append duplicates. if (LLVM_UNLIKELY(hostObjectSymbols)) { for (size_t i = 0; i < hostObjectSymbolCount; ++i) { assert( (*hostObjectSymbols)->at(runtime, i).isSymbol() && "Host object needs to return array of SymbolIDs"); marker.flush(); SymbolID id = (*hostObjectSymbols)->at(runtime, i).getSymbol(); if (dedupSet.count(id.unsafeGetRaw()) == 0) { dedupSet.insert(id.unsafeGetRaw()); assert( !InternalProperty::isInternal(id) && "host object returned reserved symbol"); auto propNameAsIndex = toArrayIndex( runtime->getIdentifierTable().getStringView(runtime, id)); if (LLVM_UNLIKELY(propNameAsIndex)) { indexNames.push_back(*propNameAsIndex); continue; } tmpHandle = HermesValue::encodeStringValue( runtime->getStringPrimFromSymbolID(id)); JSArray::setElementAt(array, runtime, index++, tmpHandle); } } } } // Now iterate the named properties again, including only Symbols. // We could iterate only once, if we chose to ignore (and disallow) // own properties on HostObjects, as we do with Proxies. if (okFlags.getIncludeSymbols()) { MutableHandle<SymbolID> idHandle{runtime}; HiddenClass::forEachProperty( runtime->makeHandle(selfHandle->clazz_), runtime, [runtime, okFlags, array, &index, &idHandle]( SymbolID id, NamedPropertyDescriptor desc) { if (!isSymbolPrimitive(id)) { return; } // If specified, check whether it is enumerable. if (!okFlags.getIncludeNonEnumerable()) { if (!desc.flags.enumerable) return; } idHandle = id; JSArray::setElementAt(array, runtime, index++, idHandle); }); } // The end (exclusive) of the named properties. uint32_t endNamed = index; // Properly set the length of the array. auto cr = JSArray::setLength( array, runtime, endNamed + indexNames.size(), PropOpFlags{}); (void)cr; assert( cr != ExecutionStatus::EXCEPTION && *cr && "JSArray::setLength() failed"); // If we have no index-like names, we are done. if (LLVM_LIKELY(indexNames.empty())) return array; // In the unlikely event that we encountered index-like names, we need to sort // them and merge them with the real indexed properties. Note that it is // guaranteed that there are no clashes. std::sort(indexNames.begin(), indexNames.end()); // Also make space for the new elements by shifting all the named properties // to the right. First, resize the array. JSArray::setStorageEndIndex(array, runtime, endNamed + indexNames.size()); // Shift the non-index property names. The region [numIndexed..endNamed) is // moved to [numIndexed+indexNames.size()..array->size()). // TODO: optimize this by implementing memcpy-like functionality in ArrayImpl. for (uint32_t last = endNamed, toLast = array->getEndIndex(); last != numIndexed;) { --last; --toLast; tmpHandle = array->at(runtime, last); JSArray::setElementAt(array, runtime, toLast, tmpHandle); } // Now we need to merge the indexes in indexNames and the array // [0..numIndexed). We start from the end and copy the larger element from // either array. // 1+ the destination position to copy into. for (uint32_t toLast = numIndexed + indexNames.size(), indexNamesLast = indexNames.size(); toLast != 0;) { if (numIndexed) { uint32_t a = (uint32_t)array->at(runtime, numIndexed - 1).getNumber(); uint32_t b; if (indexNamesLast && (b = indexNames[indexNamesLast - 1]) > a) { tmpHandle = HermesValue::encodeDoubleValue(b); --indexNamesLast; } else { tmpHandle = HermesValue::encodeDoubleValue(a); --numIndexed; } } else { assert(indexNamesLast && "prematurely ran out of source values"); tmpHandle = HermesValue::encodeDoubleValue(indexNames[indexNamesLast - 1]); --indexNamesLast; } --toLast; JSArray::setElementAt(array, runtime, toLast, tmpHandle); } return array; } /// Convert a value to string unless already converted /// \param nameValHandle [Handle<>] the value to convert /// \param str [MutableHandle<StringPrimitive>] the string is stored /// there. Must be initialized to null initially. #define LAZY_TO_STRING(runtime, nameValHandle, str) \ do { \ if (!str) { \ auto status = toString_RJS(runtime, nameValHandle); \ assert( \ status != ExecutionStatus::EXCEPTION && \ "toString() of primitive cannot fail"); \ str = status->get(); \ } \ } while (0) /// Convert a value to an identifier unless already converted /// \param nameValHandle [Handle<>] the value to convert /// \param id [SymbolID] the identifier is stored there. Must be initialized /// to INVALID_IDENTIFIER_ID initially. #define LAZY_TO_IDENTIFIER(runtime, nameValHandle, id) \ do { \ if (id.isInvalid()) { \ CallResult<Handle<SymbolID>> idRes = \ valueToSymbolID(runtime, nameValHandle); \ if (LLVM_UNLIKELY(idRes == ExecutionStatus::EXCEPTION)) { \ return ExecutionStatus::EXCEPTION; \ } \ id = **idRes; \ } \ } while (0) /// Convert a value to array index, if possible. /// \param nameValHandle [Handle<>] the value to convert /// \param str [MutableHandle<StringPrimitive>] the string is stored /// there. Must be initialized to null initially. /// \param arrayIndex [OptValue<uint32_t>] the array index is stored /// there. #define TO_ARRAY_INDEX(runtime, nameValHandle, str, arrayIndex) \ do { \ arrayIndex = toArrayIndexFastPath(*nameValHandle); \ if (!arrayIndex && !nameValHandle->isSymbol()) { \ LAZY_TO_STRING(runtime, nameValHandle, str); \ arrayIndex = toArrayIndex(runtime, str); \ } \ } while (0) /// \return true if the flags of a new property make it suitable for indexed /// storage. All new indexed properties are enumerable, writable and /// configurable and have no accessors. static bool canNewPropertyBeIndexed(DefinePropertyFlags dpf) { return dpf.setEnumerable && dpf.enumerable && dpf.setWritable && dpf.writable && dpf.setConfigurable && dpf.configurable && !dpf.setSetter && !dpf.setGetter; } struct JSObject::Helper { public: LLVM_ATTRIBUTE_ALWAYS_INLINE static ObjectFlags &flags(JSObject *self) { return self->flags_; } LLVM_ATTRIBUTE_ALWAYS_INLINE static OptValue<PropertyFlags> getOwnIndexedPropertyFlags(JSObject *self, Runtime *runtime, uint32_t index) { return JSObject::getOwnIndexedPropertyFlags(self, runtime, index); } LLVM_ATTRIBUTE_ALWAYS_INLINE static NamedPropertyDescriptor &castToNamedPropertyDescriptorRef( ComputedPropertyDescriptor &desc) { return desc.castToNamedPropertyDescriptorRef(); } }; namespace { /// ES5.1 8.12.1. /// A helper which takes a SymbolID which caches the conversion of /// nameValHandle if it's needed. It should be default constructed, /// and may or may not be set. This has been measured to be a useful /// perf win. Note that always_inline seems to be ignored on static /// methods, so this function has to be local to the cpp file in order /// to be inlined for the perf win. LLVM_ATTRIBUTE_ALWAYS_INLINE CallResult<bool> getOwnComputedPrimitiveDescriptorImpl( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, JSObject::IgnoreProxy ignoreProxy, SymbolID &id, ComputedPropertyDescriptor &desc) { assert( !nameValHandle->isObject() && "nameValHandle passed to " "getOwnComputedPrimitiveDescriptor " "cannot be an object"); // Try the fast paths first if we have "fast" index properties and the // property name is an obvious index. if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { if (JSObject::Helper::flags(*selfHandle).fastIndexProperties) { auto res = JSObject::Helper::getOwnIndexedPropertyFlags( selfHandle.get(), runtime, *arrayIndex); if (res) { // This a valid array index, residing in our indexed storage. desc.flags = *res; desc.flags.indexed = 1; desc.slot = *arrayIndex; return true; } // This a valid array index, but we don't have it in our indexed storage, // and we don't have index-like named properties. return false; } if (!selfHandle->getClass(runtime)->getHasIndexLikeProperties() && !selfHandle->isHostObject() && !selfHandle->isLazy() && !selfHandle->isProxyObject()) { // Early return to handle the case where an object definitely has no // index-like properties. This avoids allocating a new StringPrimitive and // uniquing it below. return false; } } // Convert the string to a SymbolID LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); // Look for a named property with this name. if (JSObject::getOwnNamedDescriptor( selfHandle, runtime, id, JSObject::Helper::castToNamedPropertyDescriptorRef(desc))) { return true; } if (LLVM_LIKELY( !JSObject::Helper::flags(*selfHandle).indexedStorage && !selfHandle->isLazy() && !selfHandle->isProxyObject())) { return false; } MutableHandle<StringPrimitive> strPrim{runtime}; // If we have indexed storage, perform potentially expensive conversions // to array index and check it. if (JSObject::Helper::flags(*selfHandle).indexedStorage) { // If the name is a valid integer array index, store it here. OptValue<uint32_t> arrayIndex; // Try to convert the property name to an array index. TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex); if (arrayIndex) { auto res = JSObject::Helper::getOwnIndexedPropertyFlags( selfHandle.get(), runtime, *arrayIndex); if (res) { desc.flags = *res; desc.flags.indexed = 1; desc.slot = *arrayIndex; return true; } } return false; } if (selfHandle->isLazy()) { JSObject::initializeLazyObject(runtime, selfHandle); return JSObject::getOwnComputedPrimitiveDescriptor( selfHandle, runtime, nameValHandle, ignoreProxy, desc); } assert(selfHandle->isProxyObject() && "descriptor flags are impossible"); if (ignoreProxy == JSObject::IgnoreProxy::Yes) { return false; } return JSProxy::getOwnProperty( selfHandle, runtime, nameValHandle, desc, nullptr); } } // namespace CallResult<bool> JSObject::getOwnComputedPrimitiveDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, JSObject::IgnoreProxy ignoreProxy, ComputedPropertyDescriptor &desc) { SymbolID id{}; return getOwnComputedPrimitiveDescriptorImpl( selfHandle, runtime, nameValHandle, ignoreProxy, id, desc); } CallResult<bool> JSObject::getOwnComputedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, ComputedPropertyDescriptor &desc) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return JSObject::getOwnComputedPrimitiveDescriptor( selfHandle, runtime, *converted, IgnoreProxy::No, desc); } CallResult<bool> JSObject::getOwnComputedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, ComputedPropertyDescriptor &desc, MutableHandle<> &valueOrAccessor) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // The proxy is ignored here so we can avoid calling // JSProxy::getOwnProperty twice on proxies, since // getOwnComputedPrimitiveDescriptor doesn't pass back the // valueOrAccessor. CallResult<bool> res = JSObject::getOwnComputedPrimitiveDescriptor( selfHandle, runtime, *converted, IgnoreProxy::Yes, desc); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (*res) { valueOrAccessor = getComputedSlotValue(selfHandle.get(), runtime, desc); return true; } if (LLVM_UNLIKELY(selfHandle->isProxyObject())) { return JSProxy::getOwnProperty( selfHandle, runtime, nameValHandle, desc, &valueOrAccessor); } return false; } JSObject *JSObject::getNamedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropertyFlags expectedFlags, NamedPropertyDescriptor &desc) { if (findProperty(selfHandle, runtime, name, expectedFlags, desc)) return *selfHandle; // Check here for host object flag. This means that "normal" own // properties above win over host-defined properties, but there's no // cost imposed on own property lookups. This should do what we // need in practice, and we can define host vs js property // disambiguation however we want. This is here in order to avoid // impacting perf for the common case where an own property exists // in normal storage. if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) { desc.flags.hostObject = true; desc.flags.writable = true; return *selfHandle; } if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) { assert( !selfHandle->flags_.proxyObject && "Proxy objects should never be lazy"); // Initialize the object and perform the lookup again. JSObject::initializeLazyObject(runtime, selfHandle); if (findProperty(selfHandle, runtime, name, expectedFlags, desc)) return *selfHandle; } if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) { desc.flags.proxyObject = true; return *selfHandle; } if (selfHandle->parent_) { MutableHandle<JSObject> mutableSelfHandle{ runtime, selfHandle->parent_.getNonNull(runtime)}; do { // Check the most common case first, at the cost of some code duplication. if (LLVM_LIKELY( !mutableSelfHandle->flags_.lazyObject && !mutableSelfHandle->flags_.hostObject && !mutableSelfHandle->flags_.proxyObject)) { findProp: if (findProperty( mutableSelfHandle, runtime, name, PropertyFlags::invalid(), desc)) { assert( !selfHandle->flags_.proxyObject && "Proxy object parents should never have own properties"); return *mutableSelfHandle; } } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.lazyObject)) { JSObject::initializeLazyObject(runtime, mutableSelfHandle); goto findProp; } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.hostObject)) { desc.flags.hostObject = true; desc.flags.writable = true; return *mutableSelfHandle; } else { assert( mutableSelfHandle->flags_.proxyObject && "descriptor flags are impossible"); desc.flags.proxyObject = true; return *mutableSelfHandle; } } while ((mutableSelfHandle = mutableSelfHandle->parent_.get(runtime))); } return nullptr; } ExecutionStatus JSObject::getComputedPrimitiveDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, MutableHandle<JSObject> &propObj, ComputedPropertyDescriptor &desc) { assert( !nameValHandle->isObject() && "nameValHandle passed to " "getComputedPrimitiveDescriptor cannot " "be an object"); propObj = selfHandle.get(); SymbolID id{}; GCScopeMarkerRAII marker{runtime}; do { // A proxy is ignored here so we can check the bit later and // return it back to the caller for additional processing. Handle<JSObject> loopHandle = propObj; CallResult<bool> res = getOwnComputedPrimitiveDescriptorImpl( loopHandle, runtime, nameValHandle, IgnoreProxy::Yes, id, desc); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (*res) { return ExecutionStatus::RETURNED; } if (LLVM_UNLIKELY(propObj->flags_.hostObject)) { desc.flags.hostObject = true; desc.flags.writable = true; return ExecutionStatus::RETURNED; } if (LLVM_UNLIKELY(propObj->flags_.proxyObject)) { desc.flags.proxyObject = true; return ExecutionStatus::RETURNED; } // This isn't a proxy, so use the faster getParent() instead of // getPrototypeOf. propObj = propObj->getParent(runtime); // Flush at the end of the loop to allow first iteration to be as fast as // possible. marker.flush(); } while (propObj); return ExecutionStatus::RETURNED; } ExecutionStatus JSObject::getComputedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, MutableHandle<JSObject> &propObj, ComputedPropertyDescriptor &desc) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return getComputedPrimitiveDescriptor( selfHandle, runtime, *converted, propObj, desc); } CallResult<PseudoHandle<>> JSObject::getNamedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, Handle<> receiver, PropOpFlags opFlags, PropertyCacheEntry *cacheEntry) { NamedPropertyDescriptor desc; // Locate the descriptor. propObj contains the object which may be anywhere // along the prototype chain. JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc); if (!propObj) { if (LLVM_UNLIKELY(opFlags.getMustExist())) { return runtime->raiseReferenceError( TwineChar16("Property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' doesn't exist"); } return createPseudoHandle(HermesValue::encodeUndefinedValue()); } if (LLVM_LIKELY( !desc.flags.accessor && !desc.flags.hostObject && !desc.flags.proxyObject)) { // Populate the cache if requested. if (cacheEntry && !propObj->getClass(runtime)->isDictionaryNoCache()) { cacheEntry->clazz = propObj->getClassGCPtr().getStorageType(); cacheEntry->slot = desc.slot; } return createPseudoHandle(getNamedSlotValue(propObj, runtime, desc)); } if (desc.flags.accessor) { auto *accessor = vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return Callable::executeCall0( runtime->makeHandle(accessor->getter), runtime, receiver); } else if (desc.flags.hostObject) { auto res = vmcast<HostObject>(propObj)->get(name); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return createPseudoHandle(*res); } else { assert(desc.flags.proxyObject && "descriptor flags are impossible"); return JSProxy::getNamed( runtime->makeHandle(propObj), runtime, name, receiver); } } CallResult<PseudoHandle<>> JSObject::getNamedOrIndexed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropOpFlags opFlags) { if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) { // Note that getStringView can be satisfied without materializing the // Identifier. const auto strView = runtime->getIdentifierTable().getStringView(runtime, name); if (auto nameAsIndex = toArrayIndex(strView)) { return getComputed_RJS( selfHandle, runtime, runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex))); } // Here we have indexed properties but the symbol was not index-like. // Fall through to getNamed(). } return getNamed_RJS(selfHandle, runtime, name, opFlags); } CallResult<PseudoHandle<>> JSObject::getComputedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, Handle<> receiver) { // Try the fast-path first: no "index-like" properties and the "name" already // is a valid integer index. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { // Do we have this value present in our array storage? If so, return it. PseudoHandle<> ourValue = createPseudoHandle( getOwnIndexed(selfHandle.get(), runtime, *arrayIndex)); if (LLVM_LIKELY(!ourValue->isEmpty())) return ourValue; } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; // Locate the descriptor. propObj contains the object which may be anywhere // along the prototype chain. MutableHandle<JSObject> propObj{runtime}; if (LLVM_UNLIKELY( getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!propObj) return createPseudoHandle(HermesValue::encodeUndefinedValue()); if (LLVM_LIKELY( !desc.flags.accessor && !desc.flags.hostObject && !desc.flags.proxyObject)) return createPseudoHandle( getComputedSlotValue(propObj.get(), runtime, desc)); if (desc.flags.accessor) { auto *accessor = vmcast<PropertyAccessor>( getComputedSlotValue(propObj.get(), runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return accessor->getter.get(runtime)->executeCall0( runtime->makeHandle(accessor->getter), runtime, receiver); } else if (desc.flags.hostObject) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); auto propRes = vmcast<HostObject>(propObj.get())->get(id); if (propRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return createPseudoHandle(*propRes); } else { assert(desc.flags.proxyObject && "descriptor flags are impossible"); CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return JSProxy::getComputed(propObj, runtime, *key, receiver); } } CallResult<bool> JSObject::hasNamed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name) { NamedPropertyDescriptor desc; JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc); if (propObj == nullptr) { return false; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { return JSProxy::hasNamed(runtime->makeHandle(propObj), runtime, name); } return true; } CallResult<bool> JSObject::hasNamedOrIndexed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name) { if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) { const auto strView = runtime->getIdentifierTable().getStringView(runtime, name); if (auto nameAsIndex = toArrayIndex(strView)) { if (haveOwnIndexed(selfHandle.get(), runtime, *nameAsIndex)) { return true; } if (selfHandle->flags_.fastIndexProperties) { return false; } } // Here we have indexed properties but the symbol was not stored in the // indexedStorage. // Fall through to getNamed(). } return hasNamed(selfHandle, runtime, name); } CallResult<bool> JSObject::hasComputed( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle) { // Try the fast-path first: no "index-like" properties and the "name" already // is a valid integer index. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { // Do we have this value present in our array storage? If so, return true. if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) { return true; } } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; MutableHandle<JSObject> propObj{runtime}; if (getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } if (!propObj) { return false; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return JSProxy::hasComputed(propObj, runtime, *key); } // For compatibility with polyfills we want to pretend that all HostObject // properties are "own" properties in 'in'. Since there is no way to check for // a HostObject property, we must always assume success. In practice the // property name would have been obtained from enumerating the properties in // JS code that looks something like this: // for(key in hostObj) { // if (key in hostObj) // ... // } return true; } static ExecutionStatus raiseErrorForOverridingStaticBuiltin( Handle<JSObject> selfHandle, Runtime *runtime, Handle<SymbolID> name) { Handle<StringPrimitive> methodNameHnd = runtime->makeHandle(runtime->getStringPrimFromSymbolID(name.get())); // If the 'name' property does not exist or is an accessor, we don't display // the name. NamedPropertyDescriptor desc; auto *obj = JSObject::getNamedDescriptor( selfHandle, runtime, Predefined::getSymbolID(Predefined::name), desc); assert( !selfHandle->isProxyObject() && "raiseErrorForOverridingStaticBuiltin cannot be used with proxy objects"); if (!obj || desc.flags.accessor) { return runtime->raiseTypeError( TwineChar16("Attempting to override read-only builtin method '") + TwineChar16(methodNameHnd.get()) + "'"); } // Display the name property of the builtin object if it is a string. StringPrimitive *objName = dyn_vmcast<StringPrimitive>( JSObject::getNamedSlotValue(selfHandle.get(), runtime, desc)); if (!objName) { return runtime->raiseTypeError( TwineChar16("Attempting to override read-only builtin method '") + TwineChar16(methodNameHnd.get()) + "'"); } return runtime->raiseTypeError( TwineChar16("Attempting to override read-only builtin method '") + TwineChar16(objName) + "." + TwineChar16(methodNameHnd.get()) + "'"); } CallResult<bool> JSObject::putNamedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, Handle<> valueHandle, Handle<> receiver, PropOpFlags opFlags) { NamedPropertyDescriptor desc; // Look for the property in this object or along the prototype chain. JSObject *propObj = getNamedDescriptor( selfHandle, runtime, name, PropertyFlags::defaultNewNamedPropertyFlags(), desc); // If the property exists (or, we hit a proxy/hostobject on the way // up the chain) if (propObj) { // Get the simple case out of the way: If the property already // exists on selfHandle, is not an accessor, selfHandle and // receiver are the same, selfHandle is not a host // object/proxy/internal setter, and the property is writable, // just write into the same slot. if (LLVM_LIKELY( *selfHandle == propObj && selfHandle.getHermesValue().getRaw() == receiver->getRaw() && !desc.flags.accessor && !desc.flags.internalSetter && !desc.flags.hostObject && !desc.flags.proxyObject && desc.flags.writable)) { setNamedSlotValue( *selfHandle, runtime, desc, valueHandle.getHermesValue()); return true; } if (LLVM_UNLIKELY(desc.flags.accessor)) { auto *accessor = vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc)); // If it is a read-only accessor, fail. if (!accessor->setter) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Cannot assign to property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' which has only a getter"); } return false; } // Execute the accessor on this object. if (accessor->setter.get(runtime)->executeCall1( runtime->makeHandle(accessor->setter), runtime, receiver, *valueHandle) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return true; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { assert( !opFlags.getMustExist() && "MustExist cannot be used with Proxy objects"); CallResult<bool> setRes = JSProxy::setNamed( runtime->makeHandle(propObj), runtime, name, valueHandle, receiver); if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*setRes && opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Proxy set returned false for property '") + runtime->getIdentifierTable().getStringView(runtime, name) + "'"); } return setRes; } if (LLVM_UNLIKELY(!desc.flags.writable)) { if (desc.flags.staticBuiltin) { return raiseErrorForOverridingStaticBuiltin( selfHandle, runtime, runtime->makeHandle(name)); } if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Cannot assign to read-only property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "'"); } return false; } if (*selfHandle == propObj && desc.flags.internalSetter) { return internalSetter( selfHandle, runtime, name, desc, valueHandle, opFlags); } } // The property does not exist as an conventional own property on // this object. MutableHandle<JSObject> receiverHandle{runtime, *selfHandle}; if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() || receiverHandle->isHostObject() || receiverHandle->isProxyObject()) { if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) { receiverHandle = dyn_vmcast<JSObject>(*receiver); } if (!receiverHandle) { return false; } if (getOwnNamedDescriptor(receiverHandle, runtime, name, desc)) { if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) { return false; } assert( !receiverHandle->isHostObject() && !receiverHandle->isProxyObject() && "getOwnNamedDescriptor never sets hostObject or proxyObject flags"); setNamedSlotValue( *receiverHandle, runtime, desc, valueHandle.getHermesValue()); return true; } // Now deal with host and proxy object cases. We need to call // getOwnComputedPrimitiveDescriptor because it knows how to call // the [[getOwnProperty]] Proxy impl if needed. if (LLVM_UNLIKELY( receiverHandle->isHostObject() || receiverHandle->isProxyObject())) { if (receiverHandle->isHostObject()) { return vmcast<HostObject>(receiverHandle.get()) ->set(name, *valueHandle); } ComputedPropertyDescriptor desc; Handle<> nameValHandle = runtime->makeHandle(name); CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor( receiverHandle, runtime, nameValHandle, IgnoreProxy::No, desc); if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } DefinePropertyFlags dpf; if (*descDefinedRes) { dpf.setValue = 1; } else { dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); } return JSProxy::defineOwnProperty( receiverHandle, runtime, nameValHandle, dpf, valueHandle, opFlags); } } // Does the caller require it to exist? if (LLVM_UNLIKELY(opFlags.getMustExist())) { return runtime->raiseReferenceError( TwineChar16("Property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' doesn't exist"); } // Add a new property. return addOwnProperty( receiverHandle, runtime, name, DefinePropertyFlags::getDefaultNewPropertyFlags(), valueHandle, opFlags); } CallResult<bool> JSObject::putNamedOrIndexed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, Handle<> valueHandle, PropOpFlags opFlags) { if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) { // Note that getStringView can be satisfied without materializing the // Identifier. const auto strView = runtime->getIdentifierTable().getStringView(runtime, name); if (auto nameAsIndex = toArrayIndex(strView)) { return putComputed_RJS( selfHandle, runtime, runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex)), valueHandle, opFlags); } // Here we have indexed properties but the symbol was not index-like. // Fall through to putNamed(). } return putNamed_RJS(selfHandle, runtime, name, valueHandle, opFlags); } CallResult<bool> JSObject::putComputedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, Handle<> valueHandle, Handle<> receiver, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "mustExist flag cannot be used with computed properties"); // Try the fast-path first: has "index-like" properties, the "name" // already is a valid integer index, selfHandle and receiver are the // same, and it is present in storage. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) { if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) { auto result = setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_LIKELY(*result)) return true; if (opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError( "Cannot assign to read-only property"); } return false; } } } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; // Look for the property in this object or along the prototype chain. MutableHandle<JSObject> propObj{runtime}; if (LLVM_UNLIKELY( getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // If the property exists (or, we hit a proxy/hostobject on the way // up the chain) if (propObj) { // Get the simple case out of the way: If the property already // exists on selfHandle, is not an accessor, selfHandle and // receiver are the same, selfHandle is not a host // object/proxy/internal setter, and the property is writable, // just write into the same slot. if (LLVM_LIKELY( selfHandle == propObj && selfHandle.getHermesValue().getRaw() == receiver->getRaw() && !desc.flags.accessor && !desc.flags.internalSetter && !desc.flags.hostObject && !desc.flags.proxyObject && desc.flags.writable)) { if (LLVM_UNLIKELY( setComputedSlotValue(selfHandle, runtime, desc, valueHandle) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } // Is it an accessor? if (LLVM_UNLIKELY(desc.flags.accessor)) { auto *accessor = vmcast<PropertyAccessor>( getComputedSlotValue(propObj.get(), runtime, desc)); // If it is a read-only accessor, fail. if (!accessor->setter) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeErrorForValue( "Cannot assign to property ", nameValPrimitiveHandle, " which has only a getter"); } return false; } // Execute the accessor on this object. if (accessor->setter.get(runtime)->executeCall1( runtime->makeHandle(accessor->setter), runtime, receiver, valueHandle.get()) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return true; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { assert( !opFlags.getMustExist() && "MustExist cannot be used with Proxy objects"); CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; CallResult<bool> setRes = JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver); if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*setRes && opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError( TwineChar16("Proxy trap returned false for property")); } return setRes; } if (LLVM_UNLIKELY(!desc.flags.writable)) { if (desc.flags.staticBuiltin) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); return raiseErrorForOverridingStaticBuiltin( selfHandle, runtime, runtime->makeHandle(id)); } if (opFlags.getThrowOnError()) { return runtime->raiseTypeErrorForValue( "Cannot assign to read-only property ", nameValPrimitiveHandle, ""); } return false; } if (selfHandle == propObj && desc.flags.internalSetter) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); return internalSetter( selfHandle, runtime, id, desc.castToNamedPropertyDescriptorRef(), valueHandle, opFlags); } } // The property does not exist as an conventional own property on // this object. MutableHandle<JSObject> receiverHandle{runtime, *selfHandle}; if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() || receiverHandle->isHostObject() || receiverHandle->isProxyObject()) { if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) { receiverHandle = dyn_vmcast<JSObject>(*receiver); } if (!receiverHandle) { return false; } CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor( receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc); if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } DefinePropertyFlags dpf; if (*descDefinedRes) { if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) { return false; } if (LLVM_LIKELY( !desc.flags.internalSetter && !receiverHandle->isHostObject() && !receiverHandle->isProxyObject())) { if (LLVM_UNLIKELY( setComputedSlotValue( receiverHandle, runtime, desc, valueHandle) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } } if (LLVM_UNLIKELY( desc.flags.internalSetter || receiverHandle->isHostObject() || receiverHandle->isProxyObject())) { // If putComputed is called on a proxy whose target's prototype // is an array with a propname of 'length', then internalSetter // will be true, and the receiver will be a proxy. In that case, // proxy wins. if (receiverHandle->isProxyObject()) { if (*descDefinedRes) { dpf.setValue = 1; } else { dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); } return JSProxy::defineOwnProperty( receiverHandle, runtime, nameValPrimitiveHandle, dpf, valueHandle, opFlags); } SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); if (desc.flags.internalSetter) { return internalSetter( receiverHandle, runtime, id, desc.castToNamedPropertyDescriptorRef(), valueHandle, opFlags); } assert( receiverHandle->isHostObject() && "descriptor flags are impossible"); return vmcast<HostObject>(receiverHandle.get())->set(id, *valueHandle); } } /// Can we add more properties? if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "cannot add a new property"); // TODO: better message. } return false; } // If we have indexed storage we must check whether the property is an index, // and if it is, store it in indexed storage. if (receiverHandle->flags_.indexedStorage) { OptValue<uint32_t> arrayIndex; MutableHandle<StringPrimitive> strPrim{runtime}; TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex); if (arrayIndex) { // Check whether we need to update array's ".length" property. if (auto *array = dyn_vmcast<JSArray>(receiverHandle.get())) { if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) { auto cr = putNamed_RJS( receiverHandle, runtime, Predefined::getSymbolID(Predefined::length), runtime->makeHandle( HermesValue::encodeNumberValue(*arrayIndex + 1)), opFlags); if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_UNLIKELY(!*cr)) return false; } } auto result = setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_LIKELY(*result)) return true; if (opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError("Cannot assign to read-only property"); } return false; } } SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); // Add a new named property. return addOwnProperty( receiverHandle, runtime, id, DefinePropertyFlags::getDefaultNewPropertyFlags(), valueHandle, opFlags); } CallResult<bool> JSObject::deleteNamed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "mustExist cannot be specified when deleting"); // Find the property by name. NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, name, desc); // If the property doesn't exist in this object, return success. if (!pos) { if (LLVM_LIKELY( !selfHandle->flags_.lazyObject && !selfHandle->flags_.proxyObject)) { return true; } else if (selfHandle->flags_.lazyObject) { // object is lazy, initialize and read again. initializeLazyObject(runtime, selfHandle); pos = findProperty(selfHandle, runtime, name, desc); if (!pos) // still not there, return true. return true; } else { assert(selfHandle->flags_.proxyObject && "object flags are impossible"); return proxyOpFlags( runtime, opFlags, "Proxy delete returned false", JSProxy::deleteNamed(selfHandle, runtime, name)); } } // If the property isn't configurable, fail. if (LLVM_UNLIKELY(!desc.flags.configurable)) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' is not configurable"); } return false; } // Clear the deleted property value to prevent memory leaks. setNamedSlotValue( *selfHandle, runtime, desc, HermesValue::encodeEmptyValue()); // Perform the actual deletion. auto newClazz = HiddenClass::deleteProperty( runtime->makeHandle(selfHandle->clazz_), runtime, *pos); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); return true; } CallResult<bool> JSObject::deleteComputed( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "mustExist cannot be specified when deleting"); // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; // If the name is a valid integer array index, store it here. OptValue<uint32_t> arrayIndex; // If we have indexed storage, we must attempt to convert the name to array // index, even if the conversion is expensive. if (selfHandle->flags_.indexedStorage) { MutableHandle<StringPrimitive> strPrim{runtime}; TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex); } // Try the fast-path first: the "name" is a valid array index and we don't // have "index-like" named properties. if (arrayIndex && selfHandle->flags_.fastIndexProperties) { // Delete the indexed property. if (deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) return true; // Cannot delete property (for example this may be a typed array). if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot delete property"); } return false; } // slow path, check if object is lazy before continuing. if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) { // initialize and try again. initializeLazyObject(runtime, selfHandle); return deleteComputed(selfHandle, runtime, nameValHandle, opFlags); } // Convert the string to an SymbolID; SymbolID id; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); // Find the property by name. NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, id, desc); // If the property exists, make sure it is configurable. if (pos) { // If the property isn't configurable, fail. if (LLVM_UNLIKELY(!desc.flags.configurable)) { if (opFlags.getThrowOnError()) { // TODO: a better message. return runtime->raiseTypeError("Property is not configurable"); } return false; } } // At this point we know that the named property either doesn't exist, or // is configurable and so can be deleted, or the object is a Proxy. // If it is an "index-like" property, we must also delete the "shadow" indexed // property in order to keep Array.length correct. if (arrayIndex) { if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) { // Cannot delete property (for example this may be a typed array). if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot delete property"); } return false; } } if (pos) { // delete the named property (if it exists). // Clear the deleted property value to prevent memory leaks. setNamedSlotValue( *selfHandle, runtime, desc, HermesValue::encodeEmptyValue()); // Remove the property descriptor. auto newClazz = HiddenClass::deleteProperty( runtime->makeHandle(selfHandle->clazz_), runtime, *pos); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); } else if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) { CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return proxyOpFlags( runtime, opFlags, "Proxy delete returned false", JSProxy::deleteComputed(selfHandle, runtime, *key)); } return true; } CallResult<bool> JSObject::defineOwnPropertyInternal( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "cannot use mustExist with defineOwnProperty"); assert( !(dpFlags.setValue && dpFlags.isAccessor()) && "Cannot set both value and accessor"); assert( (dpFlags.setValue || dpFlags.isAccessor() || valueOrAccessor.get().isUndefined()) && "value must be undefined when all of setValue/setSetter/setGetter are " "false"); #ifndef NDEBUG if (dpFlags.isAccessor()) { assert(valueOrAccessor.get().isPointer() && "accessor must be non-empty"); assert( !dpFlags.setWritable && !dpFlags.writable && "writable must not be set with accessors"); } #endif // Is it an existing property. NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, name, desc); if (pos) { return updateOwnProperty( selfHandle, runtime, name, *pos, desc, dpFlags, valueOrAccessor, opFlags); } if (LLVM_UNLIKELY( selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) { if (selfHandle->flags_.proxyObject) { return JSProxy::defineOwnProperty( selfHandle, runtime, name.isUniqued() ? runtime->makeHandle(HermesValue::encodeStringValue( runtime->getStringPrimFromSymbolID(name))) : runtime->makeHandle(name), dpFlags, valueOrAccessor, opFlags); } assert(selfHandle->flags_.lazyObject && "descriptor flags are impossible"); // if the property was not found and the object is lazy we need to // initialize it and try again. JSObject::initializeLazyObject(runtime, selfHandle); return defineOwnPropertyInternal( selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags); } return addOwnProperty( selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags); } ExecutionStatus JSObject::defineNewOwnProperty( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropertyFlags propertyFlags, Handle<> valueOrAccessor) { assert( !selfHandle->flags_.proxyObject && "definedNewOwnProperty cannot be used with proxy objects"); assert( !(propertyFlags.accessor && !valueOrAccessor.get().isPointer()) && "accessor must be non-empty"); assert( !(propertyFlags.accessor && propertyFlags.writable) && "writable must not be set with accessors"); assert( !HiddenClass::debugIsPropertyDefined( selfHandle->clazz_.get(runtime), runtime, name) && "new property is already defined"); return addOwnPropertyImpl( selfHandle, runtime, name, propertyFlags, valueOrAccessor); } CallResult<bool> JSObject::defineOwnComputedPrimitive( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { assert( !nameValHandle->isObject() && "nameValHandle passed to " "defineOwnComputedPrimitive() cannot be " "an object"); assert( !opFlags.getMustExist() && "cannot use mustExist with defineOwnProperty"); assert( !(dpFlags.setValue && dpFlags.isAccessor()) && "Cannot set both value and accessor"); assert( (dpFlags.setValue || dpFlags.isAccessor() || valueOrAccessor.get().isUndefined()) && "value must be undefined when all of setValue/setSetter/setGetter are " "false"); assert( !dpFlags.enableInternalSetter && "Cannot set internalSetter on a computed property"); #ifndef NDEBUG if (dpFlags.isAccessor()) { assert(valueOrAccessor.get().isPointer() && "accessor must be non-empty"); assert( !dpFlags.setWritable && !dpFlags.writable && "writable must not be set with accessors"); } #endif // If the name is a valid integer array index, store it here. OptValue<uint32_t> arrayIndex; // If we have indexed storage, we must attempt to convert the name to array // index, even if the conversion is expensive. if (selfHandle->flags_.indexedStorage) { MutableHandle<StringPrimitive> strPrim{runtime}; TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex); } SymbolID id{}; // If not storing a property with an array index name, or if we don't have // indexed storage, just pass to the named routine. if (!arrayIndex) { LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); return defineOwnPropertyInternal( selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags); } // At this point we know that we have indexed storage and that the property // has an index-like name. // First check if a named property with the same name exists. if (selfHandle->clazz_.get(runtime)->getHasIndexLikeProperties()) { LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, id, desc); // If we found a named property, update it. if (pos) { return updateOwnProperty( selfHandle, runtime, id, *pos, desc, dpFlags, valueOrAccessor, opFlags); } } // Does an indexed property with that index exist? auto indexedPropPresent = getOwnIndexedPropertyFlags(selfHandle.get(), runtime, *arrayIndex); if (indexedPropPresent) { // The current value of the property. HermesValue curValueOrAccessor = getOwnIndexed(selfHandle.get(), runtime, *arrayIndex); auto updateStatus = checkPropertyUpdate( runtime, *indexedPropPresent, dpFlags, curValueOrAccessor, valueOrAccessor, opFlags); if (updateStatus == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (updateStatus->first == PropertyUpdateStatus::failed) return false; // The property update is valid, but can the property remain an "indexed" // property, or do we need to convert it to a named property? // If the property flags didn't change, the property remains indexed. if (updateStatus->second == *indexedPropPresent) { // If the value doesn't change, we are done. if (updateStatus->first == PropertyUpdateStatus::done) return true; // If we successfully updated the value, we are done. auto result = setOwnIndexed(selfHandle, runtime, *arrayIndex, valueOrAccessor); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (*result) return true; if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError( "cannot change read-only property value"); } return false; } // OK, we need to convert an indexed property to a named one. // Check whether to use the supplied value, or to reuse the old one, as we // are simply reconfiguring it. MutableHandle<> value{runtime}; if (dpFlags.setValue || dpFlags.isAccessor()) { value = valueOrAccessor.get(); } else { value = curValueOrAccessor; } // Update dpFlags to match the existing property flags. dpFlags.setEnumerable = 1; dpFlags.setWritable = 1; dpFlags.setConfigurable = 1; dpFlags.enumerable = updateStatus->second.enumerable; dpFlags.writable = updateStatus->second.writable; dpFlags.configurable = updateStatus->second.configurable; // Delete the existing indexed property. if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) { if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot define property"); } return false; } // Add the new named property. LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); return addOwnProperty(selfHandle, runtime, id, dpFlags, value, opFlags); } /// Can we add new properties? if (!selfHandle->isExtensible()) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "cannot add a new property"); // TODO: better message. } return false; } // This is a new property with an index-like name. // Check whether we need to update array's ".length" property. bool updateLength = false; if (auto arrayHandle = Handle<JSArray>::dyn_vmcast(selfHandle)) { if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(*arrayHandle))) { NamedPropertyDescriptor lengthDesc; bool lengthPresent = getOwnNamedDescriptor( arrayHandle, runtime, Predefined::getSymbolID(Predefined::length), lengthDesc); (void)lengthPresent; assert(lengthPresent && ".length must be present in JSArray"); if (!lengthDesc.flags.writable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "Cannot assign to read-only 'length' property of array"); } return false; } updateLength = true; } } bool newIsIndexed = canNewPropertyBeIndexed(dpFlags); if (newIsIndexed) { auto result = setOwnIndexed( selfHandle, runtime, *arrayIndex, dpFlags.setValue ? valueOrAccessor : Runtime::getUndefinedValue()); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (!*result) { if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot define property"); } return false; } } // If this is an array and we need to update ".length", do so. if (updateLength) { // This should always succeed since we are simply enlarging the length. auto res = JSArray::setLength( Handle<JSArray>::vmcast(selfHandle), runtime, *arrayIndex + 1, opFlags); (void)res; assert( res != ExecutionStatus::EXCEPTION && *res && "JSArray::setLength() failed unexpectedly"); } if (newIsIndexed) return true; // We are adding a new property with an index-like name. LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); return addOwnProperty( selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags); } CallResult<bool> JSObject::defineOwnComputed( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; return defineOwnComputedPrimitive( selfHandle, runtime, *converted, dpFlags, valueOrAccessor, opFlags); } std::string JSObject::getHeuristicTypeName(GC *gc) { PointerBase *const base = gc->getPointerBase(); if (auto constructorVal = tryGetNamedNoAlloc( this, base, Predefined::getSymbolID(Predefined::constructor))) { if (auto *constructor = dyn_vmcast<JSObject>(*constructorVal)) { auto name = constructor->getNameIfExists(base); // If the constructor's name doesn't exist, or it is just the object // constructor, attempt to find a different name. if (!name.empty() && name != "Object") return name; } } std::string name = getVT()->base.snapshotMetaData.defaultNameForNode(this); // A constructor's name was not found, check if the object is in dictionary // mode. if (getClass(base)->isDictionary()) { return name + "(Dictionary)"; } // If it's not an Object, the CellKind is most likely good enough on its own if (getKind() != CellKind::ObjectKind) { return name; } // If the object isn't a dictionary, and it has only a few property names, // make the name based on those property names. std::vector<std::string> propertyNames; HiddenClass::forEachPropertyNoAlloc( getClass(base), base, [gc, &propertyNames](SymbolID id, NamedPropertyDescriptor) { if (InternalProperty::isInternal(id)) { // Internal properties aren't user-visible, skip them. return; } propertyNames.emplace_back(gc->convertSymbolToUTF8(id)); }); // NOTE: One option is to sort the property names before truncation, to // reduce the number of groups; however, by not sorting them it makes it // easier to spot sets of objects with the same properties but in different // orders, and thus find HiddenClass optimizations to make. // For objects with a lot of properties but aren't in dictionary mode yet, // keep the number displayed small. constexpr int kMaxPropertiesForTypeName = 5; bool truncated = false; if (propertyNames.size() > kMaxPropertiesForTypeName) { propertyNames.erase( propertyNames.begin() + kMaxPropertiesForTypeName, propertyNames.end()); truncated = true; } // The final name should look like Object(a, b, c). if (propertyNames.empty()) { // Don't add parentheses for objects with no properties. return name; } name += "("; bool first = true; for (const auto &prop : propertyNames) { if (!first) { name += ", "; } first = false; name += prop; } if (truncated) { // No need to check for comma edge case because this only happens for // greater than one property. static_assert( kMaxPropertiesForTypeName >= 1, "Property truncation should not happen for 0 properties"); name += ", ..."; } name += ")"; return name; } std::string JSObject::getNameIfExists(PointerBase *base) { // Try "displayName" first, if it is defined. if (auto nameVal = tryGetNamedNoAlloc( this, base, Predefined::getSymbolID(Predefined::displayName))) { if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) { return converter(name); } } // Next, use "name" if it is defined. if (auto nameVal = tryGetNamedNoAlloc( this, base, Predefined::getSymbolID(Predefined::name))) { if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) { return converter(name); } } // There is no other way to access the "name" property on an object. return ""; } std::string JSObject::_snapshotNameImpl(GCCell *cell, GC *gc) { auto *const self = vmcast<JSObject>(cell); return self->getHeuristicTypeName(gc); } void JSObject::_snapshotAddEdgesImpl(GCCell *cell, GC *gc, HeapSnapshot &snap) { auto *const self = vmcast<JSObject>(cell); // Add the prototype as a property edge, so it's easy for JS developers to // walk the prototype chain on their own. if (self->parent_) { snap.addNamedEdge( HeapSnapshot::EdgeType::Property, // __proto__ chosen for similarity to V8. "__proto__", gc->getObjectID(self->parent_)); } HiddenClass::forEachPropertyNoAlloc( self->clazz_.get(gc->getPointerBase()), gc->getPointerBase(), [self, gc, &snap](SymbolID id, NamedPropertyDescriptor desc) { if (InternalProperty::isInternal(id)) { // Internal properties aren't user-visible, skip them. return; } // Else, it's a user-visible property. GCHermesValue &prop = namedSlotRef(self, gc->getPointerBase(), desc.slot); const llvh::Optional<HeapSnapshot::NodeID> idForProp = gc->getSnapshotID(prop); if (!idForProp) { return; } std::string propName = gc->convertSymbolToUTF8(id); // If the property name is a valid array index, display it as an // "element" instead of a "property". This will put square brackets // around the number and sort it numerically rather than // alphabetically. if (auto index = ::hermes::toArrayIndex(propName)) { snap.addIndexedEdge( HeapSnapshot::EdgeType::Element, index.getValue(), idForProp.getValue()); } else { snap.addNamedEdge( HeapSnapshot::EdgeType::Property, propName, idForProp.getValue()); } }); } void JSObject::_snapshotAddLocationsImpl( GCCell *cell, GC *gc, HeapSnapshot &snap) { auto *const self = vmcast<JSObject>(cell); PointerBase *const base = gc->getPointerBase(); // Add the location of the constructor function for this object, if that // constructor is a user-defined JS function. if (auto constructorVal = tryGetNamedNoAlloc( self, base, Predefined::getSymbolID(Predefined::constructor))) { if (constructorVal->isObject()) { if (auto *constructor = dyn_vmcast<JSFunction>(*constructorVal)) { constructor->addLocationToSnapshot(snap, gc->getObjectID(self)); } } } } std::pair<uint32_t, uint32_t> JSObject::_getOwnIndexedRangeImpl( JSObject *self, Runtime *runtime) { return {0, 0}; } bool JSObject::_haveOwnIndexedImpl(JSObject *self, Runtime *, uint32_t) { return false; } OptValue<PropertyFlags> JSObject::_getOwnIndexedPropertyFlagsImpl( JSObject *self, Runtime *runtime, uint32_t) { return llvh::None; } HermesValue JSObject::_getOwnIndexedImpl(JSObject *, Runtime *, uint32_t) { return HermesValue::encodeEmptyValue(); } CallResult<bool> JSObject::_setOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t, Handle<>) { return false; } bool JSObject::_deleteOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t) { return false; } bool JSObject::_checkAllOwnIndexedImpl( JSObject * /*self*/, Runtime * /*runtime*/, ObjectVTable::CheckAllOwnIndexedMode /*mode*/) { return true; } void JSObject::preventExtensions(JSObject *self) { assert( !self->flags_.proxyObject && "[[Extensible]] slot cannot be set directly on Proxy objects"); self->flags_.noExtend = true; } CallResult<bool> JSObject::preventExtensions( Handle<JSObject> selfHandle, Runtime *runtime, PropOpFlags opFlags) { if (LLVM_UNLIKELY(selfHandle->isProxyObject())) { return JSProxy::preventExtensions(selfHandle, runtime, opFlags); } JSObject::preventExtensions(*selfHandle); return true; } ExecutionStatus JSObject::seal(Handle<JSObject> selfHandle, Runtime *runtime) { CallResult<bool> statusRes = JSObject::preventExtensions( selfHandle, runtime, PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } assert( *statusRes && "seal preventExtensions with ThrowOnError returned false"); // Already sealed? if (selfHandle->flags_.sealed) return ExecutionStatus::RETURNED; auto newClazz = HiddenClass::makeAllNonConfigurable( runtime->makeHandle(selfHandle->clazz_), runtime); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); selfHandle->flags_.sealed = true; return ExecutionStatus::RETURNED; } ExecutionStatus JSObject::freeze( Handle<JSObject> selfHandle, Runtime *runtime) { CallResult<bool> statusRes = JSObject::preventExtensions( selfHandle, runtime, PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } assert( *statusRes && "freeze preventExtensions with ThrowOnError returned false"); // Already frozen? if (selfHandle->flags_.frozen) return ExecutionStatus::RETURNED; auto newClazz = HiddenClass::makeAllReadOnly( runtime->makeHandle(selfHandle->clazz_), runtime); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); selfHandle->flags_.frozen = true; selfHandle->flags_.sealed = true; return ExecutionStatus::RETURNED; } void JSObject::updatePropertyFlagsWithoutTransitions( Handle<JSObject> selfHandle, Runtime *runtime, PropertyFlags flagsToClear, PropertyFlags flagsToSet, OptValue<llvh::ArrayRef<SymbolID>> props) { auto newClazz = HiddenClass::updatePropertyFlagsWithoutTransitions( runtime->makeHandle(selfHandle->clazz_), runtime, flagsToClear, flagsToSet, props); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); } CallResult<bool> JSObject::isExtensible( PseudoHandle<JSObject> self, Runtime *runtime) { if (LLVM_UNLIKELY(self->isProxyObject())) { return JSProxy::isExtensible(runtime->makeHandle(std::move(self)), runtime); } return self->isExtensible(); } bool JSObject::isSealed(PseudoHandle<JSObject> self, Runtime *runtime) { if (self->flags_.sealed) return true; if (!self->flags_.noExtend) return false; auto selfHandle = runtime->makeHandle(std::move(self)); if (!HiddenClass::areAllNonConfigurable( runtime->makeHandle(selfHandle->clazz_), runtime)) { return false; } if (!checkAllOwnIndexed( *selfHandle, runtime, ObjectVTable::CheckAllOwnIndexedMode::NonConfigurable)) { return false; } // Now that we know we are sealed, set the flag. selfHandle->flags_.sealed = true; return true; } bool JSObject::isFrozen(PseudoHandle<JSObject> self, Runtime *runtime) { if (self->flags_.frozen) return true; if (!self->flags_.noExtend) return false; auto selfHandle = runtime->makeHandle(std::move(self)); if (!HiddenClass::areAllReadOnly( runtime->makeHandle(selfHandle->clazz_), runtime)) { return false; } if (!checkAllOwnIndexed( *selfHandle, runtime, ObjectVTable::CheckAllOwnIndexedMode::ReadOnly)) { return false; } // Now that we know we are sealed, set the flag. selfHandle->flags_.frozen = true; selfHandle->flags_.sealed = true; return true; } CallResult<bool> JSObject::addOwnProperty( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { /// Can we add more properties? if (!selfHandle->isExtensible() && !opFlags.getInternalForce()) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Cannot add new property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "'"); } return false; } PropertyFlags flags{}; // Accessors don't set writeable. if (dpFlags.isAccessor()) { dpFlags.setWritable = 0; flags.accessor = 1; } // Override the default flags if specified. if (dpFlags.setEnumerable) flags.enumerable = dpFlags.enumerable; if (dpFlags.setWritable) flags.writable = dpFlags.writable; if (dpFlags.setConfigurable) flags.configurable = dpFlags.configurable; flags.internalSetter = dpFlags.enableInternalSetter; if (LLVM_UNLIKELY( addOwnPropertyImpl( selfHandle, runtime, name, flags, valueOrAccessor) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } ExecutionStatus JSObject::addOwnPropertyImpl( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropertyFlags propertyFlags, Handle<> valueOrAccessor) { assert( !selfHandle->flags_.proxyObject && "Internal properties cannot be added to Proxy objects"); // Add a new property to the class. // TODO: if we check for OOM here in the future, we must undo the slot // allocation. auto addResult = HiddenClass::addProperty( runtime->makeHandle(selfHandle->clazz_), runtime, name, propertyFlags); if (LLVM_UNLIKELY(addResult == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } selfHandle->clazz_.set(runtime, *addResult->first, &runtime->getHeap()); allocateNewSlotStorage( selfHandle, runtime, addResult->second, valueOrAccessor); // If this is an index-like property, we need to clear the fast path flags. if (LLVM_UNLIKELY( selfHandle->clazz_.getNonNull(runtime)->getHasIndexLikeProperties())) selfHandle->flags_.fastIndexProperties = false; return ExecutionStatus::RETURNED; } CallResult<bool> JSObject::updateOwnProperty( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, HiddenClass::PropertyPos propertyPos, NamedPropertyDescriptor desc, const DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { auto updateStatus = checkPropertyUpdate( runtime, desc.flags, dpFlags, getNamedSlotValue(selfHandle.get(), runtime, desc), valueOrAccessor, opFlags); if (updateStatus == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (updateStatus->first == PropertyUpdateStatus::failed) return false; // If the property flags changed, update them. if (updateStatus->second != desc.flags) { desc.flags = updateStatus->second; auto newClazz = HiddenClass::updateProperty( runtime->makeHandle(selfHandle->clazz_), runtime, propertyPos, desc.flags); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); } if (updateStatus->first == PropertyUpdateStatus::done) return true; assert( updateStatus->first == PropertyUpdateStatus::needSet && "unexpected PropertyUpdateStatus"); if (dpFlags.setValue) { if (LLVM_LIKELY(!desc.flags.internalSetter)) setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get()); else return internalSetter( selfHandle, runtime, name, desc, valueOrAccessor, opFlags); } else if (dpFlags.isAccessor()) { setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get()); } else { // If checkPropertyUpdate() returned needSet, but there is no value or // accessor, clear the value. setNamedSlotValue( selfHandle.get(), runtime, desc, HermesValue::encodeUndefinedValue()); } return true; } CallResult<std::pair<JSObject::PropertyUpdateStatus, PropertyFlags>> JSObject::checkPropertyUpdate( Runtime *runtime, const PropertyFlags currentFlags, DefinePropertyFlags dpFlags, const HermesValue curValueOrAccessor, Handle<> valueOrAccessor, PropOpFlags opFlags) { // 8.12.9 [5] Return true, if every field in Desc is absent. if (dpFlags.isEmpty()) return std::make_pair(PropertyUpdateStatus::done, currentFlags); assert( (!dpFlags.isAccessor() || (!dpFlags.setWritable && !dpFlags.writable)) && "can't set both accessor and writable"); assert( !dpFlags.enableInternalSetter && "cannot change the value of internalSetter"); // 8.12.9 [6] Return true, if every field in Desc also occurs in current and // the value of every field in Desc is the same value as the corresponding // field in current when compared using the SameValue algorithm (9.12). // TODO: this would probably be much more efficient with bitmasks. if ((!dpFlags.setEnumerable || dpFlags.enumerable == currentFlags.enumerable) && (!dpFlags.setConfigurable || dpFlags.configurable == currentFlags.configurable)) { if (dpFlags.isAccessor()) { if (currentFlags.accessor) { auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor); auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get()); if ((!dpFlags.setGetter || curAccessor->getter == newAccessor->getter) && (!dpFlags.setSetter || curAccessor->setter == newAccessor->setter)) { return std::make_pair(PropertyUpdateStatus::done, currentFlags); } } } else { if (!currentFlags.accessor && (!dpFlags.setValue || isSameValue(curValueOrAccessor, valueOrAccessor.get())) && (!dpFlags.setWritable || dpFlags.writable == currentFlags.writable)) { return std::make_pair(PropertyUpdateStatus::done, currentFlags); } } } // 8.12.9 [7] // If the property is not configurable, some aspects are not changeable. if (!currentFlags.configurable) { // Trying to change non-configurable to configurable? if (dpFlags.configurable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } // Trying to change the enumerability of non-configurable property? if (dpFlags.setEnumerable && dpFlags.enumerable != currentFlags.enumerable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } } PropertyFlags newFlags = currentFlags; // 8.12.9 [8] If IsGenericDescriptor(Desc) is true, then no further validation // is required. if (!(dpFlags.setValue || dpFlags.setWritable || dpFlags.setGetter || dpFlags.setSetter)) { // Do nothing } // 8.12.9 [9] // Changing between accessor and data descriptor? else if (currentFlags.accessor != dpFlags.isAccessor()) { if (!currentFlags.configurable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } // If we change from accessor to data descriptor, Preserve the existing // values of the converted property’s [[Configurable]] and [[Enumerable]] // attributes and set the rest of the property’s attributes to their default // values. // If it's the other way around, since the accessor doesn't have the // [[Writable]] attribute, do nothing. newFlags.writable = 0; // If we are changing from accessor to non-accessor, we must set a new // value. if (!dpFlags.isAccessor()) dpFlags.setValue = 1; } // 8.12.9 [10] if both are data descriptors. else if (!currentFlags.accessor) { if (!currentFlags.configurable) { if (!currentFlags.writable) { // If the current property is not writable, but the new one is. if (dpFlags.writable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } // If we are setting a different value. if (dpFlags.setValue && !isSameValue(curValueOrAccessor, valueOrAccessor.get())) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not writable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } } } } // 8.12.9 [11] Both are accessors. else { auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor); auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get()); // If not configurable, make sure that nothing is changing. if (!currentFlags.configurable) { if ((dpFlags.setGetter && newAccessor->getter != curAccessor->getter) || (dpFlags.setSetter && newAccessor->setter != curAccessor->setter)) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } } // If not setting the getter or the setter, re-use the current one. if (!dpFlags.setGetter) newAccessor->getter.set( runtime, curAccessor->getter, &runtime->getHeap()); if (!dpFlags.setSetter) newAccessor->setter.set( runtime, curAccessor->setter, &runtime->getHeap()); } // 8.12.9 [12] For each attribute field of Desc that is present, set the // correspondingly named attribute of the property named P of object O to the // value of the field. if (dpFlags.setEnumerable) newFlags.enumerable = dpFlags.enumerable; if (dpFlags.setWritable) newFlags.writable = dpFlags.writable; if (dpFlags.setConfigurable) newFlags.configurable = dpFlags.configurable; if (dpFlags.setValue) newFlags.accessor = false; else if (dpFlags.isAccessor()) newFlags.accessor = true; else return std::make_pair(PropertyUpdateStatus::done, newFlags); return std::make_pair(PropertyUpdateStatus::needSet, newFlags); } CallResult<bool> JSObject::internalSetter( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, NamedPropertyDescriptor /*desc*/, Handle<> value, PropOpFlags opFlags) { if (vmisa<JSArray>(selfHandle.get())) { if (name == Predefined::getSymbolID(Predefined::length)) { return JSArray::setLength( Handle<JSArray>::vmcast(selfHandle), runtime, value, opFlags); } } llvm_unreachable("unhandled property in Object::internalSetter()"); } namespace { /// Helper function to add all the property names of an object to an /// array, starting at the given index. Only enumerable properties are /// incluced. Returns the index after the last property added, but... CallResult<uint32_t> appendAllPropertyNames( Handle<JSObject> obj, Runtime *runtime, MutableHandle<BigStorage> &arr, uint32_t beginIndex) { uint32_t size = beginIndex; // We know that duplicate property names can only exist between objects in // the prototype chain. Hence there should not be duplicated properties // before we start to look at any prototype. bool needDedup = false; MutableHandle<> prop(runtime); MutableHandle<JSObject> head(runtime, obj.get()); MutableHandle<StringPrimitive> tmpVal{runtime}; while (head.get()) { GCScope gcScope(runtime); // enumerableProps will contain all enumerable own properties from obj. // Impl note: this is the only place where getOwnPropertyKeys will be // called without IncludeNonEnumerable on a Proxy. Everywhere else, // trap ordering is specified but ES9 13.7.5.15 says "The mechanics and // order of enumerating the properties is not specified", which is // unusual. auto cr = JSObject::getOwnPropertyNames(head, runtime, true /* onlyEnumerable */); if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto enumerableProps = *cr; auto marker = gcScope.createMarker(); for (unsigned i = 0, e = enumerableProps->getEndIndex(); i < e; ++i) { gcScope.flushToMarker(marker); prop = enumerableProps->at(runtime, i); if (!needDedup) { // If no dedup is needed, add it directly. if (LLVM_UNLIKELY( BigStorage::push_back(arr, runtime, prop) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } ++size; continue; } // Otherwise loop through all existing properties and check if we // have seen it before. bool dupFound = false; if (prop->isNumber()) { for (uint32_t j = beginIndex; j < size && !dupFound; ++j) { HermesValue val = arr->at(j); if (val.isNumber()) { dupFound = val.getNumber() == prop->getNumber(); } else { // val is string, prop is number. tmpVal = val.getString(); auto valNum = toArrayIndex( StringPrimitive::createStringView(runtime, tmpVal)); dupFound = valNum && valNum.getValue() == prop->getNumber(); } } } else { for (uint32_t j = beginIndex; j < size && !dupFound; ++j) { HermesValue val = arr->at(j); if (val.isNumber()) { // val is number, prop is string. auto propNum = toArrayIndex(StringPrimitive::createStringView( runtime, Handle<StringPrimitive>::vmcast(prop))); dupFound = propNum && (propNum.getValue() == val.getNumber()); } else { dupFound = val.getString()->equals(prop->getString()); } } } if (LLVM_LIKELY(!dupFound)) { if (LLVM_UNLIKELY( BigStorage::push_back(arr, runtime, prop) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } ++size; } } // Continue to follow the prototype chain. CallResult<PseudoHandle<JSObject>> parentRes = JSObject::getPrototypeOf(head, runtime); if (LLVM_UNLIKELY(parentRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } head = parentRes->get(); needDedup = true; } return size; } /// Adds the hidden classes of the prototype chain of obj to arr, /// starting with the prototype of obj at index 0, etc., and /// terminates with null. /// /// \param obj The object whose prototype chain should be output /// \param[out] arr The array where the classes will be appended. This /// array is cleared if any object is unsuitable for caching. ExecutionStatus setProtoClasses( Runtime *runtime, Handle<JSObject> obj, MutableHandle<BigStorage> &arr) { // Layout of a JSArray stored in the for-in cache: // [class(proto(obj)), class(proto(proto(obj))), ..., null, prop0, prop1, ...] if (!obj->shouldCacheForIn(runtime)) { arr->clear(runtime); return ExecutionStatus::RETURNED; } MutableHandle<JSObject> head(runtime, obj->getParent(runtime)); MutableHandle<> clazz(runtime); GCScopeMarkerRAII marker{runtime}; while (head.get()) { if (!head->shouldCacheForIn(runtime)) { arr->clear(runtime); return ExecutionStatus::RETURNED; } if (JSObject::Helper::flags(*head).lazyObject) { // Ensure all properties have been initialized before caching the hidden // class. Not doing this will result in changes to the hidden class // when getOwnPropertyKeys is called later. JSObject::initializeLazyObject(runtime, head); } clazz = HermesValue::encodeObjectValue(head->getClass(runtime)); if (LLVM_UNLIKELY( BigStorage::push_back(arr, runtime, clazz) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } head = head->getParent(runtime); marker.flush(); } clazz = HermesValue::encodeNullValue(); return BigStorage::push_back(arr, runtime, clazz); } /// Verifies that the classes of obj's prototype chain still matches those /// previously prefixed to arr by setProtoClasses. /// /// \param obj The object whose prototype chain should be verified /// \param arr Array previously populated by setProtoClasses /// \return The index after the terminating null if everything matches, /// otherwise 0. uint32_t matchesProtoClasses( Runtime *runtime, Handle<JSObject> obj, Handle<BigStorage> arr) { MutableHandle<JSObject> head(runtime, obj->getParent(runtime)); uint32_t i = 0; while (head.get()) { HermesValue protoCls = arr->at(i++); if (protoCls.isNull() || protoCls.getObject() != head->getClass(runtime) || head->isProxyObject()) { return 0; } head = head->getParent(runtime); } // The chains must both end at the same point. if (head || !arr->at(i++).isNull()) { return 0; } assert(i > 0 && "success should be positive"); return i; } } // namespace CallResult<Handle<BigStorage>> getForInPropertyNames( Runtime *runtime, Handle<JSObject> obj, uint32_t &beginIndex, uint32_t &endIndex) { Handle<HiddenClass> clazz(runtime, obj->getClass(runtime)); // Fast case: Check the cache. MutableHandle<BigStorage> arr(runtime, clazz->getForInCache(runtime)); if (arr) { beginIndex = matchesProtoClasses(runtime, obj, arr); if (beginIndex) { // Cache is valid for this object, so use it. endIndex = arr->size(); return arr; } // Invalid for this object. We choose to clear the cache since the // changes to the prototype chain probably affect other objects too. clazz->clearForInCache(runtime); // Clear arr to slightly reduce risk of OOM from allocation below. arr = nullptr; } // Slow case: Build the array of properties. auto ownPropEstimate = clazz->getNumProperties(); auto arrRes = obj->shouldCacheForIn(runtime) ? BigStorage::createLongLived(runtime, ownPropEstimate) : BigStorage::create(runtime, ownPropEstimate); if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } arr = std::move(*arrRes); if (setProtoClasses(runtime, obj, arr) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } beginIndex = arr->size(); // If obj or any of its prototypes are unsuitable for caching, then // beginIndex is 0 and we return an array with only the property names. bool canCache = beginIndex; auto end = appendAllPropertyNames(obj, runtime, arr, beginIndex); if (end == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } endIndex = *end; // Avoid degenerate memory explosion: if > 75% of the array is properties // or classes from prototypes, then don't cache it. const bool tooMuchProto = *end / 4 > ownPropEstimate; if (canCache && !tooMuchProto) { assert(beginIndex > 0 && "cached array must start with proto classes"); #ifdef HERMES_SLOW_DEBUG assert(beginIndex == matchesProtoClasses(runtime, obj, arr) && "matches"); #endif clazz->setForInCache(*arr, runtime); } return arr; } //===----------------------------------------------------------------------===// // class PropertyAccessor VTable PropertyAccessor::vt{CellKind::PropertyAccessorKind, cellSize<PropertyAccessor>()}; void PropertyAccessorBuildMeta(const GCCell *cell, Metadata::Builder &mb) { const auto *self = static_cast<const PropertyAccessor *>(cell); mb.addField("getter", &self->getter); mb.addField("setter", &self->setter); } #ifdef HERMESVM_SERIALIZE PropertyAccessor::PropertyAccessor(Deserializer &d) : GCCell(&d.getRuntime()->getHeap(), &vt) { d.readRelocation(&getter, RelocationKind::GCPointer); d.readRelocation(&setter, RelocationKind::GCPointer); } void PropertyAccessorSerialize(Serializer &s, const GCCell *cell) { auto *self = vmcast<const PropertyAccessor>(cell); s.writeRelocation(self->getter.get(s.getRuntime())); s.writeRelocation(self->setter.get(s.getRuntime())); s.endObject(cell); } void PropertyAccessorDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::PropertyAccessorKind && "Expected PropertyAccessor"); void *mem = d.getRuntime()->alloc(cellSize<PropertyAccessor>()); auto *cell = new (mem) PropertyAccessor(d); d.endObject(cell); } #endif CallResult<HermesValue> PropertyAccessor::create( Runtime *runtime, Handle<Callable> getter, Handle<Callable> setter) { void *mem = runtime->alloc(cellSize<PropertyAccessor>()); return HermesValue::encodeObjectValue( new (mem) PropertyAccessor(runtime, *getter, *setter)); } } // namespace vm } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_4259_0
crossvul-cpp_data_good_1183_0
// This file is part of The New Aspell // Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. //#include <stdio.h> //#define DEBUG {fprintf(stderr,"File: %s(%i)\n",__FILE__,__LINE__);} #include <string.h> #include <stdlib.h> #include "ndebug.hpp" #include <assert.h> #include "dirs.h" #include "settings.h" #ifdef USE_LOCALE # include <locale.h> #endif #ifdef HAVE_LANGINFO_CODESET # include <langinfo.h> #endif #include "cache.hpp" #include "asc_ctype.hpp" #include "config.hpp" #include "errors.hpp" #include "file_util.hpp" #include "fstream.hpp" #include "getdata.hpp" #include "itemize.hpp" #include "mutable_container.hpp" #include "posib_err.hpp" #include "string_map.hpp" #include "stack_ptr.hpp" #include "char_vector.hpp" #include "convert.hpp" #include "vararray.hpp" #include "string_list.hpp" #include "gettext.h" #include "iostream.hpp" #define DEFAULT_LANG "en_US" // NOTE: All filter options are now stored with he "f-" prefix. However // during lookup, the non prefix version is also recognized. // The "place_holder" field in Entry and the "Vector<int>" parameter of // commit_all are there to deal with the fact than when spacing // options on the command line such as "--key what" it can not be // determined if "what" should be a the value of "key" or if it should // be treated as an independent arg. This is because "key" may // be a filter option. Filter options KeyInfo are not loaded until // after a commit which is not done at the time the options are being // read in from the command line. (If the command line arguments are // read in after the other settings are read in and committed than any // options setting any of the config files will be ignored. Thus the // command line must be parsed and options must be added in an // uncommitted state). So the solution is to assume it is an // independent arg until told otherwise, the position in the arg array // is stored along with the value in the "place_holder" field. When // the config class is finally committed and it is determined that // "what" is really a value for key the stored arg position is pushed // onto the Vector<int> so it can be removed from the arg array. In // the case of a "lset-*" this will happen in multiple config // "Entry"s, so care is taken to only add the arg position once. namespace acommon { const char * const keyinfo_type_name[4] = { N_("string"), N_("integer"), N_("boolean"), N_("list") }; const int Config::num_parms_[9] = {1, 1, 0, 0, 0, 1, 1, 1, 0}; typedef Notifier * NotifierPtr; Config::Config(ParmStr name, const KeyInfo * mainbegin, const KeyInfo * mainend) : name_(name) , first_(0), insert_point_(&first_), others_(0) , committed_(true), attached_(false) , md_info_list_index(-1) , settings_read_in_(false) , load_filter_hook(0) , filter_mode_notifier(0) { keyinfo_begin = mainbegin; keyinfo_end = mainend; extra_begin = 0; extra_end = 0; } Config::~Config() { del(); } Config::Config(const Config & other) { copy(other); } Config & Config::operator= (const Config & other) { del(); copy(other); return *this; } Config * Config::clone() const { return new Config(*this); } void Config::assign(const Config * other) { *this = *(const Config *)(other); } void Config::copy(const Config & other) { assert(other.others_ == 0); others_ = 0; name_ = other.name_; committed_ = other.committed_; attached_ = other.attached_; settings_read_in_ = other.settings_read_in_; keyinfo_begin = other.keyinfo_begin; keyinfo_end = other.keyinfo_end; extra_begin = other.extra_begin; extra_end = other.extra_end; filter_modules = other.filter_modules; #ifdef HAVE_LIBDL filter_modules_ptrs = other.filter_modules_ptrs; for (Vector<Cacheable *>::iterator i = filter_modules_ptrs.begin(); i != filter_modules_ptrs.end(); ++i) (*i)->copy(); #endif md_info_list_index = other.md_info_list_index; insert_point_ = 0; Entry * const * src = &other.first_; Entry * * dest = &first_; while (*src) { *dest = new Entry(**src); if (src == other.insert_point_) insert_point_ = dest; src = &((*src)->next); dest = &((*dest)->next); } if (insert_point_ == 0) insert_point_ = dest; *dest = 0; Vector<Notifier *>::const_iterator i = other.notifier_list.begin(); Vector<Notifier *>::const_iterator end = other.notifier_list.end(); for(; i != end; ++i) { Notifier * tmp = (*i)->clone(this); if (tmp != 0) notifier_list.push_back(tmp); } } void Config::del() { while (first_) { Entry * tmp = first_->next; delete first_; first_ = tmp; } while (others_) { Entry * tmp = others_->next; delete first_; others_ = tmp; } Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); for(; i != end; ++i) { delete (*i); *i = 0; } notifier_list.clear(); #ifdef HAVE_LIBDL filter_modules.clear(); for (Vector<Cacheable *>::iterator i = filter_modules_ptrs.begin(); i != filter_modules_ptrs.end(); ++i) (*i)->release(); filter_modules_ptrs.clear(); #endif } void Config::set_filter_modules(const ConfigModule * modbegin, const ConfigModule * modend) { assert(filter_modules_ptrs.empty()); filter_modules.clear(); filter_modules.assign(modbegin, modend); } void Config::set_extra(const KeyInfo * begin, const KeyInfo * end) { extra_begin = begin; extra_end = end; } // // // // // Notifier methods // NotifierEnumeration * Config::notifiers() const { return new NotifierEnumeration(notifier_list); } bool Config::add_notifier(Notifier * n) { Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); while (i != end && *i != n) ++i; if (i != end) { return false; } else { notifier_list.push_back(n); return true; } } bool Config::remove_notifier(const Notifier * n) { Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); while (i != end && *i != n) ++i; if (i == end) { return false; } else { delete *i; notifier_list.erase(i); return true; } } bool Config::replace_notifier(const Notifier * o, Notifier * n) { Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); while (i != end && *i != o) ++i; if (i == end) { return false; } else { delete *i; *i = n; return true; } } // // retrieve methods // const Config::Entry * Config::lookup(const char * key) const { const Entry * res = 0; const Entry * cur = first_; while (cur) { if (cur->key == key && cur->action != NoOp) res = cur; cur = cur->next; } if (!res || res->action == Reset) return 0; return res; } bool Config::have(ParmStr key) const { PosibErr<const KeyInfo *> pe = keyinfo(key); if (pe.has_err()) {pe.ignore_err(); return false;} return lookup(pe.data->name); } PosibErr<String> Config::retrieve(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type == KeyInfoList) return make_err(key_not_string, ki->name); const Entry * cur = lookup(ki->name); return cur ? cur->value : get_default(ki); } PosibErr<String> Config::retrieve_any(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoList) { const Entry * cur = lookup(ki->name); return cur ? cur->value : get_default(ki); } else { StringList sl; RET_ON_ERR(retrieve_list(key, &sl)); StringListEnumeration els = sl.elements_obj(); const char * s; String val; while ( (s = els.next()) != 0 ) { val += s; val += '\n'; } val.pop_back(); return val; } } PosibErr<bool> Config::retrieve_bool(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoBool) return make_err(key_not_bool, ki->name); const Entry * cur = lookup(ki->name); String value(cur ? cur->value : get_default(ki)); if (value == "false") return false; else return true; } PosibErr<int> Config::retrieve_int(ParmStr key) const { assert(committed_); // otherwise the value may not be an integer // as it has not been verified. RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoInt) return make_err(key_not_int, ki->name); const Entry * cur = lookup(ki->name); String value(cur ? cur->value : get_default(ki)); return atoi(value.str()); } void Config::lookup_list(const KeyInfo * ki, MutableContainer & m, bool include_default) const { const Entry * cur = first_; const Entry * first_to_use = 0; while (cur) { if (cur->key == ki->name && (first_to_use == 0 || cur->action == Reset || cur->action == Set || cur->action == ListClear)) first_to_use = cur; cur = cur->next; } cur = first_to_use; if (include_default && (!cur || !(cur->action == Set || cur->action == ListClear))) { String def = get_default(ki); separate_list(def, m, true); } if (cur && cur->action == Reset) { cur = cur->next; } if (cur && cur->action == Set) { if (!include_default) m.clear(); m.add(cur->value); cur = cur->next; } if (cur && cur->action == ListClear) { if (!include_default) m.clear(); cur = cur->next; } while (cur) { if (cur->key == ki->name) { if (cur->action == ListAdd) m.add(cur->value); else if (cur->action == ListRemove) m.remove(cur->value); } cur = cur->next; } } PosibErr<void> Config::retrieve_list(ParmStr key, MutableContainer * m) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoList) return make_err(key_not_list, ki->name); lookup_list(ki, *m, true); return no_err; } static const KeyInfo * find(ParmStr key, const KeyInfo * i, const KeyInfo * end) { while (i != end) { if (strcmp(key, i->name) == 0) return i; ++i; } return i; } static const ConfigModule * find(ParmStr key, const ConfigModule * i, const ConfigModule * end) { while (i != end) { if (strcmp(key, i->name) == 0) return i; ++i; } return i; } PosibErr<const KeyInfo *> Config::keyinfo(ParmStr key) const { typedef PosibErr<const KeyInfo *> Ret; { const KeyInfo * i; i = acommon::find(key, keyinfo_begin, keyinfo_end); if (i != keyinfo_end) return Ret(i); i = acommon::find(key, extra_begin, extra_end); if (i != extra_end) return Ret(i); const char * s = strncmp(key, "f-", 2) == 0 ? key + 2 : key.str(); const char * h = strchr(s, '-'); if (h == 0) goto err; String k(s, h - s); const ConfigModule * j = acommon::find(k, filter_modules.pbegin(), filter_modules.pend()); if (j == filter_modules.pend() && load_filter_hook && committed_) { // FIXME: This isn't quite right PosibErrBase pe = load_filter_hook(const_cast<Config *>(this), k); pe.ignore_err(); j = acommon::find(k, filter_modules.pbegin(), filter_modules.pend()); } if (j == filter_modules.pend()) goto err; i = acommon::find(key, j->begin, j->end); if (i != j->end) return Ret(i); if (strncmp(key, "f-", 2) != 0) k = "f-"; else k = ""; k += key; i = acommon::find(k, j->begin, j->end); if (i != j->end) return Ret(i); } err: return Ret().prim_err(unknown_key, key); } static bool proc_locale_str(ParmStr lang, String & final_str) { if (lang == 0) return false; const char * i = lang; if (!(asc_islower(i[0]) && asc_islower(i[1]))) return false; final_str.assign(i, 2); i += 2; if (! (i[0] == '_' || i[0] == '-')) return true; i += 1; if (!(asc_isupper(i[0]) && asc_isupper(i[1]))) return true; final_str += '_'; final_str.append(i, 2); return true; } static void get_lang_env(String & str) { if (proc_locale_str(getenv("LC_MESSAGES"), str)) return; if (proc_locale_str(getenv("LANG"), str)) return; if (proc_locale_str(getenv("LANGUAGE"), str)) return; str = DEFAULT_LANG; } #ifdef USE_LOCALE static void get_lang(String & final_str) { // FIXME: THIS IS NOT THREAD SAFE String locale = setlocale (LC_ALL, NULL); if (locale == "C") setlocale (LC_ALL, ""); const char * lang = setlocale (LC_MESSAGES, NULL); bool res = proc_locale_str(lang, final_str); if (locale == "C") setlocale(LC_MESSAGES, locale.c_str()); if (!res) get_lang_env(final_str); } #else static inline void get_lang(String & str) { get_lang_env(str); } #endif #if defined USE_LOCALE && defined HAVE_LANGINFO_CODESET static inline void get_encoding(const Config & c, String & final_str) { const char * codeset = nl_langinfo(CODESET); if (ascii_encoding(c, codeset)) codeset = "none"; final_str = codeset; } #else static inline void get_encoding(const Config &, String & final_str) { final_str = "none"; } #endif String Config::get_default(const KeyInfo * ki) const { bool in_replace = false; String final_str; String replace; const char * i = ki->def; if (*i == '!') { // special cases ++i; if (strcmp(i, "lang") == 0) { const Entry * entry; if (entry = lookup("actual-lang"), entry) { return entry->value; } else if (have("master")) { final_str = "<unknown>"; } else { get_lang(final_str); } } else if (strcmp(i, "encoding") == 0) { get_encoding(*this, final_str); } else if (strcmp(i, "special") == 0) { // do nothing } else { abort(); // this should not happen } } else for(; *i; ++i) { if (!in_replace) { if (*i == '<') { in_replace = true; } else { final_str += *i; } } else { // in_replace if (*i == '/' || *i == ':' || *i == '|' || *i == '#' || *i == '^') { char sep = *i; String second; ++i; while (*i != '\0' && *i != '>') second += *i++; if (sep == '/') { String s1 = retrieve(replace); String s2 = retrieve(second); final_str += add_possible_dir(s1, s2); } else if (sep == ':') { String s1 = retrieve(replace); final_str += add_possible_dir(s1, second); } else if (sep == '#') { String s1 = retrieve(replace); assert(second.size() == 1); unsigned int s = 0; while (s != s1.size() && s1[s] != second[0]) ++s; final_str.append(s1, s); } else if (sep == '^') { String s1 = retrieve(replace); String s2 = retrieve(second); final_str += figure_out_dir(s1, s2); } else { // sep == '|' assert(replace[0] == '$'); const char * env = getenv(replace.c_str()+1); final_str += env ? env : second; } replace = ""; in_replace = false; } else if (*i == '>') { final_str += retrieve(replace).data; replace = ""; in_replace = false; } else { replace += *i; } } } return final_str; } PosibErr<String> Config::get_default(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); return get_default(ki); } #define TEST(v,l,a) \ do { \ if (len == l && memcmp(s, v, l) == 0) { \ if (action) *action = a; \ return c + 1; \ } \ } while (false) const char * Config::base_name(const char * s, Action * action) { if (action) *action = Set; const char * c = strchr(s, '-'); if (!c) return s; unsigned len = c - s; TEST("reset", 5, Reset); TEST("enable", 6, Enable); TEST("dont", 4, Disable); TEST("disable", 7, Disable); TEST("lset", 4, ListSet); TEST("rem", 3, ListRemove); TEST("remove", 6, ListRemove); TEST("add", 3, ListAdd); TEST("clear", 5, ListClear); return s; } #undef TEST void separate_list(ParmStr value, AddableContainer & out, bool do_unescape) { unsigned len = value.size(); VARARRAY(char, buf, len + 1); memcpy(buf, value, len + 1); len = strlen(buf); char * s = buf; char * end = buf + len; while (s < end) { if (do_unescape) while (*s == ' ' || *s == '\t') ++s; char * b = s; char * e = s; while (*s != '\0') { if (do_unescape && *s == '\\') { ++s; if (*s == '\0') break; e = s; ++s; } else { if (*s == ':') break; if (!do_unescape || (*s != ' ' && *s != '\t')) e = s; ++s; } } if (s != b) { ++e; *e = '\0'; if (do_unescape) unescape(b); out.add(b); } ++s; } } void combine_list(String & res, const StringList & in) { res.clear(); StringListEnumeration els = in.elements_obj(); const char * s = 0; while ( (s = els.next()) != 0) { for (; *s; ++s) { if (*s == ':') res.append('\\'); res.append(*s); } res.append(':'); } if (!res.empty() && res.back() == ':') res.pop_back(); } struct ListAddHelper : public AddableContainer { Config * config; Config::Entry * orig_entry; PosibErr<bool> add(ParmStr val); }; PosibErr<bool> ListAddHelper::add(ParmStr val) { Config::Entry * entry = new Config::Entry(*orig_entry); entry->value = val; entry->action = Config::ListAdd; config->set(entry); return true; } void Config::replace_internal(ParmStr key, ParmStr value) { Entry * entry = new Entry; entry->key = key; entry->value = value; entry->action = Set; entry->next = *insert_point_; *insert_point_ = entry; insert_point_ = &entry->next; } PosibErr<void> Config::replace(ParmStr key, ParmStr value) { Entry * entry = new Entry; entry->key = key; entry->value = value; return set(entry); } PosibErr<void> Config::remove(ParmStr key) { Entry * entry = new Entry; entry->key = key; entry->action = Reset; return set(entry); } PosibErr<void> Config::set(Entry * entry0, bool do_unescape) { StackPtr<Entry> entry(entry0); if (entry->action == NoOp) entry->key = base_name(entry->key.str(), &entry->action); if (num_parms(entry->action) == 0 && !entry->value.empty()) { if (entry->place_holder == -1) { switch (entry->action) { case Reset: return make_err(no_value_reset, entry->key); case Enable: return make_err(no_value_enable, entry->key); case Disable: return make_err(no_value_disable, entry->key); case ListClear: return make_err(no_value_clear, entry->key); default: abort(); // this shouldn't happen } } else { entry->place_holder = -1; } } if (entry->action != ListSet) { switch (entry->action) { case Enable: entry->value = "true"; entry->action = Set; break; case Disable: entry->value = "false"; entry->action = Set; break; default: ; } if (do_unescape) unescape(entry->value.mstr()); entry->next = *insert_point_; *insert_point_ = entry; insert_point_ = &entry->next; entry.release(); if (committed_) RET_ON_ERR(commit(entry0)); // entry0 == entry } else { // action == ListSet Entry * ent = new Entry; ent->key = entry->key; ent->action = ListClear; set(ent); ListAddHelper helper; helper.config = this; helper.orig_entry = entry; separate_list(entry->value.str(), helper, do_unescape); } return no_err; } PosibErr<void> Config::merge(const Config & other) { const Entry * src = other.first_; while (src) { Entry * entry = new Entry(*src); entry->next = *insert_point_; *insert_point_ = entry; insert_point_ = &entry->next; if (committed_) RET_ON_ERR(commit(entry)); src = src->next; } return no_err; } void Config::lang_config_merge(const Config & other, int which, ParmStr data_encoding) { Conv to_utf8; to_utf8.setup(*this, data_encoding, "utf-8", NormTo); const Entry * src = other.first_; Entry * * ip = &first_; while (src) { const KeyInfo * l_ki = other.keyinfo(src->key); if (l_ki->other_data == which) { const KeyInfo * c_ki = keyinfo(src->key); Entry * entry = new Entry(*src); if (c_ki->flags & KEYINFO_UTF8) entry->value = to_utf8(entry->value); entry->next = *ip; *ip = entry; ip = &entry->next; } src = src->next; } } #define NOTIFY_ALL(fun) \ do { \ Vector<Notifier *>::iterator i = notifier_list.begin(); \ Vector<Notifier *>::iterator end = notifier_list.end(); \ while (i != end) { \ RET_ON_ERR((*i)->fun); \ ++i; \ } \ } while (false) PosibErr<int> Config::commit(Entry * entry, Conv * conv) { PosibErr<const KeyInfo *> pe = keyinfo(entry->key); { if (pe.has_err()) goto error; const KeyInfo * ki = pe; entry->key = ki->name; // FIXME: This is the correct thing to do but it causes problems // with changing a filter mode in "pipe" mode and probably // elsewhere. //if (attached_ && !(ki->flags & KEYINFO_MAY_CHANGE)) { // pe = make_err(cant_change_value, entry->key); // goto error; //} int place_holder = entry->place_holder; if (conv && ki->flags & KEYINFO_UTF8) entry->value = (*conv)(entry->value); if (ki->type != KeyInfoList && list_action(entry->action)) { pe = make_err(key_not_list, entry->key); goto error; } assert(ki->def != 0); // if null this key should never have values // directly added to it String value(entry->action == Reset ? get_default(ki) : entry->value); switch (ki->type) { case KeyInfoBool: { bool val; if (value.empty() || entry->place_holder != -1) { // if entry->place_holder != -1 than IGNORE the value no // matter what it is entry->value = "true"; val = true; place_holder = -1; } else if (value == "true") { val = true; } else if (value == "false") { val = false; } else { pe = make_err(bad_value, entry->key, value, /* TRANSLATORS: "true" and "false" are literal * values and should not be translated.*/ _("either \"true\" or \"false\"")); goto error; } NOTIFY_ALL(item_updated(ki, val)); break; } case KeyInfoString: NOTIFY_ALL(item_updated(ki, value)); break; case KeyInfoInt: { int num; if (sscanf(value.str(), "%i", &num) == 1 && num >= 0) { NOTIFY_ALL(item_updated(ki, num)); } else { pe = make_err(bad_value, entry->key, value, _("a positive integer")); goto error; } break; } case KeyInfoList: NOTIFY_ALL(list_updated(ki)); break; } return place_holder; } error: entry->action = NoOp; if (!entry->file.empty()) return pe.with_file(entry->file, entry->line_num); else return (PosibErrBase &)pe; } #undef NOTIFY_ALL ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// class PossibleElementsEmul : public KeyInfoEnumeration { private: bool include_extra; bool include_modules; bool module_changed; const Config * cd; const KeyInfo * i; const ConfigModule * m; public: PossibleElementsEmul(const Config * d, bool ic, bool im) : include_extra(ic), include_modules(im), module_changed(false), cd(d), i(d->keyinfo_begin), m(0) {} KeyInfoEnumeration * clone() const { return new PossibleElementsEmul(*this); } void assign(const KeyInfoEnumeration * other) { *this = *(const PossibleElementsEmul *)(other); } virtual bool active_filter_module_changed(void) { return module_changed; } const char * active_filter_module_name(void){ if (m != 0) return m->name; return ""; } virtual const char * active_filter_module_desc(void) { if (m != 0) return m->desc; return ""; } const KeyInfo * next() { if (i == cd->keyinfo_end) { if (include_extra) i = cd->extra_begin; else i = cd->extra_end; } module_changed = false; if (i == cd->extra_end) { m = cd->filter_modules.pbegin(); if (!include_modules || m == cd->filter_modules.pend()) return 0; else { i = m->begin; module_changed = true; } } if (m == 0){ return i++; } if (m == cd->filter_modules.pend()){ return 0; } while (i == m->end) { ++m; if (m == cd->filter_modules.pend()) return 0; else { i = m->begin; module_changed = true; } } return i++; } bool at_end() const { return (m == cd->filter_modules.pend()); } }; KeyInfoEnumeration * Config::possible_elements(bool include_extra, bool include_modules) const { return new PossibleElementsEmul(this, include_extra, include_modules); } struct ListDefaultDump : public AddableContainer { OStream & out; bool first; const char * first_prefix; unsigned num_blanks; ListDefaultDump(OStream & o); PosibErr<bool> add(ParmStr d); }; ListDefaultDump::ListDefaultDump(OStream & o) : out(o), first(false) { first_prefix = _("# default: "); num_blanks = strlen(first_prefix) - 1; } PosibErr<bool> ListDefaultDump::add(ParmStr d) { if (first) { out.write(first_prefix); } else { out.put('#'); for (unsigned i = 0; i != num_blanks; ++i) out.put(' '); } VARARRAY(char, buf, d.size() * 2 + 1); escape(buf, d); out.printl(buf); first = false; return true; } class ListDump : public MutableContainer { OStream & out; const char * name; public: ListDump(OStream & o, ParmStr n) : out(o), name(n) {} PosibErr<bool> add(ParmStr d); PosibErr<bool> remove(ParmStr d); PosibErr<void> clear(); }; PosibErr<bool> ListDump::add(ParmStr d) { VARARRAY(char, buf, d.size() * 2 + 1); escape(buf, d); out.printf("add-%s %s\n", name, buf); return true; } PosibErr<bool> ListDump::remove(ParmStr d) { VARARRAY(char, buf, d.size() * 2 + 1); escape(buf, d); out.printf("remove-%s %s\n", name, buf); return true; } PosibErr<void> ListDump::clear() { out.printf("clear-%s\n", name); return no_err; } void Config::write_to_stream(OStream & out, bool include_extra) { KeyInfoEnumeration * els = possible_elements(include_extra); const KeyInfo * i; String buf; String obuf; String def; bool have_value; while ((i = els->next()) != 0) { if (i->desc == 0) continue; if (els->active_filter_module_changed()) { out.printf(_("\n" "#######################################################################\n" "#\n" "# Filter: %s\n" "# %s\n" "#\n" "# configured as follows:\n" "\n"), els->active_filter_module_name(), _(els->active_filter_module_desc())); } obuf.clear(); have_value = false; obuf.printf("# %s (%s)\n# %s\n", i->name, _(keyinfo_type_name[i->type]), _(i->desc)); if (i->def != 0) { if (i->type != KeyInfoList) { buf.resize(strlen(i->def) * 2 + 1); escape(buf.data(), i->def); obuf.printf("# default: %s", buf.data()); def = get_default(i); if (def != i->def) { buf.resize(def.size() * 2 + 1); escape(buf.data(), def.str()); obuf.printf(" = %s", buf.data()); } obuf << '\n'; const Entry * entry = lookup(i->name); if (entry) { have_value = true; buf.resize(entry->value.size() * 2 + 1); escape(buf.data(), entry->value.str()); obuf.printf("%s %s\n", i->name, buf.data()); } } else { unsigned s = obuf.size(); ListDump ld(obuf, i->name); lookup_list(i, ld, false); have_value = s != obuf.size(); } } obuf << '\n'; if (!(i->flags & KEYINFO_HIDDEN) || have_value) out.write(obuf); } delete els; } PosibErr<void> Config::read_in(IStream & in, ParmStr id) { String buf; DataPair dp; while (getdata_pair(in, dp, buf)) { to_lower(dp.key); Entry * entry = new Entry; entry->key = dp.key; entry->value = dp.value; entry->file = id; entry->line_num = dp.line_num; RET_ON_ERR(set(entry, true)); } return no_err; } PosibErr<void> Config::read_in_file(ParmStr file) { FStream in; RET_ON_ERR(in.open(file, "r")); return read_in(in, file); } PosibErr<void> Config::read_in_string(ParmStr str, const char * what) { StringIStream in(str); return read_in(in, what); } PosibErr<bool> Config::read_in_settings(const Config * other) { if (settings_read_in_) return false; bool was_committed = committed_; set_committed_state(false); if (other && other->settings_read_in_) { assert(empty()); del(); // to clean up any notifiers and similar stuff copy(*other); } else { if (other) merge(*other); const char * env = getenv("ASPELL_CONF"); if (env != 0) { insert_point_ = &first_; RET_ON_ERR(read_in_string(env, _("ASPELL_CONF env var"))); } { insert_point_ = &first_; PosibErrBase pe = read_in_file(retrieve("per-conf-path")); if (pe.has_err() && !pe.has_err(cant_read_file)) return pe; } { insert_point_ = &first_; PosibErrBase pe = read_in_file(retrieve("conf-path")); if (pe.has_err() && !pe.has_err(cant_read_file)) return pe; } if (was_committed) RET_ON_ERR(commit_all()); settings_read_in_ = true; } return true; } PosibErr<void> Config::commit_all(Vector<int> * phs, const char * codeset) { committed_ = true; others_ = first_; first_ = 0; insert_point_ = &first_; Conv to_utf8; if (codeset) RET_ON_ERR(to_utf8.setup(*this, codeset, "utf-8", NormTo)); while (others_) { *insert_point_ = others_; others_ = others_->next; (*insert_point_)->next = 0; RET_ON_ERR_SET(commit(*insert_point_, codeset ? &to_utf8 : 0), int, place_holder); if (phs && place_holder != -1 && (phs->empty() || phs->back() != place_holder)) phs->push_back(place_holder); insert_point_ = &((*insert_point_)->next); } return no_err; } PosibErr<void> Config::set_committed_state(bool val) { if (val && !committed_) { RET_ON_ERR(commit_all()); } else if (!val && committed_) { assert(empty()); committed_ = false; } return no_err; } #ifdef ENABLE_WIN32_RELOCATABLE # define HOME_DIR "<prefix>" # define PERSONAL "<lang>.pws" # define REPL "<lang>.prepl" #else # define HOME_DIR "<$HOME|./>" # define PERSONAL ".aspell.<lang>.pws" # define REPL ".aspell.<lang>.prepl" #endif static const KeyInfo config_keys[] = { // the description should be under 50 chars {"actual-dict-dir", KeyInfoString, "<dict-dir^master>", 0} , {"actual-lang", KeyInfoString, "", 0} , {"conf", KeyInfoString, "aspell.conf", /* TRANSLATORS: The remaining strings in config.cpp should be kept under 50 characters, begin with a lower case character and not include any trailing punctuation marks. */ N_("main configuration file")} , {"conf-dir", KeyInfoString, CONF_DIR, N_("location of main configuration file")} , {"conf-path", KeyInfoString, "<conf-dir/conf>", 0} , {"data-dir", KeyInfoString, DATA_DIR, N_("location of language data files")} , {"dict-alias", KeyInfoList, "", N_("create dictionary aliases")} , {"dict-dir", KeyInfoString, DICT_DIR, N_("location of the main word list")} , {"encoding", KeyInfoString, "!encoding", N_("encoding to expect data to be in"), KEYINFO_COMMON} , {"filter", KeyInfoList , "url", N_("add or removes a filter"), KEYINFO_MAY_CHANGE} , {"filter-path", KeyInfoList, DICT_DIR, N_("path(s) aspell looks for filters")} //, {"option-path", KeyInfoList, DATA_DIR, // N_("path(s) aspell looks for options descriptions")} , {"mode", KeyInfoString, "url", N_("filter mode"), KEYINFO_COMMON} , {"extra-dicts", KeyInfoList, "", N_("extra dictionaries to use")} , {"home-dir", KeyInfoString, HOME_DIR, N_("location for personal files")} , {"ignore", KeyInfoInt , "1", N_("ignore words <= n chars"), KEYINFO_MAY_CHANGE} , {"ignore-accents" , KeyInfoBool, "false", /* TRANSLATORS: It is OK if this is longer than 50 chars */ N_("ignore accents when checking words -- CURRENTLY IGNORED"), KEYINFO_MAY_CHANGE | KEYINFO_HIDDEN} , {"ignore-case", KeyInfoBool , "false", N_("ignore case when checking words"), KEYINFO_MAY_CHANGE} , {"ignore-repl", KeyInfoBool , "false", N_("ignore commands to store replacement pairs"), KEYINFO_MAY_CHANGE} , {"jargon", KeyInfoString, "", N_("extra information for the word list"), KEYINFO_HIDDEN} , {"keyboard", KeyInfoString, "standard", N_("keyboard definition to use for typo analysis")} , {"lang", KeyInfoString, "<language-tag>", N_("language code"), KEYINFO_COMMON} , {"language-tag", KeyInfoString, "!lang", N_("deprecated, use lang instead"), KEYINFO_HIDDEN} , {"local-data-dir", KeyInfoString, "<actual-dict-dir>", N_("location of local language data files") } , {"master", KeyInfoString, "<lang>", N_("base name of the main dictionary to use"), KEYINFO_COMMON} , {"master-flags", KeyInfoString, "", 0} , {"master-path", KeyInfoString, "<dict-dir/master>", 0} , {"module", KeyInfoString, "default", N_("set module name"), KEYINFO_HIDDEN} , {"module-search-order", KeyInfoList, "", N_("search order for modules"), KEYINFO_HIDDEN} , {"normalize", KeyInfoBool, "true", N_("enable Unicode normalization")} , {"norm-required", KeyInfoBool, "false", N_("Unicode normalization required for current lang")} , {"norm-form", KeyInfoString, "nfc", /* TRANSLATORS: the values after the ':' are literal values and should not be translated. */ N_("Unicode normalization form: none, nfd, nfc, comp")} , {"norm-strict", KeyInfoBool, "false", N_("avoid lossy conversions when normalization")} , {"per-conf", KeyInfoString, ".aspell.conf", N_("personal configuration file")} , {"per-conf-path", KeyInfoString, "<home-dir/per-conf>", 0} , {"personal", KeyInfoString, PERSONAL, N_("personal dictionary file name")} , {"personal-path", KeyInfoString, "<home-dir/personal>", 0} , {"prefix", KeyInfoString, PREFIX, N_("prefix directory")} , {"repl", KeyInfoString, REPL, N_("replacements list file name") } , {"repl-path", KeyInfoString, "<home-dir/repl>", 0} , {"run-together", KeyInfoBool, "false", N_("consider run-together words legal"), KEYINFO_MAY_CHANGE} , {"run-together-limit", KeyInfoInt, "2", N_("maximum number that can be strung together"), KEYINFO_MAY_CHANGE} , {"run-together-min", KeyInfoInt, "3", N_("minimal length of interior words"), KEYINFO_MAY_CHANGE} , {"save-repl", KeyInfoBool , "true", N_("save replacement pairs on save all")} , {"set-prefix", KeyInfoBool, "true", N_("set the prefix based on executable location")} , {"size", KeyInfoString, "+60", N_("size of the word list")} , {"spelling", KeyInfoString, "", N_("no longer used"), KEYINFO_HIDDEN} , {"sug-mode", KeyInfoString, "normal", N_("suggestion mode"), KEYINFO_MAY_CHANGE | KEYINFO_COMMON} , {"sug-typo-analysis", KeyInfoBool, "true", /* TRANSLATORS: "sug-mode" is a literal value and should not be translated. */ N_("use typo analysis, override sug-mode default")} , {"sug-repl-table", KeyInfoBool, "true", N_("use replacement tables, override sug-mode default")} , {"sug-split-char", KeyInfoList, "\\ :-", N_("characters to insert when a word is split"), KEYINFO_UTF8} , {"use-other-dicts", KeyInfoBool, "true", N_("use personal, replacement & session dictionaries")} , {"variety", KeyInfoList, "", N_("extra information for the word list")} , {"word-list-path", KeyInfoList, DATA_DIR, N_("search path for word list information files"), KEYINFO_HIDDEN} , {"warn", KeyInfoBool, "true", N_("enable warnings")} // // These options are generally used when creating dictionaries // and may also be specified in the language data file // , {"affix-char", KeyInfoString, "/", // FIXME: Implement /* TRANSLATORS: It is OK if this is longer than 50 chars */ N_("indicator for affix flags in word lists -- CURRENTLY IGNORED"), KEYINFO_UTF8 | KEYINFO_HIDDEN} , {"affix-compress", KeyInfoBool, "false", N_("use affix compression when creating dictionaries")} , {"clean-affixes", KeyInfoBool, "true", N_("remove invalid affix flags")} , {"clean-words", KeyInfoBool, "false", N_("attempts to clean words so that they are valid")} , {"invisible-soundslike", KeyInfoBool, "false", N_("compute soundslike on demand rather than storing")} , {"partially-expand", KeyInfoBool, "false", N_("partially expand affixes for better suggestions")} , {"skip-invalid-words", KeyInfoBool, "true", N_("skip invalid words")} , {"validate-affixes", KeyInfoBool, "true", N_("check if affix flags are valid")} , {"validate-words", KeyInfoBool, "true", N_("check if words are valid")} // // These options are specific to the "aspell" utility. They are // here so that they can be specified in configuration files. // , {"backup", KeyInfoBool, "true", N_("create a backup file by appending \".bak\"")} , {"byte-offsets", KeyInfoBool, "false", N_("use byte offsets instead of character offsets")} , {"guess", KeyInfoBool, "false", N_("create missing root/affix combinations"), KEYINFO_MAY_CHANGE} , {"keymapping", KeyInfoString, "aspell", N_("keymapping for check mode: \"aspell\" or \"ispell\"")} , {"reverse", KeyInfoBool, "false", N_("reverse the order of the suggest list")} , {"suggest", KeyInfoBool, "true", N_("suggest possible replacements"), KEYINFO_MAY_CHANGE} , {"time" , KeyInfoBool, "false", N_("time load time and suggest time in pipe mode"), KEYINFO_MAY_CHANGE} }; const KeyInfo * config_impl_keys_begin = config_keys; const KeyInfo * config_impl_keys_end = config_keys + sizeof(config_keys)/sizeof(KeyInfo); Config * new_basic_config() { aspell_gettext_init(); return new Config("aspell", config_impl_keys_begin, config_impl_keys_end); } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_1183_0
crossvul-cpp_data_good_2812_0
/***************************************************************** | | AP4 - hdlr Atoms | | Copyright 2002-2008 Axiomatic Systems, LLC | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4HdlrAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Utils.h" /*---------------------------------------------------------------------- | dynamic cast support +---------------------------------------------------------------------*/ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_HdlrAtom) /*---------------------------------------------------------------------- | AP4_HdlrAtom::Create +---------------------------------------------------------------------*/ AP4_HdlrAtom* AP4_HdlrAtom::Create(AP4_Size size, AP4_ByteStream& stream) { AP4_UI08 version; AP4_UI32 flags; if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL; if (version != 0) return NULL; return new AP4_HdlrAtom(size, version, flags, stream); } /*---------------------------------------------------------------------- | AP4_HdlrAtom::AP4_HdlrAtom +---------------------------------------------------------------------*/ AP4_HdlrAtom::AP4_HdlrAtom(AP4_Atom::Type hdlr_type, const char* hdlr_name) : AP4_Atom(AP4_ATOM_TYPE_HDLR, AP4_FULL_ATOM_HEADER_SIZE, 0, 0), m_HandlerType(hdlr_type), m_HandlerName(hdlr_name) { m_Size32 += 20+m_HandlerName.GetLength()+1; m_Reserved[0] = m_Reserved[1] = m_Reserved[2] = 0; } /*---------------------------------------------------------------------- | AP4_HdlrAtom::AP4_HdlrAtom +---------------------------------------------------------------------*/ AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags) { AP4_UI32 predefined; stream.ReadUI32(predefined); stream.ReadUI32(m_HandlerType); stream.ReadUI32(m_Reserved[0]); stream.ReadUI32(m_Reserved[1]); stream.ReadUI32(m_Reserved[2]); // read the name unless it is empty if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return; AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20); char* name = new char[name_size+1]; if (name == NULL) return; stream.Read(name, name_size); name[name_size] = '\0'; // force a null termination // handle a special case: the Quicktime files have a pascal // string here, but ISO MP4 files have a C string. // we try to detect a pascal encoding and correct it. if ((AP4_UI08)name[0] == (AP4_UI08)(name_size-1)) { m_HandlerName = name+1; } else { m_HandlerName = name; } delete[] name; } /*---------------------------------------------------------------------- | AP4_HdlrAtom::WriteFields +---------------------------------------------------------------------*/ AP4_Result AP4_HdlrAtom::WriteFields(AP4_ByteStream& stream) { AP4_Result result; // write the data result = stream.WriteUI32(0); // predefined if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_HandlerType); if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_Reserved[0]); if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_Reserved[1]); if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_Reserved[2]); if (AP4_FAILED(result)) return result; AP4_UI08 name_size = (AP4_UI08)m_HandlerName.GetLength(); if (AP4_FULL_ATOM_HEADER_SIZE+20+name_size > m_Size32) { name_size = (AP4_UI08)(m_Size32-AP4_FULL_ATOM_HEADER_SIZE+20); } if (name_size) { result = stream.Write(m_HandlerName.GetChars(), name_size); if (AP4_FAILED(result)) return result; } // pad with zeros if necessary AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+20+name_size); while (padding--) stream.WriteUI08(0); return AP4_SUCCESS; } /*---------------------------------------------------------------------- | AP4_HdlrAtom::InspectFields +---------------------------------------------------------------------*/ AP4_Result AP4_HdlrAtom::InspectFields(AP4_AtomInspector& inspector) { char type[5]; AP4_FormatFourChars(type, m_HandlerType); inspector.AddField("handler_type", type); inspector.AddField("handler_name", m_HandlerName.GetChars()); return AP4_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_2812_0
crossvul-cpp_data_good_4256_2
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/BCGen/HBC/BytecodeGenerator.h" #include "hermes/BCGen/HBC/ConsecutiveStringStorage.h" #include "hermes/FrontEndDefs/Builtins.h" #include "hermes/Support/OSCompat.h" #include "hermes/Support/UTF8.h" #include "llvh/ADT/SmallString.h" #include "llvh/Support/Format.h" #include "llvh/Support/raw_ostream.h" #include <locale> #include <unordered_map> using hermes::oscompat::to_string; namespace hermes { namespace hbc { unsigned BytecodeFunctionGenerator::getStringID(LiteralString *value) const { return BMGen_.getStringID(value->getValue().str()); } unsigned BytecodeFunctionGenerator::getIdentifierID( LiteralString *value) const { return BMGen_.getIdentifierID(value->getValue().str()); } uint32_t BytecodeFunctionGenerator::addRegExp(CompiledRegExp regexp) { return BMGen_.addRegExp(std::move(regexp)); } uint32_t BytecodeFunctionGenerator::addFilename(StringRef filename) { return BMGen_.addFilename(filename); } void BytecodeFunctionGenerator::addExceptionHandler( HBCExceptionHandlerInfo info) { exceptionHandlers_.push_back(info); } void BytecodeFunctionGenerator::addDebugSourceLocation( const DebugSourceLocation &info) { // If an address is repeated, it means no actual bytecode was emitted for the // previous source location. if (!debugLocations_.empty() && debugLocations_.back().address == info.address) { debugLocations_.back() = info; } else { debugLocations_.push_back(info); } } void BytecodeFunctionGenerator::setJumpTable( std::vector<uint32_t> &&jumpTable) { assert(!jumpTable.empty() && "invoked with no jump table"); jumpTable_ = std::move(jumpTable); } uint32_t BytecodeModuleGenerator::addArrayBuffer(ArrayRef<Literal *> elements) { return literalGenerator_.serializeBuffer(elements, arrayBuffer_, false); } std::pair<uint32_t, uint32_t> BytecodeModuleGenerator::addObjectBuffer( ArrayRef<Literal *> keys, ArrayRef<Literal *> vals) { return std::pair<uint32_t, uint32_t>{ literalGenerator_.serializeBuffer(keys, objKeyBuffer_, true), literalGenerator_.serializeBuffer(vals, objValBuffer_, false)}; } std::unique_ptr<BytecodeFunction> BytecodeFunctionGenerator::generateBytecodeFunction( Function::DefinitionKind definitionKind, ValueKind valueKind, bool strictMode, uint32_t paramCount, uint32_t environmentSize, uint32_t nameID) { return std::unique_ptr<BytecodeFunction>(new BytecodeFunction( std::move(opcodes_), definitionKind, valueKind, strictMode, FunctionHeader( bytecodeSize_, paramCount, frameSize_, environmentSize, nameID, highestReadCacheIndex_, highestWriteCacheIndex_), std::move(exceptionHandlers_), std::move(jumpTable_))); } unsigned BytecodeFunctionGenerator::getFunctionID(Function *F) { return BMGen_.addFunction(F); } void BytecodeFunctionGenerator::shrinkJump(offset_t loc) { // We are shrinking a long jump into a short jump. // The size of operand reduces from 4 bytes to 1 byte, a delta of 3. const static int ShrinkOffset = 3; std::rotate( opcodes_.begin() + loc, opcodes_.begin() + loc + ShrinkOffset, opcodes_.end()); opcodes_.resize(opcodes_.size() - ShrinkOffset); // Change this instruction from long jump to short jump. longToShortJump(loc - 1); } void BytecodeFunctionGenerator::updateJumpTarget( offset_t loc, int newVal, int bytes) { // The jump target is encoded in little-endian. Update it correctly // regardless of host byte order. for (; bytes; --bytes, ++loc) { opcodes_[loc] = (opcode_atom_t)(newVal); newVal >>= 8; } } void BytecodeFunctionGenerator::updateJumpTableOffset( offset_t loc, uint32_t jumpTableOffset, uint32_t instLoc) { assert(opcodes_.size() > instLoc && "invalid switchimm offset"); // The offset is not aligned, but will be aligned when read in the // interpreter. updateJumpTarget( loc, opcodes_.size() + jumpTableOffset * sizeof(uint32_t) - instLoc, sizeof(uint32_t)); } unsigned BytecodeModuleGenerator::addFunction(Function *F) { lazyFunctions_ |= F->isLazy(); return functionIDMap_.allocate(F); } void BytecodeModuleGenerator::setFunctionGenerator( Function *F, unique_ptr<BytecodeFunctionGenerator> BFG) { assert( functionGenerators_.find(F) == functionGenerators_.end() && "Adding same function twice."); functionGenerators_[F] = std::move(BFG); } unsigned BytecodeModuleGenerator::getStringID(StringRef str) const { return stringTable_.getStringID(str); } unsigned BytecodeModuleGenerator::getIdentifierID(StringRef str) const { return stringTable_.getIdentifierID(str); } void BytecodeModuleGenerator::initializeStringTable( StringLiteralTable stringTable) { assert(stringTable_.empty() && "String table must be empty"); stringTable_ = std::move(stringTable); } uint32_t BytecodeModuleGenerator::addRegExp(CompiledRegExp regexp) { return regExpTable_.addRegExp(std::move(regexp)); } uint32_t BytecodeModuleGenerator::addFilename(StringRef filename) { return filenameTable_.addFilename(filename); } void BytecodeModuleGenerator::addCJSModule( uint32_t functionID, uint32_t nameID) { assert( cjsModulesStatic_.empty() && "Statically resolved modules must be in cjsModulesStatic_"); cjsModules_.push_back({nameID, functionID}); } void BytecodeModuleGenerator::addCJSModuleStatic( uint32_t moduleID, uint32_t functionID) { assert(cjsModules_.empty() && "Unresolved modules must be in cjsModules_"); assert( moduleID - cjsModuleOffset_ == cjsModulesStatic_.size() && "Module ID out of order in cjsModulesStatic_"); (void)moduleID; cjsModulesStatic_.push_back(functionID); } std::unique_ptr<BytecodeModule> BytecodeModuleGenerator::generate() { assert( valid_ && "BytecodeModuleGenerator::generate() cannot be called more than once"); valid_ = false; assert( functionIDMap_.getElements().size() == functionGenerators_.size() && "Missing functions."); auto kinds = stringTable_.getStringKinds(); auto hashes = stringTable_.getIdentifierHashes(); BytecodeOptions bytecodeOptions; bytecodeOptions.staticBuiltins = options_.staticBuiltinsEnabled; bytecodeOptions.cjsModulesStaticallyResolved = !cjsModulesStatic_.empty(); std::unique_ptr<BytecodeModule> BM{new BytecodeModule( functionGenerators_.size(), std::move(kinds), std::move(hashes), stringTable_.acquireStringTable(), stringTable_.acquireStringStorage(), regExpTable_.getEntryList(), regExpTable_.getBytecodeBuffer(), entryPointIndex_, std::move(arrayBuffer_), std::move(objKeyBuffer_), std::move(objValBuffer_), cjsModuleOffset_, std::move(cjsModules_), std::move(cjsModulesStatic_), bytecodeOptions)}; DebugInfoGenerator debugInfoGen{std::move(filenameTable_)}; const uint32_t strippedFunctionNameId = options_.stripFunctionNames ? getStringID(kStrippedFunctionName) : 0; auto functions = functionIDMap_.getElements(); std::shared_ptr<Context> contextIfNeeded; for (unsigned i = 0, e = functions.size(); i < e; ++i) { auto *F = functions[i]; auto &BFG = *functionGenerators_[F]; uint32_t functionNameId = options_.stripFunctionNames ? strippedFunctionNameId : getStringID(functions[i]->getOriginalOrInferredName().str()); std::unique_ptr<BytecodeFunction> func = BFG.generateBytecodeFunction( F->getDefinitionKind(), F->getKind(), F->isStrictMode(), F->getExpectedParamCountIncludingThis(), F->getFunctionScope()->getVariables().size(), functionNameId); #ifndef HERMESVM_LEAN if (F->getParent() ->shareContext() ->allowFunctionToStringWithRuntimeSource() || F->isLazy()) { auto context = F->getParent()->shareContext(); assert( (!contextIfNeeded || contextIfNeeded.get() == context.get()) && "Different instances of Context seen"); contextIfNeeded = context; BM->setFunctionSourceRange(i, F->getSourceRange()); } #endif if (F->isLazy()) { #ifdef HERMESVM_LEAN llvm_unreachable("Lazy support compiled out"); #else auto lazyData = llvh::make_unique<LazyCompilationData>(); lazyData->parentScope = F->getLazyScope(); lazyData->nodeKind = F->getLazySource().nodeKind; lazyData->isGeneratorInnerFunction = F->getLazySource().isGeneratorInnerFunction; lazyData->bufferId = F->getLazySource().bufferId; lazyData->originalName = F->getOriginalOrInferredName(); lazyData->closureAlias = F->getLazyClosureAlias() ? F->getLazyClosureAlias()->getName() : Identifier(); lazyData->strictMode = F->isStrictMode(); func->setLazyCompilationData(std::move(lazyData)); #endif } if (BFG.hasDebugInfo()) { uint32_t sourceLocOffset = debugInfoGen.appendSourceLocations( BFG.getSourceLocation(), i, BFG.getDebugLocations()); uint32_t lexicalDataOffset = debugInfoGen.appendLexicalData( BFG.getLexicalParentID(), BFG.getDebugVariableNames()); func->setDebugOffsets({sourceLocOffset, lexicalDataOffset}); } BM->setFunction(i, std::move(func)); } BM->setContext(contextIfNeeded); BM->setDebugInfo(debugInfoGen.serializeWithMove()); return BM; } } // namespace hbc } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_4256_2
crossvul-cpp_data_bad_2812_0
/***************************************************************** | | AP4 - hdlr Atoms | | Copyright 2002-2008 Axiomatic Systems, LLC | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4HdlrAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Utils.h" /*---------------------------------------------------------------------- | dynamic cast support +---------------------------------------------------------------------*/ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_HdlrAtom) /*---------------------------------------------------------------------- | AP4_HdlrAtom::Create +---------------------------------------------------------------------*/ AP4_HdlrAtom* AP4_HdlrAtom::Create(AP4_Size size, AP4_ByteStream& stream) { AP4_UI08 version; AP4_UI32 flags; if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL; if (version != 0) return NULL; return new AP4_HdlrAtom(size, version, flags, stream); } /*---------------------------------------------------------------------- | AP4_HdlrAtom::AP4_HdlrAtom +---------------------------------------------------------------------*/ AP4_HdlrAtom::AP4_HdlrAtom(AP4_Atom::Type hdlr_type, const char* hdlr_name) : AP4_Atom(AP4_ATOM_TYPE_HDLR, AP4_FULL_ATOM_HEADER_SIZE, 0, 0), m_HandlerType(hdlr_type), m_HandlerName(hdlr_name) { m_Size32 += 20+m_HandlerName.GetLength()+1; m_Reserved[0] = m_Reserved[1] = m_Reserved[2] = 0; } /*---------------------------------------------------------------------- | AP4_HdlrAtom::AP4_HdlrAtom +---------------------------------------------------------------------*/ AP4_HdlrAtom::AP4_HdlrAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_HDLR, size, version, flags) { AP4_UI32 predefined; stream.ReadUI32(predefined); stream.ReadUI32(m_HandlerType); stream.ReadUI32(m_Reserved[0]); stream.ReadUI32(m_Reserved[1]); stream.ReadUI32(m_Reserved[2]); // read the name unless it is empty if (size < AP4_FULL_ATOM_HEADER_SIZE+20) return; AP4_UI32 name_size = size-(AP4_FULL_ATOM_HEADER_SIZE+20); char* name = new char[name_size+1]; if (name == NULL) return; stream.Read(name, name_size); name[name_size] = '\0'; // force a null termination // handle a special case: the Quicktime files have a pascal // string here, but ISO MP4 files have a C string. // we try to detect a pascal encoding and correct it. if (name[0] == name_size-1) { m_HandlerName = name+1; } else { m_HandlerName = name; } delete[] name; } /*---------------------------------------------------------------------- | AP4_HdlrAtom::WriteFields +---------------------------------------------------------------------*/ AP4_Result AP4_HdlrAtom::WriteFields(AP4_ByteStream& stream) { AP4_Result result; // write the data result = stream.WriteUI32(0); // predefined if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_HandlerType); if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_Reserved[0]); if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_Reserved[1]); if (AP4_FAILED(result)) return result; result = stream.WriteUI32(m_Reserved[2]); if (AP4_FAILED(result)) return result; AP4_UI08 name_size = (AP4_UI08)m_HandlerName.GetLength(); if (AP4_FULL_ATOM_HEADER_SIZE+20+name_size > m_Size32) { name_size = (AP4_UI08)(m_Size32-AP4_FULL_ATOM_HEADER_SIZE+20); } if (name_size) { result = stream.Write(m_HandlerName.GetChars(), name_size); if (AP4_FAILED(result)) return result; } // pad with zeros if necessary AP4_Size padding = m_Size32-(AP4_FULL_ATOM_HEADER_SIZE+20+name_size); while (padding--) stream.WriteUI08(0); return AP4_SUCCESS; } /*---------------------------------------------------------------------- | AP4_HdlrAtom::InspectFields +---------------------------------------------------------------------*/ AP4_Result AP4_HdlrAtom::InspectFields(AP4_AtomInspector& inspector) { char type[5]; AP4_FormatFourChars(type, m_HandlerType); inspector.AddField("handler_type", type); inspector.AddField("handler_name", m_HandlerName.GetChars()); return AP4_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_2812_0
crossvul-cpp_data_bad_2323_0
/* This file has been derived from Konversation, the KDE IRC client. 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 2 of the License, or (at your option) any later version. */ /* Copyright (C) 1997 Robey Pointer <robeypointer@gmail.com> Copyright (C) 2005 Ismail Donmez <ismail@kde.org> Copyright (C) 2009 Travis McHenry <tmchenryaz@cox.net> Copyright (C) 2009 Johannes Huber <johu@gmx.de> */ #include "cipher.h" #include "logger.h" Cipher::Cipher() { m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923"); setType("blowfish"); } Cipher::Cipher(QByteArray key, QString cipherType) { m_primeNum = QCA::BigInteger("12745216229761186769575009943944198619149164746831579719941140425076456621824834322853258804883232842877311723249782818608677050956745409379781245497526069657222703636504651898833151008222772087491045206203033063108075098874712912417029101508315117935752962862335062591404043092163187352352197487303798807791605274487594646923"); setKey(key); setType(cipherType); } Cipher::~Cipher() {} bool Cipher::setKey(QByteArray key) { if (key.isEmpty()) { m_key.clear(); return false; } if (key.mid(0, 4).toLower() == "ecb:") { m_cbc = false; m_key = key.mid(4); } //strip cbc: if included else if (key.mid(0, 4).toLower() == "cbc:") { m_cbc = true; m_key = key.mid(4); } else { // if(Preferences::self()->encryptionType()) // m_cbc = true; // else m_cbc = false; m_key = key; } return true; } bool Cipher::setType(const QString &type) { //TODO check QCA::isSupported() m_type = type; return true; } QByteArray Cipher::decrypt(QByteArray cipherText) { QByteArray pfx = ""; bool error = false; // used to flag non cbc, seems like good practice not to parse w/o regard for set encryption type //if we get cbc if (cipherText.mid(0, 5) == "+OK *") { //if we have cbc if (m_cbc) cipherText = cipherText.mid(5); //if we don't else { cipherText = cipherText.mid(5); pfx = "ERROR_NONECB: "; error = true; } } //if we get ecb else if (cipherText.mid(0, 4) == "+OK " || cipherText.mid(0, 5) == "mcps ") { //if we had cbc if (m_cbc) { cipherText = (cipherText.mid(0, 4) == "+OK ") ? cipherText.mid(4) : cipherText.mid(5); pfx = "ERROR_NONCBC: "; error = true; } //if we don't else { if (cipherText.mid(0, 4) == "+OK ") cipherText = cipherText.mid(4); else cipherText = cipherText.mid(5); } } //all other cases we fail else return cipherText; QByteArray temp; // (if cbc and no error we parse cbc) || (if ecb and error we parse cbc) if ((m_cbc && !error) || (!m_cbc && error)) { cipherText = cipherText; temp = blowfishCBC(cipherText, false); if (temp == cipherText) { // kDebug("Decryption from CBC Failed"); return cipherText+' '+'\n'; } else cipherText = temp; } else { temp = blowfishECB(cipherText, false); if (temp == cipherText) { // kDebug("Decryption from ECB Failed"); return cipherText+' '+'\n'; } else cipherText = temp; } // TODO FIXME the proper fix for this is to show encryption differently e.g. [nick] instead of <nick> // don't hate me for the mircryption reference there. if (cipherText.at(0) == 1) pfx = "\x0"; cipherText = pfx+cipherText+' '+'\n'; // FIXME(??) why is there an added space here? return cipherText; } QByteArray Cipher::initKeyExchange() { QCA::Initializer init; m_tempKey = QCA::KeyGenerator().createDH(QCA::DLGroup(m_primeNum, QCA::BigInteger(2))).toDH(); if (m_tempKey.isNull()) return QByteArray(); QByteArray publicKey = m_tempKey.toPublicKey().toDH().y().toArray().toByteArray(); //remove leading 0 if (publicKey.length() > 135 && publicKey.at(0) == '\0') publicKey = publicKey.mid(1); return publicKey.toBase64().append('A'); } QByteArray Cipher::parseInitKeyX(QByteArray key) { QCA::Initializer init; bool isCBC = false; if (key.endsWith(" CBC")) { isCBC = true; key.chop(4); } if (key.length() != 181) return QByteArray(); QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180)); QCA::DLGroup group(m_primeNum, QCA::BigInteger(2)); QCA::DHPrivateKey privateKey = QCA::KeyGenerator().createDH(group).toDH(); if (privateKey.isNull()) return QByteArray(); QByteArray publicKey = privateKey.y().toArray().toByteArray(); //remove leading 0 if (publicKey.length() > 135 && publicKey.at(0) == '\0') publicKey = publicKey.mid(1); QCA::DHPublicKey remotePub(group, remoteKey); if (remotePub.isNull()) return QByteArray(); QByteArray sharedKey = privateKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); //remove trailing = because mircryption and fish think it's a swell idea. while (sharedKey.endsWith('=')) sharedKey.chop(1); if (isCBC) sharedKey.prepend("cbc:"); bool success = setKey(sharedKey); if (!success) return QByteArray(); return publicKey.toBase64().append('A'); } bool Cipher::parseFinishKeyX(QByteArray key) { QCA::Initializer init; if (key.length() != 181) return false; QCA::SecureArray remoteKey = QByteArray::fromBase64(key.left(180)); QCA::DLGroup group(m_primeNum, QCA::BigInteger(2)); QCA::DHPublicKey remotePub(group, remoteKey); if (remotePub.isNull()) return false; if (m_tempKey.isNull()) return false; QByteArray sharedKey = m_tempKey.deriveKey(remotePub).toByteArray(); sharedKey = QCA::Hash("sha256").hash(sharedKey).toByteArray().toBase64(); //remove trailng = because mircryption and fish think it's a swell idea. while (sharedKey.endsWith('=')) sharedKey.chop(1); bool success = setKey(sharedKey); return success; } QByteArray Cipher::decryptTopic(QByteArray cipherText) { if (cipherText.mid(0, 4) == "+OK ") // FiSH style topic cipherText = cipherText.mid(4); else if (cipherText.left(5) == "«m«") cipherText = cipherText.mid(5, cipherText.length()-10); else return cipherText; QByteArray temp; //TODO currently no backwards sanity checks for topic, it seems to use different standards //if somebody figures them out they can enable it and add "ERROR_NONECB/CBC" warnings if (m_cbc) temp = blowfishCBC(cipherText.mid(1), false); else temp = blowfishECB(cipherText, false); if (temp == cipherText) { return cipherText; } else cipherText = temp; if (cipherText.mid(0, 2) == "@@") cipherText = cipherText.mid(2); return cipherText; } bool Cipher::encrypt(QByteArray &cipherText) { if (cipherText.left(3) == "+p ") //don't encode if...? cipherText = cipherText.mid(3); else { if (m_cbc) //encode in ecb or cbc decide how to determine later { QByteArray temp = blowfishCBC(cipherText, true); if (temp == cipherText) { // kDebug("CBC Encoding Failed"); return false; } cipherText = "+OK *" + temp; } else { QByteArray temp = blowfishECB(cipherText, true); if (temp == cipherText) { // kDebug("ECB Encoding Failed"); return false; } cipherText = "+OK " + temp; } } return true; } //THE BELOW WORKS AKA DO NOT TOUCH UNLESS YOU KNOW WHAT YOU'RE DOING QByteArray Cipher::blowfishCBC(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; if (direction) { // make sure cipherText is an interval of 8 bits. We do this before so that we // know there's at least 8 bytes to en/decryption this ensures QCA doesn't fail while ((temp.length() % 8) != 0) temp.append('\0'); QCA::InitializationVector iv(8); temp.prepend(iv.toByteArray()); // prefix with 8bits of IV for mircryptions *CUSTOM* cbc implementation } else { temp = QByteArray::fromBase64(temp); //supposedly nescessary if we get a truncated message also allows for decryption of 'crazy' //en/decoding clients that use STANDARDIZED PADDING TECHNIQUES while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::CBC, QCA::Cipher::NoPadding, dir, m_key, QCA::InitializationVector(QByteArray("0"))); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) //send in base64 temp2 = temp2.toBase64(); else //cut off the 8bits of IV temp2 = temp2.remove(0, 8); return temp2; } QByteArray Cipher::blowfishECB(QByteArray cipherText, bool direction) { QCA::Initializer init; QByteArray temp = cipherText; //do padding ourselves if (direction) { while ((temp.length() % 8) != 0) temp.append('\0'); } else { temp = b64ToByte(temp); while ((temp.length() % 8) != 0) temp.append('\0'); } QCA::Direction dir = (direction) ? QCA::Encode : QCA::Decode; QCA::Cipher cipher(m_type, QCA::Cipher::ECB, QCA::Cipher::NoPadding, dir, m_key); QByteArray temp2 = cipher.update(QCA::MemoryRegion(temp)).toByteArray(); temp2 += cipher.final().toByteArray(); if (!cipher.ok()) return cipherText; if (direction) temp2 = byteToB64(temp2); return temp2; } //Custom non RFC 2045 compliant Base64 enc/dec code for mircryption / FiSH compatibility QByteArray Cipher::byteToB64(QByteArray text) { int left = 0; int right = 0; int k = -1; int v; QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; QByteArray encoded; while (k < (text.length() - 1)) { k++; v = text.at(k); if (v < 0) v += 256; left = v << 24; k++; v = text.at(k); if (v < 0) v += 256; left += v << 16; k++; v = text.at(k); if (v < 0) v += 256; left += v << 8; k++; v = text.at(k); if (v < 0) v += 256; left += v; k++; v = text.at(k); if (v < 0) v += 256; right = v << 24; k++; v = text.at(k); if (v < 0) v += 256; right += v << 16; k++; v = text.at(k); if (v < 0) v += 256; right += v << 8; k++; v = text.at(k); if (v < 0) v += 256; right += v; for (int i = 0; i < 6; i++) { encoded.append(base64.at(right & 0x3F).toAscii()); right = right >> 6; } //TODO make sure the .toascii doesn't break anything for (int i = 0; i < 6; i++) { encoded.append(base64.at(left & 0x3F).toAscii()); left = left >> 6; } } return encoded; } QByteArray Cipher::b64ToByte(QByteArray text) { QString base64 = "./0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; QByteArray decoded; int k = -1; while (k < (text.length() - 1)) { int right = 0; int left = 0; int v = 0; int w = 0; int z = 0; for (int i = 0; i < 6; i++) { k++; v = base64.indexOf(text.at(k)); right |= v << (i * 6); } for (int i = 0; i < 6; i++) { k++; v = base64.indexOf(text.at(k)); left |= v << (i * 6); } for (int i = 0; i < 4; i++) { w = ((left & (0xFF << ((3 - i) * 8)))); z = w >> ((3 - i) * 8); if (z < 0) { z = z + 256; } decoded.append(z); } for (int i = 0; i < 4; i++) { w = ((right & (0xFF << ((3 - i) * 8)))); z = w >> ((3 - i) * 8); if (z < 0) { z = z + 256; } decoded.append(z); } } return decoded; } bool Cipher::neededFeaturesAvailable() { QCA::Initializer init; if (QCA::isSupported("blowfish-ecb") && QCA::isSupported("blowfish-cbc") && QCA::isSupported("dh")) return true; return false; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_2323_0
crossvul-cpp_data_good_4251_0
/* JSON_parser.c */ /* 2005-12-30 */ /* Copyright (c) 2005 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // If we have json-c then don't use this library since that one has a more // permissive licence #ifndef HAVE_JSONC #include "hphp/runtime/ext/json/JSON_parser.h" #include <folly/FBVector.h> #include "hphp/runtime/base/array-provenance.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/collections.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-info.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/base/init-fini-node.h" #include "hphp/runtime/base/utf8-decode.h" #include "hphp/runtime/ext/json/ext_json.h" #include "hphp/runtime/ext/collections/ext_collections-map.h" #include "hphp/runtime/ext/collections/ext_collections-vector.h" #include "hphp/system/systemlib.h" #include "hphp/util/fast_strtoll_base10.h" #include "hphp/zend/zend-strtod.h" #define MAX_LENGTH_OF_LONG 20 static const char long_min_digits[] = "9223372036854775808"; namespace HPHP { /* Characters are mapped into these 32 symbol classes. This allows for significant reductions in the size of the state transition table. */ /* error */ #define S_ERR -1 /* space */ #define S_SPA 0 /* other whitespace */ #define S_WSP 1 /* { */ #define S_LBE 2 /* } */ #define S_RBE 3 /* [ */ #define S_LBT 4 /* ] */ #define S_RBT 5 /* : */ #define S_COL 6 /* , */ #define S_COM 7 /* " */ #define S_QUO 8 /* \ */ #define S_BAC 9 /* / */ #define S_SLA 10 /* + */ #define S_PLU 11 /* - */ #define S_MIN 12 /* . */ #define S_DOT 13 /* 0 */ #define S_ZER 14 /* 123456789 */ #define S_DIG 15 /* a */ #define S__A_ 16 /* b */ #define S__B_ 17 /* c */ #define S__C_ 18 /* d */ #define S__D_ 19 /* e */ #define S__E_ 20 /* f */ #define S__F_ 21 /* l */ #define S__L_ 22 /* n */ #define S__N_ 23 /* r */ #define S__R_ 24 /* s */ #define S__S_ 25 /* t */ #define S__T_ 26 /* u */ #define S__U_ 27 /* ABCDF */ #define S_A_F 28 /* E */ #define S_E 29 /* everything else */ #define S_ETC 30 /* This table maps the 128 ASCII characters into the 32 character classes. The remaining Unicode characters should be mapped to S_ETC. */ alignas(64) static const int8_t ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*<fb>*/ alignas(64) static const int8_t loose_ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*</fb>*/ /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. A new state is a number between 0 and 29. An action is a negative number between -1 and -9. A JSON text is accepted if the end of the text is in state 9 and mode is Mode::DONE. */ alignas(64) static const int8_t state_transition_table[30][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} }; /*<fb>*/ /* Alternate "loose" transition table to support unquoted keys. Note: State 3 has same outgoing transitions in both transition tables. This is used below in the fast-case for appending simple characters (3 -> 3). */ alignas(64) static const int8_t loose_state_transition_table[31][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-7,-1,-1,-1,-7, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /*30*/ {30,-1,30,30,30,30,-10,30,-4,4,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30} }; /*</fb>*/ /** * These modes can be pushed on the PDA stack. */ enum class Mode { INVALID = 0, DONE = 1, KEY = 2, OBJECT = 3, ARRAY = 4 }; namespace { int dehexchar(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - ('A' - 10); if (c >= 'a' && c <= 'f') return c - ('a' - 10); return -1; } NEVER_INLINE static void tvDecRefRange(TypedValue* begin, TypedValue* end) { assertx(begin <= end); for (auto tv = begin; tv != end; ++tv) { tvDecRefGen(tv); } } /* * Parses a subset of JSON. Currently unsupported: * - Non-ASCII * - Character escape sequences * - Non-string array keys * - Arrays nested > 255 levels */ struct SimpleParser { static constexpr int kMaxArrayDepth = 255; /* * Returns buffer size in bytes needed to handle any input up to given length. */ static size_t BufferBytesForLength(int length) { return (length + 1) * sizeof(TypedValue) / 2; // Worst case: "[0,0,...,0]" } /* * Returns false for unsupported or malformed input (does not distinguish). */ static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); if (!ok || (parser.skipSpace(), parser.p != inp + length)) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; } private: SimpleParser(const char* input, int length, TypedValue* buffer, JSONContainerType container_type, bool is_tsimplejson) : p(input) , top(buffer) , array_depth(-kMaxArrayDepth) /* Start negative to simplify check. */ , container_type(container_type) , is_tsimplejson(is_tsimplejson) { assertx(input[length] == 0); // Parser relies on sentinel to avoid checks. } /* * Skip whitespace, then if next char is 'ch', consume it and return true, * otherwise let it be and return false. */ bool matchSeparator(char ch) { if (LIKELY(*p++ == ch)) return true; return matchSeparatorSlow(ch); } NEVER_INLINE bool matchSeparatorSlow(char ch) { --p; skipSpace(); if (LIKELY(*p++ == ch)) return true; --p; return false; } NEVER_INLINE void skipSpace() { while (isSpace(*p)) p++; } bool isSpace(char ch) const { return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\f'; } /* * Variant parser. * * JSON arrays don't permit leading 0's in numbers, so we have to thread that * context through here to parseNumber(). */ bool parseValue(bool array_elem = false) { auto const ch = *p++; if (ch == '{') return parseMixed(); else if (ch == '[') return parsePacked(); else if (ch == '\"') return parseString(); else if ((ch >= '0' && ch <= '9') || ch == '-') return parseNumber(ch, array_elem); else if (ch == 't') return parseRue(); else if (ch == 'f') return parseAlse(); else if (ch == 'n') return parseUll(); else if (isSpace(ch)) { skipSpace(); return parseValue(array_elem); } else return false; } bool parseRue() { if (*p++ != 'r') return false; if (*p++ != 'u') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = true; return true; } bool parseAlse() { if (*p++ != 'a') return false; if (*p++ != 'l') return false; if (*p++ != 's') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = false; return true; } bool parseUll() { if (*p++ != 'u') return false; if (*p++ != 'l') return false; if (*p++ != 'l') return false; top++->m_type = KindOfNull; return true; } bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; if (UNLIKELY(ch1 != '0')) return false; auto const ch2 = *p++; if (UNLIKELY(ch2 != '0')) return false; auto const dch3 = dehexchar(*p++); if (UNLIKELY(dch3 < 0)) return false; auto const dch4 = dehexchar(*p++); if (UNLIKELY(dch4 < 0)) return false; out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } } bool parseRawString(int* len) { assertx(p[-1] == '"'); // SimpleParser only handles "-quoted strings *len = 0; auto const charTop = reinterpret_cast<signed char*>(top); for (signed char ch = *p++; ch != '\"'; ch = *p++) { charTop[(*len)++] = ch; // overwritten later if `ch == '\\'` if (ch < ' ') { // `ch < ' '` catches null and also non-ASCII (since signed char) return false; } else if (ch == '\\') { if (!handleBackslash(charTop[*len - 1])) return false; } } return true; } bool parseString() { int len; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); pushStringData(StringData::Make(start, len, CopyString)); return true; } bool parseMixedKey() { int len; int64_t num; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); auto const slice = folly::StringPiece(start, len); start[len] = '\0'; if (container_type != JSONContainerType::HACK_ARRAYS && container_type != JSONContainerType::LEGACY_HACK_ARRAYS && is_strictly_integer(start, len, num)) { pushInt64(num); } else if (auto const str = lookupStaticString(slice)) { auto const tv = top++; tv->m_type = KindOfPersistentString; tv->m_data.pstr = str; } else { pushStringData(StringData::Make(start, len, CopyString)); } return true; } bool parsePacked() { auto const fp = top; if (!matchSeparator(']')) { if (++array_depth >= 0) return false; do { if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator(']')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateVec() : PackedArray::MakeVecNatural(top - fp, fp); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyVecArray()->copy() : PackedArray::MakeVecNatural(top - fp, fp); ret->setLegacyArray(true); return ret; } if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { return top == fp ? ArrayData::CreateVArray() : PackedArray::MakeVArrayNatural(top - fp, fp); } assertx(container_type == JSONContainerType::DARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArrayNatural(top - fp, fp); }(); top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } bool parseMixed() { auto const fp = top; if (!matchSeparator('}')) { if (++array_depth >= 0) return false; do { if (!matchSeparator('\"')) return false; // Only support string keys. if (!parseMixedKey()) return false; // TODO(14491721): Precompute and save hash to avoid deref in MakeMixed. if (!matchSeparator(':')) return false; if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator('}')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateDict() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyDictArray()->copy() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); ret->setLegacyArray(true); return ret; } assertx(container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArray((top - fp) >> 1, fp)->asArrayData(); }(); // MixedArray::MakeMixed can return nullptr if there are duplicate keys if (!arr) return false; top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } /* * Parse remainder of number after initial character firstChar (maybe '-'). */ bool parseNumber(char firstChar, bool array_elem = false) { uint64_t x = 0; bool neg = false; const char* begin = p - 1; if (firstChar == '-') { neg = true; } else { x = firstChar - '0'; // first digit } // Parse maximal digit sequence into x (non-negative). while (*p >= '0' && *p <= '9') { x = (x * 10) + (*p - '0'); ++p; } if (*p == '.' || *p == 'e' || *p == 'E') { pushDouble(zend_strtod(begin, &p)); return true; } auto len = p - begin; // JSON arrays don't permit leading 0's in numbers. if (UNLIKELY(len > 1 && firstChar == '0' && array_elem)) { return false; } // Now 'x' is the usigned absolute value of a naively parsed integer, but // potentially overflowed mod 2^64. if (LIKELY(len < 19) || (len == 19 && firstChar <= '8')) { int64_t sx = x; pushInt64(neg ? -sx : sx); } else { parseBigInt(len); } return true; } /* * Assuming 'len' characters ('0'-'9', maybe prefix '-') have been read, * re-parse and push as an int64_t if possible, otherwise as a double. */ void parseBigInt(int len) { assertx(*p > '9' || *p < '0'); // Aleady read maximal digit sequence. errno = 0; const int64_t sx = strtoll(p - len, nullptr, 10); if (errno == ERANGE) { const double dval = zend_strtod(p - len, nullptr); assertx(dval == floor(dval)); pushDouble(dval); } else { pushInt64(sx); } } void pushDouble(double data) { auto const tv = top++; tv->m_type = KindOfDouble; tv->m_data.dbl = data; } void pushInt64(int64_t data) { auto const tv = top++; tv->m_type = KindOfInt64; tv->m_data.num = data; } void pushStringData(StringData* data) { auto const tv = top++; tv->m_type = KindOfString; tv->m_data.pstr = data; } void pushArrayData(ArrayData* data) { auto const tv = top++; tv->m_type = data->toDataType(); tv->m_data.parr = data; assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } const char* p; TypedValue* top; int array_depth; JSONContainerType container_type; bool is_tsimplejson; }; /* * String buffer wrapper that does NOT check its capacity in release mode. User * supplies the allocation and must ensure to never append past the end. */ struct UncheckedBuffer { void clear() { p = begin; } // Use given buffer with space for 'cap' chars, including '\0'. void setBuf(char* buf, size_t cap) { begin = p = buf; #ifndef NDEBUG end = begin + cap; #endif } void append(char c) { assertx(p < end); *p++ = c; } void shrinkBy(int decrease) { p -= decrease; assertx(p >= begin); } int size() { return p - begin; } // NUL-terminates the output before returning it, for backward-compatibility. char* data() { assertx(p < end); *p = 0; return begin; } String copy() { return String(data(), size(), CopyString); } char* p{nullptr}; char* begin{nullptr}; #ifndef NDEBUG char* end{nullptr}; #endif }; } /** * A stack maintains the states of nested structures. */ struct json_parser { struct json_state { Mode mode; String key; Variant val; }; folly::fbvector<json_state> stack; // check_non_safepoint_surprise() above will not trigger gc TYPE_SCAN_IGNORE_FIELD(stack); int top; int mark; // the watermark int depth; json_error_codes error_code; // Thread-local buffer; reused on each call. JSON parsing cannot lead to code // execution and is not re-entrant. SimpleParser assumes no surprise checks. union { TypedValue* tv{nullptr}; // SimpleParser's stack. char* raw; // sb_buf/key } tl_buffer; TYPE_SCAN_IGNORE_FIELD(tv); UncheckedBuffer sb_buf; UncheckedBuffer sb_key; int sb_cap{0}; // Capacity of each of sb_buf/key. void initSb(int length) { if (UNLIKELY(length >= sb_cap)) { // No decoded string in the output can use more bytes than input size. const auto new_cap = length + 1; size_t bufSize = length <= RuntimeOption::EvalSimpleJsonMaxLength ? SimpleParser::BufferBytesForLength(length) : new_cap * 2; if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; if (!tl_heap->preAllocOOM(bufSize)) { tl_buffer.raw = (char*)json_malloc(bufSize); if (!tl_buffer.raw) tl_heap->forceOOM(); } check_non_safepoint_surprise(); always_assert(tl_buffer.raw); sb_buf.setBuf(tl_buffer.raw, new_cap); sb_key.setBuf(tl_buffer.raw + new_cap, new_cap); // Set new capacity if and ony if allocations succeed. sb_cap = new_cap; } else { sb_buf.clear(); sb_key.clear(); } } void flushSb() { if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; sb_buf.setBuf(nullptr, 0); sb_key.setBuf(nullptr, 0); } private: static void* json_malloc(size_t size) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_malloc(size); } else { return malloc(size); } } static void json_free(void* ptr) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_free(ptr); } else { return free(ptr); } } }; RDS_LOCAL(json_parser, s_json_parser); // In Zend, the json_parser struct is publicly // accessible. Thus the fields could be accessed // directly. Just using setter/accessor functions // to get around that. json_error_codes json_get_last_error_code() { return s_json_parser->error_code; } void json_set_last_error_code(json_error_codes ec) { s_json_parser->error_code = ec; } const char *json_get_last_error_msg() { switch (s_json_parser->error_code) { case JSON_ERROR_NONE: return "No error"; case JSON_ERROR_DEPTH: return "Maximum stack depth exceeded"; case JSON_ERROR_STATE_MISMATCH: return "State mismatch (invalid or malformed JSON)"; case JSON_ERROR_CTRL_CHAR: return "Control character error, possibly incorrectly encoded"; case JSON_ERROR_SYNTAX: return "Syntax error"; case JSON_ERROR_UTF8: return "Malformed UTF-8 characters, possibly incorrectly encoded"; case json_error_codes::JSON_ERROR_RECURSION: return "Recursion detected"; case json_error_codes::JSON_ERROR_INF_OR_NAN: return "Inf and NaN cannot be JSON encoded"; case json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE: return "Type is not supported"; default: return "Unknown error"; } } // For each request, make sure we start with the default error code. void json_parser_init() { s_json_parser->error_code = JSON_ERROR_NONE; } void json_parser_flush_caches() { s_json_parser->flushSb(); } /** * Push a mode onto the stack. Return false if there is overflow. */ static int push(json_parser *json, Mode mode) { if (json->top + 1 >= json->depth) { return false; } json->top += 1; json->stack[json->top].mode = mode; if (json->top > json->mark) { json->mark = json->top; } return true; } /** * Pop the stack, assuring that the current mode matches the expectation. * Return false if there is underflow or if the modes mismatch. */ static int pop(json_parser *json, Mode mode) { if (json->top < 0 || json->stack[json->top].mode != mode) { return false; } json->stack[json->top].mode = Mode::INVALID; json->top -= 1; return true; } static String copy_and_clear(UncheckedBuffer &buf) { auto ret = buf.size() > 0 ? buf.copy() : empty_string(); buf.clear(); return ret; } static Variant to_double(UncheckedBuffer &buf) { auto data = buf.data(); auto ret = data ? zend_strtod(data, nullptr) : 0.0; buf.clear(); return ret; } static void json_create_zval(Variant &z, UncheckedBuffer &buf, DataType type, int64_t options) { switch (type) { case KindOfBoolean: z = (buf.data() && (*buf.data() == 't')); return; case KindOfInt64: { bool bigint = false; const char *p = buf.data(); assertx(p); if (p == NULL) { z = int64_t(0); return; } bool neg = *buf.data() == '-'; int len = buf.size(); if (neg) len--; if (len >= MAX_LENGTH_OF_LONG - 1) { if (len == MAX_LENGTH_OF_LONG - 1) { int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits); if (!(cmp < 0 || (cmp == 0 && neg))) { bigint = true; } } else { bigint = true; } } if (bigint) { if (!(options & k_JSON_BIGINT_AS_STRING)) { // See KindOfDouble (below) z = to_double(buf); } else { z = copy_and_clear(buf); } } else { z = fast_strtoll_base10(buf.data()); } return; } case KindOfDouble: // Use zend_strtod() instead of strtod() here since JSON specifies using // a '.' for decimal separators regardless of locale. z = to_double(buf); return; case KindOfString: z = copy_and_clear(buf); return; case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfPersistentArray: case KindOfArray: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfObject: case KindOfResource: case KindOfFunc: case KindOfClass: case KindOfClsMeth: case KindOfRecord: z = uninit_null(); return; } not_reached(); } NEVER_INLINE void utf16_to_utf8_tail(UncheckedBuffer &buf, unsigned short utf16) { if (utf16 < 0x800) { buf.append((char)(0xc0 | (utf16 >> 6))); buf.append((char)(0x80 | (utf16 & 0x3f))); } else if ((utf16 & 0xfc00) == 0xdc00 && buf.size() >= 3 && ((unsigned char)buf.data()[buf.size() - 3]) == 0xed && ((unsigned char)buf.data()[buf.size() - 2] & 0xf0) == 0xa0 && ((unsigned char)buf.data()[buf.size() - 1] & 0xc0) == 0x80) { /* found surrogate pair */ unsigned long utf32; utf32 = (((buf.data()[buf.size() - 2] & 0xf) << 16) | ((buf.data()[buf.size() - 1] & 0x3f) << 10) | (utf16 & 0x3ff)) + 0x10000; buf.shrinkBy(3); buf.append((char)(0xf0 | (utf32 >> 18))); buf.append((char)(0x80 | ((utf32 >> 12) & 0x3f))); buf.append((char)(0x80 | ((utf32 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf32 & 0x3f))); } else { buf.append((char)(0xe0 | (utf16 >> 12))); buf.append((char)(0x80 | ((utf16 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf16 & 0x3f))); } } ALWAYS_INLINE void utf16_to_utf8(UncheckedBuffer &buf, unsigned short utf16) { if (LIKELY(utf16 < 0x80)) { buf.append((char)utf16); return; } return utf16_to_utf8_tail(buf, utf16); } StaticString s__empty_("_empty_"); static void object_set(const json_parser* json, Variant &var, const String& key, const Variant& value, int assoc, JSONContainerType container_type) { if (!assoc) { // We know it is stdClass, and everything is public (and dynamic). if (key.empty()) { var.getObjectData()->setProp(nullptr, s__empty_.get(), *value.asTypedValue()); } else { var.getObjectData()->o_set(key, value); } } else { if (container_type == JSONContainerType::COLLECTIONS) { auto keyTV = make_tv<KindOfString>(key.get()); collections::set(var.getObjectData(), &keyTV, value.asTypedValue()); } else if (container_type == JSONContainerType::HACK_ARRAYS || container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { forceToDict(var).set(key, value); } else { int64_t i; if (key.get()->isStrictlyInteger(i)) { forceToDArray(var).set(i, value); } else { forceToDArray(var).set(key, value); } } if (var.isArray()) { DEBUG_ONLY auto const data = var.getArrayData(); assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } } } static void attach_zval(json_parser *json, const String& key, int assoc, JSONContainerType container_type) { if (json->top < 1) { return; } auto& root = json->stack[json->top - 1].val; auto& child = json->stack[json->top].val; auto up_mode = json->stack[json->top - 1].mode; if (up_mode == Mode::ARRAY) { if (container_type == JSONContainerType::COLLECTIONS) { collections::append(root.getObjectData(), child.asTypedValue()); } else { root.asArrRef().append(child); } } else if (up_mode == Mode::OBJECT) { object_set(json, root, key, child, assoc, container_type); } } JSONContainerType get_container_type_from_options(int64_t options) { if ((options & k_JSON_FB_STABLE_MAPS) || (options & k_JSON_FB_COLLECTIONS)) { return JSONContainerType::COLLECTIONS; } if (options & k_JSON_FB_HACK_ARRAYS) { return JSONContainerType::HACK_ARRAYS; } if (options & k_JSON_FB_DARRAYS) { return JSONContainerType::DARRAYS; } if (options & k_JSON_FB_DARRAYS_AND_VARRAYS) { return JSONContainerType::DARRAYS_AND_VARRAYS; } if (options & k_JSON_FB_LEGACY_HACK_ARRAYS) { return JSONContainerType::LEGACY_HACK_ARRAYS; } return JSONContainerType::DARRAYS; } /** * The JSON_parser takes a UTF-8 encoded string and determines if it is a * syntactically correct JSON text. Along the way, it creates a PHP variable. * * It is implemented as a Pushdown Automaton; that means it is a finite state * machine with a stack. * * The behavior is as follows: * Container Type | is_assoc | JSON input => output type * * COLLECTIONS | true | "{}" => c_Map * COLLECTIONS | false | "{}" => c_Map * COLLECTIONS | true | "[]" => c_Vector * COLLECTIONS | false | "[]" => c_Vector * * HACK_ARRAYS | true | "{}" => dict * HACK_ARRAYS | false | "{}" => stdClass * HACK_ARRAYS | true | "[]" => vec * HACK_ARRAYS | false | "[]" => stdClass * * DARRAYS | true | "{}" => darray * DARRAYS | false | "{}" => stdClass * DARRAYS | true | "[]" => darray * DARRAYS | false | "[]" => stdClass * * DARRAYS_AND_VARRAYS | true | "{}" => darray * DARRAYS_AND_VARRAYS | false | "{}" => stdClass * DARRAYS_AND_VARRAYS | true | "[]" => varray * DARRAYS_AND_VARRAYS | false | "[]" => stdClass */ bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } #endif /* HAVE_JSONC */
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_4251_0
crossvul-cpp_data_bad_65_0
/* * Snd_fx.cpp * ----------- * Purpose: Processing of pattern commands, song length calculation... * Notes : This needs some heavy refactoring. * I thought of actually adding an effect interface class. Every pattern effect * could then be moved into its own class that inherits from the effect interface. * If effect handling differs severly between module formats, every format would have * its own class for that effect. Then, a call chain of effect classes could be set up * for each format, since effects cannot be processed in the same order in all formats. * Authors: Olivier Lapicque * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "Sndfile.h" #include "mod_specifications.h" #ifdef MODPLUG_TRACKER #include "../mptrack/Moddoc.h" #endif // MODPLUG_TRACKER #include "tuning.h" #include "Tables.h" #include "modsmp_ctrl.h" // For updating the loop wraparound data with the invert loop effect #include "plugins/PlugInterface.h" OPENMPT_NAMESPACE_BEGIN // Formats which have 7-bit (0...128) instead of 6-bit (0...64) global volume commands, or which are imported to this range (mostly formats which are converted to IT internally) #ifdef MODPLUG_TRACKER #define GLOBALVOL_7BIT_FORMATS_EXT (MOD_TYPE_MT2) #else #define GLOBALVOL_7BIT_FORMATS_EXT Enum<MODTYPE>::value_type() #endif // MODPLUG_TRACKER #define GLOBALVOL_7BIT_FORMATS (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM | MOD_TYPE_PTM | MOD_TYPE_MDL | MOD_TYPE_DTM | GLOBALVOL_7BIT_FORMATS_EXT) // Compensate frequency slide LUTs depending on whether we are handling periods or frequency - "up" and "down" in function name are seen from frequency perspective. static uint32 GetLinearSlideDownTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(LinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? LinearSlideDownTable[i] : LinearSlideUpTable[i]; } static uint32 GetLinearSlideUpTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(LinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? LinearSlideUpTable[i] : LinearSlideDownTable[i]; } static uint32 GetFineLinearSlideDownTable(const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(FineLinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? FineLinearSlideDownTable[i] : FineLinearSlideUpTable[i]; } static uint32 GetFineLinearSlideUpTable (const CSoundFile *sndFile, uint32 i) { MPT_ASSERT(i < CountOf(FineLinearSlideDownTable)); return sndFile->m_playBehaviour[kHertzInLinearMode] ? FineLinearSlideUpTable[i] : FineLinearSlideDownTable[i]; } //////////////////////////////////////////////////////////// // Length // Memory class for GetLength() code class GetLengthMemory { protected: const CSoundFile &sndFile; public: std::unique_ptr<CSoundFile::PlayState> state; struct ChnSettings { double patLoop = 0.0; CSoundFile::samplecount_t patLoopSmp = 0; ROWINDEX patLoopStart = 0; uint32 ticksToRender = 0; // When using sample sync, we still need to render this many ticks bool incChanged = false; // When using sample sync, note frequency has changed uint8 vol = 0xFF; }; #ifndef NO_PLUGINS typedef std::map<std::pair<ModCommand::INSTR, uint16>, uint16> PlugParamMap; PlugParamMap plugParams; #endif std::vector<ChnSettings> chnSettings; double elapsedTime; static const uint32 IGNORE_CHANNEL = uint32_max; GetLengthMemory(const CSoundFile &sf) : sndFile(sf) , state(mpt::make_unique<CSoundFile::PlayState>(sf.m_PlayState)) { Reset(); } void Reset() { plugParams.clear(); elapsedTime = 0.0; state->m_lTotalSampleCount = 0; state->m_nMusicSpeed = sndFile.m_nDefaultSpeed; state->m_nMusicTempo = sndFile.m_nDefaultTempo; state->m_nGlobalVolume = sndFile.m_nDefaultGlobalVolume; chnSettings.assign(sndFile.GetNumChannels(), ChnSettings()); for(CHANNELINDEX chn = 0; chn < sndFile.GetNumChannels(); chn++) { state->Chn[chn].Reset(ModChannel::resetTotal, sndFile, chn); state->Chn[chn].nOldGlobalVolSlide = 0; state->Chn[chn].nOldChnVolSlide = 0; state->Chn[chn].nNote = state->Chn[chn].nNewNote = state->Chn[chn].nLastNote = NOTE_NONE; } } // Increment playback position of sample and envelopes on a channel void RenderChannel(CHANNELINDEX channel, uint32 tickDuration, uint32 portaStart = uint32_max) { ModChannel &chn = state->Chn[channel]; uint32 numTicks = chnSettings[channel].ticksToRender; if(numTicks == IGNORE_CHANNEL || numTicks == 0 || (!chn.IsSamplePlaying() && !chnSettings[channel].incChanged) || chn.pModSample == nullptr) { return; } const SmpLength sampleEnd = chn.dwFlags[CHN_LOOP] ? chn.nLoopEnd : chn.nLength; const SmpLength loopLength = chn.nLoopEnd - chn.nLoopStart; const bool itEnvMode = sndFile.m_playBehaviour[kITEnvelopePositionHandling]; const bool updatePitchEnv = (chn.PitchEnv.flags & (ENV_ENABLED | ENV_FILTER)) == ENV_ENABLED; bool stopNote = false; SamplePosition inc = chn.increment * tickDuration; if(chn.dwFlags[CHN_PINGPONGFLAG]) inc.Negate(); for(uint32 i = 0; i < numTicks; i++) { bool updateInc = (chn.PitchEnv.flags & (ENV_ENABLED | ENV_FILTER)) == ENV_ENABLED; if(i >= portaStart) { chn.isFirstTick = false; const ModCommand &p = *sndFile.Patterns[state->m_nPattern].GetpModCommand(state->m_nRow, channel); if(p.command == CMD_TONEPORTAMENTO) sndFile.TonePortamento(&chn, p.param); else if(p.command == CMD_TONEPORTAVOL) sndFile.TonePortamento(&chn, 0); if(p.volcmd == VOLCMD_TONEPORTAMENTO) { uint32 param = p.vol; if(sndFile.GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DMF | MOD_TYPE_DBM | MOD_TYPE_IMF | MOD_TYPE_PSM | MOD_TYPE_J2B | MOD_TYPE_ULT | MOD_TYPE_OKT | MOD_TYPE_MT2 | MOD_TYPE_MDL)) { param = ImpulseTrackerPortaVolCmd[param & 0x0F]; } else { // Close enough. Do not bother with idiosyncratic FT2 behaviour here. param <<= 4; } sndFile.TonePortamento(&chn, param); } updateInc = true; } int period = chn.nPeriod; if(itEnvMode) sndFile.IncrementEnvelopePositions(&chn); if(updatePitchEnv) { sndFile.ProcessPitchFilterEnvelope(&chn, period); updateInc = true; } if(!itEnvMode) sndFile.IncrementEnvelopePositions(&chn); int vol = 0; sndFile.ProcessInstrumentFade(&chn, vol); if(updateInc || chnSettings[channel].incChanged) { chn.increment = sndFile.GetChannelIncrement(&chn, period, 0); chnSettings[channel].incChanged = false; inc = chn.increment * tickDuration; if(chn.dwFlags[CHN_PINGPONGFLAG]) inc.Negate(); } chn.position += inc; if(chn.position.GetUInt() >= sampleEnd) { if(chn.dwFlags[CHN_LOOP]) { // We exceeded the sample loop, go back to loop start. if(chn.dwFlags[CHN_PINGPONGLOOP]) { if(chn.position < SamplePosition(chn.nLoopStart, 0)) { chn.position = SamplePosition(chn.nLoopStart + chn.nLoopStart, 0) - chn.position; chn.dwFlags.flip(CHN_PINGPONGFLAG); inc.Negate(); } SmpLength posInt = chn.position.GetUInt() - chn.nLoopStart; SmpLength pingpongLength = loopLength * 2; if(sndFile.m_playBehaviour[kITPingPongMode]) pingpongLength--; posInt %= pingpongLength; bool forward = (posInt < loopLength); if(forward) chn.position.SetInt(chn.nLoopStart + posInt); else chn.position.SetInt(chn.nLoopEnd - (posInt - loopLength)); if(forward == chn.dwFlags[CHN_PINGPONGFLAG]) { chn.dwFlags.flip(CHN_PINGPONGFLAG); inc.Negate(); } } else { SmpLength posInt = chn.position.GetUInt(); if(posInt >= chn.nLoopEnd + loopLength) { const SmpLength overshoot = posInt - chn.nLoopEnd; posInt -= (overshoot / loopLength) * loopLength; } while(posInt >= chn.nLoopEnd) { posInt -= loopLength; } chn.position.SetInt(posInt); } } else { // Past sample end. stopNote = true; break; } } } if(stopNote) { chn.Stop(); chn.nPortamentoDest = 0; } chnSettings[channel].ticksToRender = 0; } }; // Get mod length in various cases. Parameters: // [in] adjustMode: See enmGetLengthResetMode for possible adjust modes. // [in] target: Time or position target which should be reached, or no target to get length of the first sub song. Use GetLengthTarget::StartPos to also specify a position from where the seeking should begin. // [out] See definition of type GetLengthType for the returned values. std::vector<GetLengthType> CSoundFile::GetLength(enmGetLengthResetMode adjustMode, GetLengthTarget target) { std::vector<GetLengthType> results; GetLengthType retval; retval.startOrder = target.startOrder; retval.startRow = target.startRow; // Are we trying to reach a certain pattern position? const bool hasSearchTarget = target.mode != GetLengthTarget::NoTarget; const bool adjustSamplePos = (adjustMode & eAdjustSamplePositions) == eAdjustSamplePositions; SEQUENCEINDEX sequence = target.sequence; if(sequence >= Order.GetNumSequences()) sequence = Order.GetCurrentSequenceIndex(); const ModSequence &orderList = Order(sequence); GetLengthMemory memory(*this); CSoundFile::PlayState &playState = *memory.state; // Temporary visited rows vector (so that GetLength() won't interfere with the player code if the module is playing at the same time) RowVisitor visitedRows(*this, sequence); playState.m_nNextRow = playState.m_nRow = target.startRow; playState.m_nNextOrder = playState.m_nCurrentOrder = target.startOrder; // Fast LUTs for commands that are too weird / complicated / whatever to emulate in sample position adjust mode. std::bitset<MAX_EFFECTS> forbiddenCommands; std::bitset<MAX_VOLCMDS> forbiddenVolCommands; if(adjustSamplePos) { forbiddenCommands.set(CMD_ARPEGGIO); forbiddenCommands.set(CMD_PORTAMENTOUP); forbiddenCommands.set(CMD_PORTAMENTODOWN); forbiddenCommands.set(CMD_XFINEPORTAUPDOWN); forbiddenCommands.set(CMD_NOTESLIDEUP); forbiddenCommands.set(CMD_NOTESLIDEUPRETRIG); forbiddenCommands.set(CMD_NOTESLIDEDOWN); forbiddenCommands.set(CMD_NOTESLIDEDOWNRETRIG); forbiddenVolCommands.set(VOLCMD_PORTAUP); forbiddenVolCommands.set(VOLCMD_PORTADOWN); // Optimize away channels for which it's pointless to adjust sample positions for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { if(ChnSettings[i].dwFlags[CHN_MUTE]) memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } if(target.mode == GetLengthTarget::SeekPosition && target.pos.order < orderList.size()) { // If we know where to seek, we can directly rule out any channels on which a new note would be triggered right at the start. const PATTERNINDEX seekPat = orderList[target.pos.order]; if(Patterns.IsValidPat(seekPat) && Patterns[seekPat].IsValidRow(target.pos.row)) { const ModCommand *m = Patterns[seekPat].GetRow(target.pos.row); for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, m++) { if(m->note == NOTE_NOTECUT || m->note == NOTE_KEYOFF || (m->note == NOTE_FADE && GetNumInstruments()) || (m->IsNote() && !m->IsPortamento())) { memory.chnSettings[i].ticksToRender = GetLengthMemory::IGNORE_CHANNEL; } } } } } // If samples are being synced, force them to resync if tick duration changes uint32 oldTickDuration = 0; for (;;) { // Time target reached. if(target.mode == GetLengthTarget::SeekSeconds && memory.elapsedTime >= target.time) { retval.targetReached = true; break; } uint32 rowDelay = 0, tickDelay = 0; playState.m_nRow = playState.m_nNextRow; playState.m_nCurrentOrder = playState.m_nNextOrder; if(orderList.IsValidPat(playState.m_nCurrentOrder) && playState.m_nRow >= Patterns[orderList[playState.m_nCurrentOrder]].GetNumRows()) { playState.m_nRow = 0; if(m_playBehaviour[kFT2LoopE60Restart]) { playState.m_nRow = playState.m_nNextPatStartRow; playState.m_nNextPatStartRow = 0; } playState.m_nCurrentOrder = ++playState.m_nNextOrder; } // Check if pattern is valid playState.m_nPattern = playState.m_nCurrentOrder < orderList.size() ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); bool positionJumpOnThisRow = false; bool patternBreakOnThisRow = false; bool patternLoopEndedOnThisRow = false, patternLoopStartedOnThisRow = false; if(!Patterns.IsValidPat(playState.m_nPattern) && playState.m_nPattern != orderList.GetInvalidPatIndex() && target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order) { // Early test: Target is inside +++ or non-existing pattern retval.targetReached = true; break; } while(playState.m_nPattern >= Patterns.Size()) { // End of song? if((playState.m_nPattern == orderList.GetInvalidPatIndex()) || (playState.m_nCurrentOrder >= orderList.size())) { if(playState.m_nCurrentOrder == orderList.GetRestartPos()) break; else playState.m_nCurrentOrder = orderList.GetRestartPos(); } else { playState.m_nCurrentOrder++; } playState.m_nPattern = (playState.m_nCurrentOrder < orderList.size()) ? orderList[playState.m_nCurrentOrder] : orderList.GetInvalidPatIndex(); playState.m_nNextOrder = playState.m_nCurrentOrder; if((!Patterns.IsValidPat(playState.m_nPattern)) && visitedRows.IsVisited(playState.m_nCurrentOrder, 0, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nCurrentOrder = playState.m_nNextOrder; playState.m_nPattern = orderList[playState.m_nCurrentOrder]; playState.m_nNextRow = playState.m_nRow; break; } } } if(playState.m_nNextOrder == ORDERINDEX_INVALID) { // GetFirstUnvisitedRow failed, so there is nothing more to play break; } // Skip non-existing patterns if(!Patterns.IsValidPat(playState.m_nPattern)) { // If there isn't even a tune, we should probably stop here. if(playState.m_nCurrentOrder == orderList.GetRestartPos()) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } playState.m_nNextOrder = playState.m_nCurrentOrder + 1; continue; } // Should never happen if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) playState.m_nRow = 0; // Check whether target was reached. if(target.mode == GetLengthTarget::SeekPosition && playState.m_nCurrentOrder == target.pos.order && playState.m_nRow == target.pos.row) { retval.targetReached = true; break; } if(visitedRows.IsVisited(playState.m_nCurrentOrder, playState.m_nRow, true)) { if(!hasSearchTarget || !visitedRows.GetFirstUnvisitedRow(playState.m_nNextOrder, playState.m_nRow, true)) { // We aren't searching for a specific row, or we couldn't find any more unvisited rows. break; } else { // We haven't found the target row yet, but we found some other unplayed row... continue searching from here. retval.duration = memory.elapsedTime; results.push_back(retval); retval.startRow = playState.m_nRow; retval.startOrder = playState.m_nNextOrder; memory.Reset(); playState.m_nNextRow = playState.m_nRow; continue; } } retval.endOrder = playState.m_nCurrentOrder; retval.endRow = playState.m_nRow; // Update next position playState.m_nNextRow = playState.m_nRow + 1; // Jumped to invalid pattern row? if(playState.m_nRow >= Patterns[playState.m_nPattern].GetNumRows()) { playState.m_nRow = 0; } // New pattern? if(!playState.m_nRow) { for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { memory.chnSettings[chn].patLoop = memory.elapsedTime; memory.chnSettings[chn].patLoopSmp = playState.m_lTotalSampleCount; } } ModChannel *pChn = playState.Chn; // For various effects, we need to know first how many ticks there are in this row. const ModCommand *p = Patterns[playState.m_nPattern].GetpModCommand(playState.m_nRow, 0); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, p++) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; if(p->IsPcNote()) { #ifndef NO_PLUGINS if((adjustMode & eAdjust) && p->instr > 0 && p->instr <= MAX_MIXPLUGINS) { memory.plugParams[std::make_pair(p->instr, p->GetValueVolCol())] = p->GetValueEffectCol(); } #endif // NO_PLUGINS pChn[nChn].rowCommand.Clear(); continue; } pChn[nChn].rowCommand = *p; switch(p->command) { case CMD_SPEED: SetSpeed(playState, p->param); break; case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(p->param != 0) SetSpeed(playState, p->param); } break; case CMD_S3MCMDEX: if((p->param & 0xF0) == 0x60) { // Fine Pattern Delay tickDelay += (p->param & 0x0F); } else if((p->param & 0xF0) == 0xE0 && !rowDelay) { // Pattern Delay if(!(GetType() & MOD_TYPE_S3M) || (p->param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. rowDelay = 1 + (p->param & 0x0F); } } break; case CMD_MODCMDEX: if((p->param & 0xF0) == 0xE0) { // Pattern Delay rowDelay = 1 + (p->param & 0x0F); } break; } } if(rowDelay == 0) rowDelay = 1; const uint32 numTicks = (playState.m_nMusicSpeed + tickDelay) * rowDelay; const uint32 nonRowTicks = numTicks - rowDelay; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) if(!pChn->rowCommand.IsEmpty()) { if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; ModCommand::NOTE note = pChn->rowCommand.note; if (pChn->rowCommand.instr) { pChn->nNewIns = pChn->rowCommand.instr; pChn->nLastNote = NOTE_NONE; memory.chnSettings[nChn].vol = 0xFF; } if (pChn->rowCommand.IsNote()) pChn->nLastNote = note; // Update channel panning if(pChn->rowCommand.IsNote() || pChn->rowCommand.instr) { SAMPLEINDEX smp = 0; if(GetNumInstruments()) { ModInstrument *pIns; if(pChn->nNewIns <= GetNumInstruments() && (pIns = Instruments[pChn->nNewIns]) != nullptr) { if(pIns->dwFlags[INS_SETPANNING]) pChn->nPan = pIns->nPan; if(ModCommand::IsNote(note)) smp = pIns->Keyboard[note - NOTE_MIN]; } } else { smp = pChn->nNewIns; } if(smp > 0 && smp <= GetNumSamples() && Samples[smp].uFlags[CHN_PANNING]) { pChn->nPan = Samples[smp].nPan; } } switch(pChn->rowCommand.volcmd) { case VOLCMD_VOLUME: memory.chnSettings[nChn].vol = pChn->rowCommand.vol; break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: if(pChn->rowCommand.vol != 0) pChn->nOldVolParam = pChn->rowCommand.vol; break; } switch(command) { // Position Jump case CMD_POSITIONJUMP: positionJumpOnThisRow = true; playState.m_nNextOrder = static_cast<ORDERINDEX>(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn)); playState.m_nNextPatStartRow = 0; // FT2 E60 bug // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if(!patternBreakOnThisRow || (GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) playState.m_nNextRow = 0; if (adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(playState, nChn, param); if(row != ROWINDEX_INVALID) { patternBreakOnThisRow = true; playState.m_nNextRow = row; if(!positionJumpOnThisRow) { playState.m_nNextOrder = playState.m_nCurrentOrder + 1; } if(adjustMode & eAdjust) { pChn->nPatternLoopCount = 0; pChn->nPatternLoop = 0; } } } break; // Set Tempo case CMD_TEMPO: if(!m_playBehaviour[kMODVBlankTiming]) { TEMPO tempo(CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn), 0); if ((adjustMode & eAdjust) && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { if (tempo.GetInt()) pChn->nOldTempo = static_cast<uint8>(tempo.GetInt()); else tempo.Set(pChn->nOldTempo); } if (tempo.GetInt() >= 0x20) playState.m_nMusicTempo = tempo; else { // Tempo Slide TEMPO tempoDiff((tempo.GetInt() & 0x0F) * nonRowTicks, 0); if ((tempo.GetInt() & 0xF0) == 0x10) { playState.m_nMusicTempo += tempoDiff; } else { if(tempoDiff < playState.m_nMusicTempo) playState.m_nMusicTempo -= tempoDiff; else playState.m_nMusicTempo.Set(0); } } TEMPO tempoMin = GetModSpecifications().GetTempoMin(), tempoMax = GetModSpecifications().GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(playState.m_nMusicTempo, tempoMin, tempoMax); } break; case CMD_S3MCMDEX: switch(param & 0xF0) { case 0x90: if(param <= 0x91) { pChn->dwFlags.set(CHN_SURROUND, param == 0x91); } break; case 0xA0: // High sample offset pChn->nOldHiOffset = param & 0x0F; break; case 0xB0: // Pattern Loop if (param & 0x0F) { patternLoopEndedOnThisRow = true; } else { CHANNELINDEX firstChn = nChn, lastChn = nChn; if(GetType() == MOD_TYPE_S3M) { // ST3 has only one global loop memory. firstChn = 0; lastChn = GetNumChannels() - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { memory.chnSettings[c].patLoop = memory.elapsedTime; memory.chnSettings[c].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[c].patLoopStart = playState.m_nRow; } patternLoopStartedOnThisRow = true; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_MODCMDEX: switch(param & 0xF0) { case 0x60: // Pattern Loop if (param & 0x0F) { playState.m_nNextPatStartRow = memory.chnSettings[nChn].patLoopStart; // FT2 E60 bug patternLoopEndedOnThisRow = true; } else { patternLoopStartedOnThisRow = true; memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow; } break; case 0xF0: // Active macro pChn->nActiveMacro = param & 0x0F; break; } break; case CMD_XFINEPORTAUPDOWN: // ignore high offset in compatible mode if(((param & 0xF0) == 0xA0) && !m_playBehaviour[kFT2RestrictXCommand]) pChn->nOldHiOffset = param & 0x0F; break; } // The following calculations are not interesting if we just want to get the song length. if (!(adjustMode & eAdjust)) continue; switch(command) { // Portamento Up/Down case CMD_PORTAMENTOUP: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } break; case CMD_PORTAMENTODOWN: if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } break; // Tone-Portamento case CMD_TONEPORTAMENTO: if (param) pChn->nPortamentoSlide = param << 2; break; // Offset case CMD_OFFSET: if (param) pChn->oldOffset = param << 8; break; // Volume Slide case CMD_VOLUMESLIDE: case CMD_TONEPORTAVOL: if (param) pChn->nOldVolumeSlide = param; break; // Set Volume case CMD_VOLUME: memory.chnSettings[nChn].vol = param; break; // Global Volume case CMD_GLOBALVOLUME: if(!(GetType() & GLOBALVOL_7BIT_FORMATS) && param < 128) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values if(param <= 128) { playState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { playState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: if(m_playBehaviour[kPerChannelGlobalVolSlide]) { // IT compatibility 16. Global volume slide params are stored per channel (FT2/IT) if (param) pChn->nOldGlobalVolSlide = param; else param = pChn->nOldGlobalVolSlide; } else { if (param) playState.Chn[0].nOldGlobalVolSlide = param; else param = playState.Chn[0].nOldGlobalVolSlide; } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { param >>= 4; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param << 1; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param; } else if (param & 0xF0) { param >>= 4; param <<= 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume += param * nonRowTicks; } else { param = (param & 0x0F) << 1; if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param <<= 1; playState.m_nGlobalVolume -= param * nonRowTicks; } Limit(playState.m_nGlobalVolume, 0, 256); break; case CMD_CHANNELVOLUME: if (param <= 64) pChn->nGlobalVol = param; break; case CMD_CHANNELVOLSLIDE: { if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; int32 volume = pChn->nGlobalVol; if((param & 0x0F) == 0x0F && (param & 0xF0)) volume += (param >> 4); // Fine Up else if((param & 0xF0) == 0xF0 && (param & 0x0F)) volume -= (param & 0x0F); // Fine Down else if(param & 0x0F) // Down volume -= (param & 0x0F) * nonRowTicks; else // Up volume += ((param & 0xF0) >> 4) * nonRowTicks; Limit(volume, 0, 64); pChn->nGlobalVol = volume; } break; case CMD_PANNING8: Panning(pChn, param, Pan8bit); break; case CMD_MODCMDEX: if(param < 0x10) { // LED filter for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { playState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } } MPT_FALLTHROUGH; case CMD_S3MCMDEX: if((param & 0xF0) == 0x80) { Panning(pChn, (param & 0x0F), Pan4bit); } break; case CMD_VIBRATOVOL: if (param) pChn->nOldVolumeSlide = param; param = 0; MPT_FALLTHROUGH; case CMD_VIBRATO: Vibrato(pChn, param); break; case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; case CMD_TREMOLO: Tremolo(pChn, param); break; case CMD_PANBRELLO: Panbrello(pChn, param); break; } switch(pChn->rowCommand.volcmd) { case VOLCMD_PANNING: Panning(pChn, pChn->rowCommand.vol, Pan6bit); break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the "set vibrato speed" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = pChn->rowCommand.vol & 0x0F; else Vibrato(pChn, pChn->rowCommand.vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, pChn->rowCommand.vol); break; } // Process vibrato / tremolo / panbrello switch(pChn->rowCommand.command) { case CMD_VIBRATO: case CMD_FINEVIBRATO: case CMD_VIBRATOVOL: if(adjustMode & eAdjust) { uint32 vibTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nVibratoSpeed * vibTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nVibratoPos += static_cast<uint8>(inc); } break; case CMD_TREMOLO: if(adjustMode & eAdjust) { uint32 tremTicks = ((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) ? numTicks : nonRowTicks; uint32 inc = pChn->nTremoloSpeed * tremTicks; if(m_playBehaviour[kITVibratoTremoloPanbrello]) inc *= 4; pChn->nTremoloPos += static_cast<uint8>(inc); } break; case CMD_PANBRELLO: if(adjustMode & eAdjust) { // Panbrello effect is permanent in compatible mode, so actually apply panbrello for the last tick of this row pChn->nPanbrelloPos += static_cast<uint8>(pChn->nPanbrelloSpeed * (numTicks - 1)); ProcessPanbrello(pChn); } break; } } // Interpret F00 effect in XM files as "stop song" if(GetType() == MOD_TYPE_XM && playState.m_nMusicSpeed == uint16_max) { break; } playState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; if(Patterns[playState.m_nPattern].GetOverrideSignature()) { playState.m_nCurrentRowsPerBeat = Patterns[playState.m_nPattern].GetRowsPerBeat(); } const uint32 tickDuration = GetTickDuration(playState); const uint32 rowDuration = tickDuration * numTicks; memory.elapsedTime += static_cast<double>(rowDuration) / static_cast<double>(m_MixerSettings.gdwMixingFreq); playState.m_lTotalSampleCount += rowDuration; if(adjustSamplePos) { // Super experimental and dirty sample seeking pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); pChn++, nChn++) { if(memory.chnSettings[nChn].ticksToRender == GetLengthMemory::IGNORE_CHANNEL) continue; uint32 startTick = 0; const ModCommand &m = pChn->rowCommand; uint32 paramHi = m.param >> 4, paramLo = m.param & 0x0F; bool porta = m.command == CMD_TONEPORTAMENTO || m.command == CMD_TONEPORTAVOL || m.volcmd == VOLCMD_TONEPORTAMENTO; bool stopNote = patternLoopStartedOnThisRow; // It's too much trouble to keep those pattern loops in sync... if(m.instr) pChn->proTrackerOffset = 0; if(m.IsNote()) { if(porta && memory.chnSettings[nChn].incChanged) { // If there's a portamento, the current channel increment mustn't be 0 in NoteChange() pChn->increment = GetChannelIncrement(pChn, pChn->nPeriod, 0); } int32 setPan = pChn->nPan; pChn->nNewNote = pChn->nLastNote; if(pChn->nNewIns != 0) InstrumentChange(pChn, pChn->nNewIns, porta); NoteChange(pChn, m.note, porta); memory.chnSettings[nChn].incChanged = true; if((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xD0 && paramLo < numTicks) { startTick = paramLo; } else if(m.command == CMD_DELAYCUT && paramHi < numTicks) { startTick = paramHi; } if(rowDelay > 1 && startTick != 0 && (GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT))) { startTick += (playState.m_nMusicSpeed + tickDelay) * (rowDelay - 1); } if(!porta) memory.chnSettings[nChn].ticksToRender = 0; // Panning commands have to be re-applied after a note change with potential pan change. if(m.command == CMD_PANNING8 || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && paramHi == 0x8) || m.volcmd == VOLCMD_PANNING) { pChn->nPan = setPan; } if(m.command == CMD_OFFSET) { bool isExtended = false; SmpLength offset = CalculateXParam(playState.m_nPattern, playState.m_nRow, nChn, &isExtended); if(!isExtended) { offset <<= 8; if(offset == 0) offset = pChn->oldOffset; offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } else if(m.command == CMD_OFFSETPERCENTAGE) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, m.param, 255)); } else if(m.command == CMD_REVERSEOFFSET && pChn->pModSample != nullptr) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far ReverseSampleOffset(*pChn, m.param); startTick = playState.m_nMusicSpeed - 1; } else if(m.volcmd == VOLCMD_OFFSET) { if(m.vol <= CountOf(pChn->pModSample->cues) && pChn->pModSample != nullptr) { SmpLength offset; if(m.vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[m.vol - 1]; SampleOffset(*pChn, offset); } } } if(m.note == NOTE_KEYOFF || m.note == NOTE_NOTECUT || (m.note == NOTE_FADE && GetNumInstruments()) || ((m.command == CMD_MODCMDEX || m.command == CMD_S3MCMDEX) && (m.param & 0xF0) == 0xC0 && paramLo < numTicks) || (m.command == CMD_DELAYCUT && paramLo != 0 && startTick + paramLo < numTicks)) { stopNote = true; } if(m.command == CMD_VOLUME) { pChn->nVolume = m.param * 4; } else if(m.volcmd == VOLCMD_VOLUME) { pChn->nVolume = m.vol * 4; } if(pChn->pModSample && !stopNote) { // Check if we don't want to emulate some effect and thus stop processing. if(m.command < MAX_EFFECTS) { if(forbiddenCommands[m.command]) { stopNote = true; } else if(m.command == CMD_MODCMDEX) { // Special case: Slides using extended commands switch(m.param & 0xF0) { case 0x10: case 0x20: stopNote = true; } } } if(m.volcmd < forbiddenVolCommands.size() && forbiddenVolCommands[m.volcmd]) { stopNote = true; } } if(stopNote) { pChn->Stop(); memory.chnSettings[nChn].ticksToRender = 0; } else { if(oldTickDuration != tickDuration && oldTickDuration != 0) { memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far } switch(m.command) { case CMD_TONEPORTAVOL: case CMD_VOLUMESLIDE: case CMD_VIBRATOVOL: if(m.param || (GetType() != MOD_TYPE_MOD)) { for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, m.param); } } break; case CMD_MODCMDEX: if((m.param & 0x0F) || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { pChn->isFirstTick = true; switch(m.param & 0xF0) { case 0xA0: FineVolumeUp(pChn, m.param & 0x0F, false); break; case 0xB0: FineVolumeDown(pChn, m.param & 0x0F, false); break; } } break; case CMD_S3MCMDEX: if(m.param == 0x9E) { // Play forward memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.reset(CHN_PINGPONGFLAG); } else if(m.param == 0x9F) { // Reverse memory.RenderChannel(nChn, oldTickDuration); // Re-sync what we've got so far pChn->dwFlags.set(CHN_PINGPONGFLAG); if(!pChn->position.GetInt() && pChn->nLength && (m.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } } else if((m.param & 0xF0) == 0x70) { // TODO //ExtendedS3MCommands(nChn, param); } break; } pChn->isFirstTick = true; switch(m.volcmd) { case VOLCMD_FINEVOLUP: FineVolumeUp(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_FINEVOLDOWN: FineVolumeDown(pChn, m.vol, m_playBehaviour[kITVolColMemory]); break; case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it ModCommand::VOL vol = m.vol; if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } if(m.volcmd == VOLCMD_VOLSLIDEUP) vol <<= 4; for(uint32 i = 0; i < numTicks; i++) { pChn->isFirstTick = (i == 0); VolumeSlide(pChn, vol); } } break; } if(porta) { // Portamento needs immediate syncing, as the pitch changes on each tick uint32 portaTick = memory.chnSettings[nChn].ticksToRender + startTick + 1; memory.chnSettings[nChn].ticksToRender += numTicks; memory.RenderChannel(nChn, tickDuration, portaTick); } else { memory.chnSettings[nChn].ticksToRender += (numTicks - startTick); } } } } oldTickDuration = tickDuration; // Pattern loop is not executed in FT2 if there are any position jump or pattern break commands on the same row. // Pattern loop is not executed in IT if there are any position jump commands on the same row. // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if(patternLoopEndedOnThisRow && (!m_playBehaviour[kFT2PatternLoopWithJumps] || !(positionJumpOnThisRow || patternBreakOnThisRow)) && (!m_playBehaviour[kITPatternLoopWithJumps] || !positionJumpOnThisRow)) { std::map<double, int> startTimes; // This is really just a simple estimation for nested pattern loops. It should handle cases correctly where all parallel loops start and end on the same row. // If one of them starts or ends "in between", it will most likely calculate a wrong duration. // For S3M files, it's also way off. pChn = playState.Chn; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { ModCommand::COMMAND command = pChn->rowCommand.command; ModCommand::PARAM param = pChn->rowCommand.param; if((command == CMD_S3MCMDEX && param >= 0xB1 && param <= 0xBF) || (command == CMD_MODCMDEX && param >= 0x61 && param <= 0x6F)) { const double start = memory.chnSettings[nChn].patLoop; if(!startTimes[start]) startTimes[start] = 1; startTimes[start] = mpt::lcm(startTimes[start], 1 + (param & 0x0F)); } } for(const auto &i : startTimes) { memory.elapsedTime += (memory.elapsedTime - i.first) * (double)(i.second - 1); for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { if(memory.chnSettings[nChn].patLoop == i.first) { playState.m_lTotalSampleCount += (playState.m_lTotalSampleCount - memory.chnSettings[nChn].patLoopSmp) * (i.second - 1); if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; memory.chnSettings[nChn].patLoopStart = playState.m_nRow + 1; } break; } } } if(GetType() == MOD_TYPE_IT) { // IT pattern loop start row update - at the end of a pattern loop, set pattern loop start to next row (for upcoming pattern loops with missing SB0) for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if((pChn->rowCommand.command == CMD_S3MCMDEX && pChn->rowCommand.param >= 0xB1 && pChn->rowCommand.param <= 0xBF)) { memory.chnSettings[nChn].patLoop = memory.elapsedTime; memory.chnSettings[nChn].patLoopSmp = playState.m_lTotalSampleCount; } } } } } // Now advance the sample positions for sample seeking on channels that are still playing if(adjustSamplePos) { for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++) { if(memory.chnSettings[nChn].ticksToRender != GetLengthMemory::IGNORE_CHANNEL) { memory.RenderChannel(nChn, oldTickDuration); } } } if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { retval.lastOrder = playState.m_nCurrentOrder; retval.lastRow = playState.m_nRow; } retval.duration = memory.elapsedTime; results.push_back(retval); // Store final variables if(adjustMode & eAdjust) { if(retval.targetReached || target.mode == GetLengthTarget::NoTarget) { // Target found, or there is no target (i.e. play whole song)... m_PlayState = std::move(playState); m_PlayState.m_nNextRow = m_PlayState.m_nRow; m_PlayState.m_nFrameDelay = m_PlayState.m_nPatternDelay = 0; m_PlayState.m_nTickCount = Util::MaxValueOfType(m_PlayState.m_nTickCount) - 1; m_PlayState.m_bPositionChanged = true; for(CHANNELINDEX n = 0; n < GetNumChannels(); n++) { if(m_PlayState.Chn[n].nLastNote != NOTE_NONE) { m_PlayState.Chn[n].nNewNote = m_PlayState.Chn[n].nLastNote; } if(memory.chnSettings[n].vol != 0xFF && !adjustSamplePos) { m_PlayState.Chn[n].nVolume = std::min(memory.chnSettings[n].vol, uint8(64)) * 4; } } #ifndef NO_PLUGINS // If there were any PC events, update plugin parameters to their latest value. std::bitset<MAX_MIXPLUGINS> plugSetProgram; for(const auto &param : memory.plugParams) { PLUGINDEX plug = param.first.first - 1; IMixPlugin *plugin = m_MixPlugins[plug].pMixPlugin; if(plugin != nullptr) { if(!plugSetProgram[plug]) { // Used for bridged plugins to avoid sending out individual messages for each parameter. plugSetProgram.set(plug); plugin->BeginSetProgram(); } plugin->SetParameter(param.first.second, param.second / PlugParamValue(ModCommand::maxColumnValue)); } } if(plugSetProgram.any()) { for(PLUGINDEX i = 0; i < MAX_MIXPLUGINS; i++) { if(plugSetProgram[i]) { m_MixPlugins[i].pMixPlugin->EndSetProgram(); } } } #endif // NO_PLUGINS } else if(adjustMode != eAdjustOnSuccess) { // Target not found (e.g. when jumping to a hidden sub song), reset global variables... m_PlayState.m_nMusicSpeed = m_nDefaultSpeed; m_PlayState.m_nMusicTempo = m_nDefaultTempo; m_PlayState.m_nGlobalVolume = m_nDefaultGlobalVolume; } // When adjusting the playback status, we will also want to update the visited rows vector according to the current position. if(sequence != Order.GetCurrentSequenceIndex()) { Order.SetSequence(sequence); } visitedSongRows.Set(visitedRows); } return results; } ////////////////////////////////////////////////////////////////////////////////////////////////// // Effects // Change sample or instrument number. void CSoundFile::InstrumentChange(ModChannel *pChn, uint32 instr, bool bPorta, bool bUpdVol, bool bResetEnv) const { const ModInstrument *pIns = instr <= GetNumInstruments() ? Instruments[instr] : nullptr; const ModSample *pSmp = &Samples[instr]; ModCommand::NOTE note = pChn->nNewNote; if(note == NOTE_NONE && m_playBehaviour[kITInstrWithoutNote]) return; if(pIns != nullptr && ModCommand::IsNote(note)) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it if(pIns->Keyboard[note - NOTE_MIN] == 0 && m_playBehaviour[kITEmptyNoteMapSlot] && !pIns->HasValidMIDIChannel()) { pChn->pModInstrument = pIns; return; } if(pIns->NoteMap[note - NOTE_MIN] > NOTE_MAX) return; uint32 n = pIns->Keyboard[note - NOTE_MIN]; pSmp = ((n) && (n < MAX_SAMPLES)) ? &Samples[n] : nullptr; } else if(GetNumInstruments()) { // No valid instrument, or not a valid note. if (note >= NOTE_MIN_SPECIAL) return; if(m_playBehaviour[kITEmptyNoteMapSlot] && (pIns == nullptr || !pIns->HasValidMIDIChannel())) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it pChn->pModInstrument = nullptr; pChn->nNewIns = 0; return; } pSmp = nullptr; } bool returnAfterVolumeAdjust = false; // instrumentChanged is used for IT carry-on env option bool instrumentChanged = (pIns != pChn->pModInstrument); const bool sampleChanged = (pChn->pModSample != nullptr) && (pSmp != pChn->pModSample); const bool newTuning = (GetType() == MOD_TYPE_MPT && pIns && pIns->pTuning); // Playback behavior change for MPT: With portamento don't change sample if it is in // the same instrument as previous sample. if(bPorta && newTuning && pIns == pChn->pModInstrument && sampleChanged) return; if(sampleChanged && bPorta) { // IT compatibility: No sample change (also within multi-sample instruments) during portamento when using Compatible Gxx. // Test case: PortaInsNumCompat.it, PortaSampleCompat.it, PortaCutCompat.it if(m_playBehaviour[kITPortamentoInstrument] && m_SongFlags[SONG_ITCOMPATGXX] && !pChn->increment.IsZero()) { pSmp = pChn->pModSample; } // Special XM hack (also applies to MOD / S3M, except when playing IT-style S3Ms, such as k_vision.s3m) // Test case: PortaSmpChange.mod, PortaSmpChange.s3m if((!instrumentChanged && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)) && pIns) || (GetType() == MOD_TYPE_PLM) || (GetType() == MOD_TYPE_MOD && pChn->IsSamplePlaying()) || m_playBehaviour[kST3PortaSampleChange]) { // FT2 doesn't change the sample in this case, // but still uses the sample info from the old one (bug?) returnAfterVolumeAdjust = true; } } // IT compatibility: A lone instrument number should only reset sample properties to those of the corresponding sample in instrument mode. // C#5 01 ... <-- sample 1 // C-5 .. g02 <-- sample 2 // ... 01 ... <-- still sample 1, but with properties of sample 2 // In the above example, no sample change happens on the second row. In the third row, sample 1 keeps playing but with the // volume and panning properties of sample 2. // Test case: InstrAfterMultisamplePorta.it if(m_nInstruments && !instrumentChanged && sampleChanged && pChn->pCurrentSample != nullptr && m_playBehaviour[kITMultiSampleInstrumentNumber] && !pChn->rowCommand.IsNote()) { returnAfterVolumeAdjust = true; } // IT Compatibility: Envelope pickup after SCx cut (but don't do this when working with plugins, or else envelope carry stops working) // Test case: cut-carry.it if(!pChn->IsSamplePlaying() && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && (!pIns || !pIns->HasValidMIDIChannel())) { instrumentChanged = true; } // FT2 compatibility: new instrument + portamento = ignore new instrument number, but reload old instrument settings (the world of XM is upside down...) // And this does *not* happen if volume column portamento is used together with note delay... (handled in ProcessEffects(), where all the other note delay stuff is.) // Test case: porta-delay.xm if(instrumentChanged && bPorta && m_playBehaviour[kFT2PortaIgnoreInstr] && (pChn->pModInstrument != nullptr || pChn->pModSample != nullptr)) { pIns = pChn->pModInstrument; pSmp = pChn->pModSample; instrumentChanged = false; } else { pChn->pModInstrument = pIns; } // Update Volume if (bUpdVol && (!(GetType() & (MOD_TYPE_MOD | MOD_TYPE_S3M)) || ((pSmp != nullptr && pSmp->HasSampleData()) || pChn->HasMIDIOutput()))) { if(pSmp) { if(!pSmp->uFlags[SMP_NODEFAULTVOLUME]) pChn->nVolume = pSmp->nVolume; } else if(pIns && pIns->nMixPlug) { pChn->nVolume = pChn->GetVSTVolume(); } else { pChn->nVolume = 0; } } if(returnAfterVolumeAdjust && sampleChanged && m_playBehaviour[kMODSampleSwap] && pSmp != nullptr) { // ProTracker applies new instrument's finetune but keeps the old sample playing. // Test case: PortaSwapPT.mod pChn->nFineTune = pSmp->nFineTune; } if(returnAfterVolumeAdjust) return; // Instrument adjust pChn->nNewIns = 0; // IT Compatiblity: NNA is reset on every note change, not every instrument change (fixes s7xinsnum.it). if (pIns && ((!m_playBehaviour[kITNNAReset] && pSmp) || pIns->nMixPlug)) pChn->nNNA = pIns->nNNA; // Update volume pChn->UpdateInstrumentVolume(pSmp, pIns); // Update panning // FT2 compatibility: Only reset panning on instrument numbers, not notes (bUpdVol condition) // Test case: PanMemory.xm // IT compatibility: Sample and instrument panning is only applied on note change, not instrument change // Test case: PanReset.it if((bUpdVol || !(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) && !m_playBehaviour[kITPanningReset]) { ApplyInstrumentPanning(pChn, pIns, pSmp); } // Reset envelopes if(bResetEnv) { // Blurb by Storlek (from the SchismTracker code): // Conditions experimentally determined to cause envelope reset in Impulse Tracker: // - no note currently playing (of course) // - note given, no portamento // - instrument number given, portamento, compat gxx enabled // - instrument number given, no portamento, after keyoff, old effects enabled // If someone can enlighten me to what the logic really is here, I'd appreciate it. // Seems like it's just a total mess though, probably to get XMs to play right. bool reset, resetAlways; // IT Compatibility: Envelope reset // Test case: EnvReset.it if(m_playBehaviour[kITEnvelopeReset]) { const bool insNumber = (instr != 0); reset = (!pChn->nLength || (insNumber && bPorta && m_SongFlags[SONG_ITCOMPATGXX]) || (insNumber && !bPorta && pChn->dwFlags[CHN_NOTEFADE | CHN_KEYOFF] && m_SongFlags[SONG_ITOLDEFFECTS])); // NOTE: IT2.14 with SB/GUS/etc. output is different. We are going after IT's WAV writer here. // For SB/GUS/etc. emulation, envelope carry should only apply when the NNA isn't set to "Note Cut". // Test case: CarryNNA.it resetAlways = (!pChn->nFadeOutVol || instrumentChanged || pChn->dwFlags[CHN_KEYOFF]); } else { reset = (!bPorta || !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) || m_SongFlags[SONG_ITCOMPATGXX] || !pChn->nLength || (pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol)); resetAlways = !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) || instrumentChanged || pIns == nullptr || pChn->dwFlags[CHN_KEYOFF | CHN_NOTEFADE]; } if(reset) { pChn->dwFlags.set(CHN_FASTVOLRAMP); if(pIns != nullptr) { if(resetAlways) { pChn->ResetEnvelopes(); } else { if(!pIns->VolEnv.dwFlags[ENV_CARRY]) pChn->VolEnv.Reset(); if(!pIns->PanEnv.dwFlags[ENV_CARRY]) pChn->PanEnv.Reset(); if(!pIns->PitchEnv.dwFlags[ENV_CARRY]) pChn->PitchEnv.Reset(); } } // IT Compatibility: Autovibrato reset if(!m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } } else if(pIns != nullptr && !pIns->VolEnv.dwFlags[ENV_ENABLED]) { if(m_playBehaviour[kITPortamentoInstrument]) { pChn->VolEnv.Reset(); } else { pChn->ResetEnvelopes(); } } } // Invalid sample ? if(pSmp == nullptr && (pIns == nullptr || !pIns->HasValidMIDIChannel())) { pChn->pModSample = nullptr; pChn->nInsVol = 0; return; } // Tone-Portamento doesn't reset the pingpong direction flag if(bPorta && pSmp == pChn->pModSample && pSmp != nullptr) { // If channel length is 0, we cut a previous sample using SCx. In that case, we have to update sample length, loop points, etc... if(GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT) && pChn->nLength != 0) return; pChn->dwFlags.reset(CHN_KEYOFF | CHN_NOTEFADE); pChn->dwFlags = (pChn->dwFlags & (CHN_CHANNELFLAGS | CHN_PINGPONGFLAG)); } else //if(!instrumentChanged || pChn->rowCommand.instr != 0 || !IsCompatibleMode(TRK_FASTTRACKER2)) // SampleChange.xm? { pChn->dwFlags.reset(CHN_KEYOFF | CHN_NOTEFADE); // IT compatibility tentative fix: Don't change bidi loop direction when // no sample nor instrument is changed. if((m_playBehaviour[kITPingPongNoReset] || !(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) && pSmp == pChn->pModSample && !instrumentChanged) pChn->dwFlags = (pChn->dwFlags & (CHN_CHANNELFLAGS | CHN_PINGPONGFLAG)); else pChn->dwFlags = (pChn->dwFlags & CHN_CHANNELFLAGS); if(pIns) { // Copy envelope flags (we actually only need the "enabled" and "pitch" flag) pChn->VolEnv.flags = pIns->VolEnv.dwFlags; pChn->PanEnv.flags = pIns->PanEnv.dwFlags; pChn->PitchEnv.flags = pIns->PitchEnv.dwFlags; // A cutoff frequency of 0 should not be reset just because the filter envelope is enabled. // Test case: FilterEnvReset.it if((pIns->PitchEnv.dwFlags & (ENV_ENABLED | ENV_FILTER)) == (ENV_ENABLED | ENV_FILTER) && !m_playBehaviour[kITFilterBehaviour]) { if(!pChn->nCutOff) pChn->nCutOff = 0x7F; } if(pIns->IsCutoffEnabled()) pChn->nCutOff = pIns->GetCutoff(); if(pIns->IsResonanceEnabled()) pChn->nResonance = pIns->GetResonance(); } } if(pSmp == nullptr) { pChn->pModSample = nullptr; pChn->nLength = 0; return; } if(bPorta && pChn->nLength == 0 && (m_playBehaviour[kFT2PortaNoNote] || m_playBehaviour[kITPortaNoNote])) { // IT/FT2 compatibility: If the note just stopped on the previous tick, prevent it from restarting. // Test cases: PortaJustStoppedNote.xm, PortaJustStoppedNote.it pChn->increment.Set(0); } pChn->pModSample = pSmp; pChn->nLength = pSmp->nLength; pChn->nLoopStart = pSmp->nLoopStart; pChn->nLoopEnd = pSmp->nLoopEnd; // ProTracker "oneshot" loops (if loop start is 0, play the whole sample once and then repeat until loop end) if(m_playBehaviour[kMODOneShotLoops] && pChn->nLoopStart == 0) pChn->nLoopEnd = pSmp->nLength; pChn->dwFlags |= (pSmp->uFlags & (CHN_SAMPLEFLAGS | CHN_SURROUND)); // IT Compatibility: Autovibrato reset if(m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } if(newTuning) { pChn->nC5Speed = pSmp->nC5Speed; pChn->m_CalculateFreq = true; pChn->nFineTune = 0; } else if(!bPorta || sampleChanged || !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM))) { // Don't reset finetune changed by "set finetune" command. // Test case: finetune.xm, finetune.mod // But *do* change the finetune if we switch to a different sample, to fix // Miranda`s axe by Jamson (jam007.xm) - this file doesn't use compatible play mode, // so we may want to use IsCompatibleMode instead if further problems arise. pChn->nC5Speed = pSmp->nC5Speed; pChn->nFineTune = pSmp->nFineTune; } pChn->nTranspose = pSmp->RelativeTone; // FT2 compatibility: Don't reset portamento target with new instrument numbers. // Test case: Porta-Pickup.xm // ProTracker does the same. // Test case: PortaTarget.mod if(!m_playBehaviour[kFT2PortaTargetNoReset] && GetType() != MOD_TYPE_MOD) { pChn->nPortamentoDest = 0; } pChn->m_PortamentoFineSteps = 0; if(pChn->dwFlags[CHN_SUSTAINLOOP]) { pChn->nLoopStart = pSmp->nSustainStart; pChn->nLoopEnd = pSmp->nSustainEnd; if(pChn->dwFlags[CHN_PINGPONGSUSTAIN]) pChn->dwFlags.set(CHN_PINGPONGLOOP); pChn->dwFlags.set(CHN_LOOP); } if(pChn->dwFlags[CHN_LOOP] && pChn->nLoopEnd < pChn->nLength) pChn->nLength = pChn->nLoopEnd; // Fix sample position on instrument change. This is needed for IT "on the fly" sample change. // XXX is this actually called? In ProcessEffects(), a note-on effect is emulated if there's an on the fly sample change! if(pChn->position.GetUInt() >= pChn->nLength) { if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) { pChn->position.Set(0); } } } void CSoundFile::NoteChange(ModChannel *pChn, int note, bool bPorta, bool bResetEnv, bool bManual) const { if (note < NOTE_MIN) return; const ModSample *pSmp = pChn->pModSample; const ModInstrument *pIns = pChn->pModInstrument; const bool newTuning = (GetType() == MOD_TYPE_MPT && pIns != nullptr && pIns->pTuning); // save the note that's actually used, as it's necessary to properly calculate PPS and stuff const int realnote = note; if((pIns) && (note - NOTE_MIN < (int)CountOf(pIns->Keyboard))) { uint32 n = pIns->Keyboard[note - NOTE_MIN]; if((n) && (n < MAX_SAMPLES)) { pSmp = &Samples[n]; } else if(m_playBehaviour[kITEmptyNoteMapSlot] && !pChn->HasMIDIOutput()) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it return; } note = pIns->NoteMap[note - NOTE_MIN]; } // Key Off if(note > NOTE_MAX) { // Key Off (+ Invalid Note for XM - TODO is this correct?) if(note == NOTE_KEYOFF || !(GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT))) { KeyOff(pChn); } else // Invalid Note -> Note Fade { if(/*note == NOTE_FADE && */ GetNumInstruments()) pChn->dwFlags.set(CHN_NOTEFADE); } // Note Cut if (note == NOTE_NOTECUT) { pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); // IT compatibility: Stopping sample playback by setting sample increment to 0 rather than volume // Test case: NoteOffInstr.it if ((!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) || (m_nInstruments != 0 && !m_playBehaviour[kITInstrWithNoteOff])) pChn->nVolume = 0; if(m_playBehaviour[kITInstrWithNoteOff]) pChn->increment.Set(0); pChn->nFadeOutVol = 0; } // IT compatibility tentative fix: Clear channel note memory. if(m_playBehaviour[kITClearOldNoteAfterCut]) { pChn->nNote = pChn->nNewNote = NOTE_NONE; } return; } if(newTuning) { if(!bPorta || pChn->nNote == NOTE_NONE) pChn->nPortamentoDest = 0; else { pChn->nPortamentoDest = pIns->pTuning->GetStepDistance(pChn->nNote, pChn->m_PortamentoFineSteps, static_cast<Tuning::NOTEINDEXTYPE>(note), 0); //Here pChn->nPortamentoDest means 'steps to slide'. pChn->m_PortamentoFineSteps = -pChn->nPortamentoDest; } } if(!bPorta && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MED | MOD_TYPE_MT2))) { if(pSmp) { pChn->nTranspose = pSmp->RelativeTone; pChn->nFineTune = pSmp->nFineTune; } } // IT Compatibility: Update multisample instruments frequency even if instrument is not specified (fixes the guitars in spx-shuttledeparture.it) // Test case: freqreset-noins.it if(!bPorta && pSmp && m_playBehaviour[kITMultiSampleBehaviour]) pChn->nC5Speed = pSmp->nC5Speed; if(bPorta && !pChn->IsSamplePlaying()) { if(m_playBehaviour[kFT2PortaNoNote]) { // FT2 Compatibility: Ignore notes with portamento if there was no note playing. // Test case: 3xx-no-old-samp.xm pChn->nPeriod = 0; return; } else if(m_playBehaviour[kITPortaNoNote]) { // IT Compatibility: Ignore portamento command if no note was playing (e.g. if a previous note has faded out). // Test case: Fade-Porta.it bPorta = false; } } if(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2|MOD_TYPE_MED|MOD_TYPE_MOD)) { note += pChn->nTranspose; // RealNote = PatternNote + RelativeTone; (0..118, 0 = C-0, 118 = A#9) Limit(note, NOTE_MIN + 11, NOTE_MIN + 130); // 119 possible notes } else { Limit(note, NOTE_MIN, NOTE_MAX); } if(m_playBehaviour[kITRealNoteMapping]) { // need to memorize the original note for various effects (e.g. PPS) pChn->nNote = static_cast<ModCommand::NOTE>(Clamp(realnote, NOTE_MIN, NOTE_MAX)); } else { pChn->nNote = static_cast<ModCommand::NOTE>(note); } pChn->m_CalculateFreq = true; if ((!bPorta) || (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))) pChn->nNewIns = 0; uint32 period = GetPeriodFromNote(note, pChn->nFineTune, pChn->nC5Speed); pChn->nPanbrelloOffset = 0; // IT compatibility: Sample and instrument panning is only applied on note change, not instrument change // Test case: PanReset.it if(m_playBehaviour[kITPanningReset]) ApplyInstrumentPanning(pChn, pIns, pSmp); if(bResetEnv && !bPorta) { pChn->nVolSwing = pChn->nPanSwing = 0; pChn->nResSwing = pChn->nCutSwing = 0; if(pIns) { // IT Compatiblity: NNA is reset on every note change, not every instrument change (fixes spx-farspacedance.it). if(m_playBehaviour[kITNNAReset]) pChn->nNNA = pIns->nNNA; if(!pIns->VolEnv.dwFlags[ENV_CARRY]) pChn->VolEnv.Reset(); if(!pIns->PanEnv.dwFlags[ENV_CARRY]) pChn->PanEnv.Reset(); if(!pIns->PitchEnv.dwFlags[ENV_CARRY]) pChn->PitchEnv.Reset(); // Volume Swing if(pIns->nVolSwing) { pChn->nVolSwing = static_cast<int16>(((mpt::random<int8>(AccessPRNG()) * pIns->nVolSwing) / 64 + 1) * (m_playBehaviour[kITSwingBehaviour] ? pChn->nInsVol : ((pChn->nVolume + 1) / 2)) / 199); } // Pan Swing if(pIns->nPanSwing) { pChn->nPanSwing = static_cast<int16>(((mpt::random<int8>(AccessPRNG()) * pIns->nPanSwing * 4) / 128)); if(!m_playBehaviour[kITSwingBehaviour]) { pChn->nRestorePanOnNewNote = static_cast<int16>(pChn->nPan + 1); } } // Cutoff Swing if(pIns->nCutSwing) { int32 d = ((int32)pIns->nCutSwing * (int32)(static_cast<int32>(mpt::random<int8>(AccessPRNG())) + 1)) / 128; pChn->nCutSwing = static_cast<int16>((d * pChn->nCutOff + 1) / 128); pChn->nRestoreCutoffOnNewNote = pChn->nCutOff + 1; } // Resonance Swing if(pIns->nResSwing) { int32 d = ((int32)pIns->nResSwing * (int32)(static_cast<int32>(mpt::random<int8>(AccessPRNG())) + 1)) / 128; pChn->nResSwing = static_cast<int16>((d * pChn->nResonance + 1) / 128); pChn->nRestoreResonanceOnNewNote = pChn->nResonance + 1; } } } if(!pSmp) return; if(period) { if((!bPorta) || (!pChn->nPeriod)) pChn->nPeriod = period; if(!newTuning) { // FT2 compatibility: Don't reset portamento target with new notes. // Test case: Porta-Pickup.xm // ProTracker does the same. // Test case: PortaTarget.mod // IT compatibility: Portamento target is completely cleared with new notes. // Test case: PortaReset.it if(bPorta || !(m_playBehaviour[kFT2PortaTargetNoReset] || m_playBehaviour[kITClearPortaTarget] || GetType() == MOD_TYPE_MOD)) { pChn->nPortamentoDest = period; } } if(!bPorta || (!pChn->nLength && !(GetType() & MOD_TYPE_S3M))) { pChn->pModSample = pSmp; pChn->nLength = pSmp->nLength; pChn->nLoopEnd = pSmp->nLength; pChn->nLoopStart = 0; pChn->position.Set(0); if(m_SongFlags[SONG_PT_MODE] && !pChn->rowCommand.instr) { pChn->position.SetInt(std::min<SmpLength>(pChn->proTrackerOffset, pChn->nLength - 1)); } else { pChn->proTrackerOffset = 0; } pChn->dwFlags = (pChn->dwFlags & CHN_CHANNELFLAGS) | (pSmp->uFlags & (CHN_SAMPLEFLAGS | CHN_SURROUND)); pChn->dwFlags.reset(CHN_PORTAMENTO); if(pChn->dwFlags[CHN_SUSTAINLOOP]) { pChn->nLoopStart = pSmp->nSustainStart; pChn->nLoopEnd = pSmp->nSustainEnd; pChn->dwFlags.set(CHN_PINGPONGLOOP, pChn->dwFlags[CHN_PINGPONGSUSTAIN]); pChn->dwFlags.set(CHN_LOOP); if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd; } else if(pChn->dwFlags[CHN_LOOP]) { pChn->nLoopStart = pSmp->nLoopStart; pChn->nLoopEnd = pSmp->nLoopEnd; if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd; } // ProTracker "oneshot" loops (if loop start is 0, play the whole sample once and then repeat until loop end) if(m_playBehaviour[kMODOneShotLoops] && pChn->nLoopStart == 0) pChn->nLoopEnd = pChn->nLength = pSmp->nLength; if(pChn->dwFlags[CHN_REVERSE]) { pChn->dwFlags.set(CHN_PINGPONGFLAG); pChn->position.SetInt(pChn->nLength - 1); } // Handle "retrigger" waveform type if(pChn->nVibratoType < 4) { // IT Compatibilty: Slightly different waveform offsets (why does MPT have two different offsets here with IT old effects enabled and disabled?) if(!m_playBehaviour[kITVibratoTremoloPanbrello] && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && !m_SongFlags[SONG_ITOLDEFFECTS]) pChn->nVibratoPos = 0x10; else if(GetType() == MOD_TYPE_MTM) pChn->nVibratoPos = 0x20; else if(!(GetType() & (MOD_TYPE_DIGI | MOD_TYPE_DBM))) pChn->nVibratoPos = 0; } // IT Compatibility: No "retrigger" waveform here if(!m_playBehaviour[kITVibratoTremoloPanbrello] && pChn->nTremoloType < 4) { pChn->nTremoloPos = 0; } } if(pChn->position.GetUInt() >= pChn->nLength) pChn->position.SetInt(pChn->nLoopStart); } else { bPorta = false; } if (!bPorta || (!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM))) || (pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol) || (m_SongFlags[SONG_ITCOMPATGXX] && pChn->rowCommand.instr != 0)) { if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_DBM)) && pChn->dwFlags[CHN_NOTEFADE] && !pChn->nFadeOutVol) { pChn->ResetEnvelopes(); // IT Compatibility: Autovibrato reset if(!m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } pChn->dwFlags.reset(CHN_NOTEFADE); pChn->nFadeOutVol = 65536; } if ((!bPorta) || (!m_SongFlags[SONG_ITCOMPATGXX]) || (pChn->rowCommand.instr)) { if ((!(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) || (pChn->rowCommand.instr)) { pChn->dwFlags.reset(CHN_NOTEFADE); pChn->nFadeOutVol = 65536; } } } // IT compatibility: Don't reset key-off flag on porta notes unless Compat Gxx is enabled // Test case: Off-Porta.it, Off-Porta-CompatGxx.it if(m_playBehaviour[kITDontResetNoteOffOnPorta] && bPorta && (!m_SongFlags[SONG_ITCOMPATGXX] || pChn->rowCommand.instr == 0)) pChn->dwFlags.reset(CHN_EXTRALOUD); else pChn->dwFlags.reset(CHN_EXTRALOUD | CHN_KEYOFF); // Enable Ramping if(!bPorta) { pChn->nLeftVU = pChn->nRightVU = 0xFF; pChn->dwFlags.reset(CHN_FILTER); pChn->dwFlags.set(CHN_FASTVOLRAMP); // IT compatibility 15. Retrigger is reset in RetrigNote (Tremor doesn't store anything here, so we just don't reset this as well) if(!m_playBehaviour[kITRetrigger] && !m_playBehaviour[kITTremor]) { // FT2 compatibility: Retrigger is reset in RetrigNote, tremor in ProcessEffects if(!m_playBehaviour[kFT2Retrigger] && !m_playBehaviour[kFT2Tremor]) { pChn->nRetrigCount = 0; pChn->nTremorCount = 0; } } if(bResetEnv) { pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } pChn->rightVol = pChn->leftVol = 0; bool useFilter = !m_SongFlags[SONG_MPTFILTERMODE]; // Setup Initial Filter for this note if(pIns) { if(pIns->IsResonanceEnabled()) { pChn->nResonance = pIns->GetResonance(); useFilter = true; } if(pIns->IsCutoffEnabled()) { pChn->nCutOff = pIns->GetCutoff(); useFilter = true; } if(useFilter && (pIns->nFilterMode != FLTMODE_UNCHANGED)) { pChn->nFilterMode = pIns->nFilterMode; } } else { pChn->nVolSwing = pChn->nPanSwing = 0; pChn->nCutSwing = pChn->nResSwing = 0; } if((pChn->nCutOff < 0x7F || m_playBehaviour[kITFilterBehaviour]) && useFilter) { SetupChannelFilter(pChn, true); } } // Special case for MPT if (bManual) pChn->dwFlags.reset(CHN_MUTE); if((pChn->dwFlags[CHN_MUTE] && (m_MixerSettings.MixerFlags & SNDMIX_MUTECHNMODE)) || (pChn->pModSample != nullptr && pChn->pModSample->uFlags[CHN_MUTE] && !bManual) || (pChn->pModInstrument != nullptr && pChn->pModInstrument->dwFlags[INS_MUTE] && !bManual)) { if (!bManual) pChn->nPeriod = 0; } // Reset the Amiga resampler for this channel if(!bPorta) { pChn->paulaState.Reset(); } } // Apply sample or instrumernt panning void CSoundFile::ApplyInstrumentPanning(ModChannel *pChn, const ModInstrument *instr, const ModSample *smp) const { int32 newPan = int32_min; // Default instrument panning if(instr != nullptr && instr->dwFlags[INS_SETPANNING]) newPan = instr->nPan; // Default sample panning if(smp != nullptr && smp->uFlags[CHN_PANNING]) newPan = smp->nPan; if(newPan != int32_min) { pChn->nPan = newPan; // IT compatibility: Sample and instrument panning overrides channel surround status. // Test case: SmpInsPanSurround.it if(m_playBehaviour[kPanOverride] && !m_SongFlags[SONG_SURROUNDPAN]) { pChn->dwFlags.reset(CHN_SURROUND); } } } CHANNELINDEX CSoundFile::GetNNAChannel(CHANNELINDEX nChn) const { const ModChannel *pChn = &m_PlayState.Chn[nChn]; // Check for empty channel const ModChannel *pi = &m_PlayState.Chn[m_nChannels]; for (CHANNELINDEX i = m_nChannels; i < MAX_CHANNELS; i++, pi++) if (!pi->nLength) return i; if (!pChn->nFadeOutVol) return 0; // All channels are used: check for lowest volume CHANNELINDEX result = 0; uint32 vol = (1u << (14 + 9)) / 4u; // 25% uint32 envpos = uint32_max; const ModChannel *pj = &m_PlayState.Chn[m_nChannels]; for (CHANNELINDEX j = m_nChannels; j < MAX_CHANNELS; j++, pj++) { if (!pj->nFadeOutVol) return j; // Use a combination of real volume [14 bit] (which includes volume envelopes, but also potentially global volume) and note volume [9 bit]. // Rationale: We need volume envelopes in case e.g. all NNA channels are playing at full volume but are looping on a 0-volume envelope node. // But if global volume is not applied to master and the global volume temporarily drops to 0, we would kill arbitrary channels. Hence, add the note volume as well. uint32 v = (pj->nRealVolume << 9) | pj->nVolume; if(pj->dwFlags[CHN_LOOP]) v >>= 1; if ((v < vol) || ((v == vol) && (pj->VolEnv.nEnvPosition > envpos))) { envpos = pj->VolEnv.nEnvPosition; vol = v; result = j; } } return result; } CHANNELINDEX CSoundFile::CheckNNA(CHANNELINDEX nChn, uint32 instr, int note, bool forceCut) { CHANNELINDEX nnaChn = CHANNELINDEX_INVALID; ModChannel &srcChn = m_PlayState.Chn[nChn]; const ModInstrument *pIns = nullptr; if(!ModCommand::IsNote(static_cast<ModCommand::NOTE>(note))) { return nnaChn; } // Always NNA cut - using if((!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_MT2)) || !m_nInstruments || forceCut) && !srcChn.HasMIDIOutput()) { if(!srcChn.nLength || srcChn.dwFlags[CHN_MUTE] || !(srcChn.rightVol | srcChn.leftVol)) { return CHANNELINDEX_INVALID; } nnaChn = GetNNAChannel(nChn); if(!nnaChn) return CHANNELINDEX_INVALID; ModChannel &chn = m_PlayState.Chn[nnaChn]; // Copy Channel chn = srcChn; chn.dwFlags.reset(CHN_VIBRATO | CHN_TREMOLO | CHN_MUTE | CHN_PORTAMENTO); chn.nPanbrelloOffset = 0; chn.nMasterChn = nChn + 1; chn.nCommand = CMD_NONE; chn.rowCommand.Clear(); // Cut the note chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); // Stop this channel srcChn.nLength = 0; srcChn.position.Set(0); srcChn.nROfs = srcChn.nLOfs = 0; srcChn.rightVol = srcChn.leftVol = 0; return nnaChn; } if(instr > GetNumInstruments()) instr = 0; const ModSample *pSample = srcChn.pModSample; // If no instrument is given, assume previous instrument to still be valid. // Test case: DNA-NoInstr.it pIns = instr > 0 ? Instruments[instr] : srcChn.pModInstrument; if(pIns != nullptr) { uint32 n = pIns->Keyboard[note - NOTE_MIN]; note = pIns->NoteMap[note - NOTE_MIN]; if ((n) && (n < MAX_SAMPLES)) { pSample = &Samples[n]; } else if(m_playBehaviour[kITEmptyNoteMapSlot] && !pIns->HasValidMIDIChannel()) { // Impulse Tracker ignores empty slots. // We won't ignore them if a plugin is assigned to this slot, so that VSTis still work as intended. // Test case: emptyslot.it, PortaInsNum.it, gxsmp.it, gxsmp2.it return CHANNELINDEX_INVALID; } } if (srcChn.dwFlags[CHN_MUTE]) return CHANNELINDEX_INVALID; for(CHANNELINDEX i = nChn; i < MAX_CHANNELS; i++) if(i >= m_nChannels || i == nChn) { ModChannel &chn = m_PlayState.Chn[i]; bool applyDNAtoPlug = false; if((chn.nMasterChn == nChn + 1 || i == nChn) && chn.pModInstrument != nullptr) { bool bOk = false; // Duplicate Check Type switch(chn.pModInstrument->nDCT) { // Note case DCT_NOTE: if(note && chn.nNote == note && pIns == chn.pModInstrument) bOk = true; if(pIns && pIns->nMixPlug) applyDNAtoPlug = true; break; // Sample case DCT_SAMPLE: if(pSample != nullptr && pSample == chn.pModSample) bOk = true; break; // Instrument case DCT_INSTRUMENT: if(pIns == chn.pModInstrument) bOk = true; if(pIns && pIns->nMixPlug) applyDNAtoPlug = true; break; // Plugin case DCT_PLUGIN: if(pIns && (pIns->nMixPlug) && (pIns->nMixPlug == chn.pModInstrument->nMixPlug)) { applyDNAtoPlug = true; bOk = true; } break; } // Duplicate Note Action if (bOk) { #ifndef NO_PLUGINS if (applyDNAtoPlug && chn.nNote != NOTE_NONE) { switch(chn.pModInstrument->nDNA) { case DNA_NOTECUT: case DNA_NOTEOFF: case DNA_NOTEFADE: // Switch off duplicated note played on this plugin SendMIDINote(i, chn.GetPluginNote(m_playBehaviour[kITRealNoteMapping]) + NOTE_MAX_SPECIAL, 0); chn.nArpeggioLastNote = NOTE_NONE; break; } } #endif // NO_PLUGINS switch(chn.pModInstrument->nDNA) { // Cut case DNA_NOTECUT: KeyOff(&chn); chn.nVolume = 0; break; // Note Off case DNA_NOTEOFF: KeyOff(&chn); break; // Note Fade case DNA_NOTEFADE: chn.dwFlags.set(CHN_NOTEFADE); break; } if(!chn.nVolume) { chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } } // Do we need to apply New/Duplicate Note Action to a VSTi? bool applyNNAtoPlug = false; #ifndef NO_PLUGINS IMixPlugin *pPlugin = nullptr; if(srcChn.HasMIDIOutput() && ModCommand::IsNote(srcChn.nNote)) // instro sends to a midi chan { PLUGINDEX nPlugin = GetBestPlugin(nChn, PrioritiseInstrument, RespectMutes); if(nPlugin > 0 && nPlugin <= MAX_MIXPLUGINS) { pPlugin = m_MixPlugins[nPlugin-1].pMixPlugin; if(pPlugin) { // apply NNA to this plugin iff it is currently playing a note on this tracker channel // (and if it is playing a note, we know that would be the last note played on this chan). applyNNAtoPlug = pPlugin->IsNotePlaying(srcChn.GetPluginNote(m_playBehaviour[kITRealNoteMapping]), GetBestMidiChannel(nChn), nChn); } } } #endif // NO_PLUGINS // New Note Action if((srcChn.nRealVolume > 0 && srcChn.nLength > 0) || applyNNAtoPlug) { nnaChn = GetNNAChannel(nChn); if(nnaChn != 0) { ModChannel &chn = m_PlayState.Chn[nnaChn]; // Copy Channel chn = srcChn; chn.dwFlags.reset(CHN_VIBRATO | CHN_TREMOLO | CHN_PORTAMENTO); chn.nPanbrelloOffset = 0; chn.nMasterChn = nChn < GetNumChannels() ? nChn + 1 : 0; chn.nCommand = CMD_NONE; #ifndef NO_PLUGINS if(applyNNAtoPlug && pPlugin) { //Move note to the NNA channel (odd, but makes sense with DNA stuff). //Actually a bad idea since it then become very hard to kill some notes. //pPlugin->MoveNote(pChn.nNote, pChn.pModInstrument->nMidiChannel, nChn, n); switch(srcChn.nNNA) { case NNA_NOTEOFF: case NNA_NOTECUT: case NNA_NOTEFADE: //switch off note played on this plugin, on this tracker channel and midi channel //pPlugin->MidiCommand(pChn.pModInstrument->nMidiChannel, pChn.pModInstrument->nMidiProgram, pChn.nNote + NOTE_MAX_SPECIAL, 0, n); SendMIDINote(nChn, NOTE_KEYOFF, 0); srcChn.nArpeggioLastNote = NOTE_NONE; break; } } #endif // NO_PLUGINS // Key Off the note switch(srcChn.nNNA) { case NNA_NOTEOFF: KeyOff(&chn); break; case NNA_NOTECUT: chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE); break; case NNA_NOTEFADE: chn.dwFlags.set(CHN_NOTEFADE); break; } if(!chn.nVolume) { chn.nFadeOutVol = 0; chn.dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } // Stop this channel srcChn.nLength = 0; srcChn.position.Set(0); srcChn.nROfs = srcChn.nLOfs = 0; } } return nnaChn; } bool CSoundFile::ProcessEffects() { ModChannel *pChn = m_PlayState.Chn; ROWINDEX nBreakRow = ROWINDEX_INVALID; // Is changed if a break to row command is encountered ROWINDEX nPatLoopRow = ROWINDEX_INVALID; // Is changed if a pattern loop jump-back is executed ORDERINDEX nPosJump = ORDERINDEX_INVALID; for(CHANNELINDEX nChn = 0; nChn < GetNumChannels(); nChn++, pChn++) { const uint32 tickCount = m_PlayState.m_nTickCount % (m_PlayState.m_nMusicSpeed + m_PlayState.m_nFrameDelay); uint32 instr = pChn->rowCommand.instr; ModCommand::VOLCMD volcmd = pChn->rowCommand.volcmd; uint32 vol = pChn->rowCommand.vol; ModCommand::COMMAND cmd = pChn->rowCommand.command; uint32 param = pChn->rowCommand.param; bool bPorta = pChn->rowCommand.IsPortamento(); uint32 nStartTick = 0; pChn->isFirstTick = m_SongFlags[SONG_FIRSTTICK]; // Process parameter control note. if(pChn->rowCommand.note == NOTE_PC) { #ifndef NO_PLUGINS const PLUGINDEX plug = pChn->rowCommand.instr; const PlugParamIndex plugparam = pChn->rowCommand.GetValueVolCol(); const PlugParamValue value = pChn->rowCommand.GetValueEffectCol() / PlugParamValue(ModCommand::maxColumnValue); if(plug > 0 && plug <= MAX_MIXPLUGINS && m_MixPlugins[plug - 1].pMixPlugin) m_MixPlugins[plug-1].pMixPlugin->SetParameter(plugparam, value); #endif // NO_PLUGINS } // Process continuous parameter control note. // Row data is cleared after first tick so on following // ticks using channels m_nPlugParamValueStep to identify // the need for parameter control. The condition cmd == 0 // is to make sure that m_nPlugParamValueStep != 0 because // of NOTE_PCS, not because of macro. if(pChn->rowCommand.note == NOTE_PCS || (cmd == CMD_NONE && pChn->m_plugParamValueStep != 0)) { #ifndef NO_PLUGINS const bool isFirstTick = m_SongFlags[SONG_FIRSTTICK]; if(isFirstTick) pChn->m_RowPlug = pChn->rowCommand.instr; const PLUGINDEX nPlug = pChn->m_RowPlug; const bool hasValidPlug = (nPlug > 0 && nPlug <= MAX_MIXPLUGINS && m_MixPlugins[nPlug-1].pMixPlugin); if(hasValidPlug) { if(isFirstTick) pChn->m_RowPlugParam = ModCommand::GetValueVolCol(pChn->rowCommand.volcmd, pChn->rowCommand.vol); const PlugParamIndex plugparam = pChn->m_RowPlugParam; if(isFirstTick) { PlugParamValue targetvalue = ModCommand::GetValueEffectCol(pChn->rowCommand.command, pChn->rowCommand.param) / PlugParamValue(ModCommand::maxColumnValue); pChn->m_plugParamTargetValue = targetvalue; pChn->m_plugParamValueStep = (targetvalue - m_MixPlugins[nPlug-1].pMixPlugin->GetParameter(plugparam)) / float(GetNumTicksOnCurrentRow()); } if(m_PlayState.m_nTickCount + 1 == GetNumTicksOnCurrentRow()) { // On last tick, set parameter exactly to target value. m_MixPlugins[nPlug-1].pMixPlugin->SetParameter(plugparam, pChn->m_plugParamTargetValue); } else m_MixPlugins[nPlug-1].pMixPlugin->ModifyParameter(plugparam, pChn->m_plugParamValueStep); } #endif // NO_PLUGINS } // Apart from changing parameters, parameter control notes are intended to be 'invisible'. // To achieve this, clearing the note data so that rest of the process sees the row as empty row. if(ModCommand::IsPcNote(pChn->rowCommand.note)) { pChn->ClearRowCmd(); instr = 0; volcmd = VOLCMD_NONE; vol = 0; cmd = CMD_NONE; param = 0; bPorta = false; } // Process Invert Loop (MOD Effect, called every row if it's active) if(!m_SongFlags[SONG_FIRSTTICK]) { InvertLoop(&m_PlayState.Chn[nChn]); } else { if(instr) m_PlayState.Chn[nChn].nEFxOffset = 0; } // Process special effects (note delay, pattern delay, pattern loop) if (cmd == CMD_DELAYCUT) { //:xy --> note delay until tick x, note cut at tick x+y nStartTick = (param & 0xF0) >> 4; const uint32 cutAtTick = nStartTick + (param & 0x0F); NoteCut(nChn, cutAtTick, m_playBehaviour[kITSCxStopsSample]); } else if ((cmd == CMD_MODCMDEX) || (cmd == CMD_S3MCMDEX)) { if ((!param) && (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))) param = pChn->nOldCmdEx; else pChn->nOldCmdEx = static_cast<ModCommand::PARAM>(param); // Note Delay ? if ((param & 0xF0) == 0xD0) { nStartTick = param & 0x0F; if(nStartTick == 0) { //IT compatibility 22. SD0 == SD1 if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) nStartTick = 1; //ST3 ignores notes with SD0 completely else if(GetType() == MOD_TYPE_S3M) continue; } else if(nStartTick >= (m_PlayState.m_nMusicSpeed + m_PlayState.m_nFrameDelay) && m_playBehaviour[kITOutOfRangeDelay]) { // IT compatibility 08. Handling of out-of-range delay command. // Additional test case: tickdelay.it if(instr) { pChn->nNewIns = static_cast<ModCommand::INSTR>(instr); } continue; } } else if(m_SongFlags[SONG_FIRSTTICK]) { // Pattern Loop ? if((((param & 0xF0) == 0x60 && cmd == CMD_MODCMDEX) || ((param & 0xF0) == 0xB0 && cmd == CMD_S3MCMDEX)) && !(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE])) // not even effects are processed on muted S3M channels { ROWINDEX nloop = PatternLoop(pChn, param & 0x0F); if (nloop != ROWINDEX_INVALID) { // FT2 compatibility: E6x overwrites jump targets of Dxx effects that are located left of the E6x effect. // Test cases: PatLoop-Jumps.xm, PatLoop-Various.xm if(nBreakRow != ROWINDEX_INVALID && m_playBehaviour[kFT2PatternLoopWithJumps]) { nBreakRow = nloop; } nPatLoopRow = nloop; } if(GetType() == MOD_TYPE_S3M) { // ST3 doesn't have per-channel pattern loop memory, so spam all changes to other channels as well. for (CHANNELINDEX i = 0; i < GetNumChannels(); i++) { m_PlayState.Chn[i].nPatternLoop = pChn->nPatternLoop; m_PlayState.Chn[i].nPatternLoopCount = pChn->nPatternLoopCount; } } } else if ((param & 0xF0) == 0xE0) { // Pattern Delay // In Scream Tracker 3 / Impulse Tracker, only the first delay command on this row is considered. // Test cases: PatternDelays.it, PatternDelays.s3m, PatternDelays.xm // XXX In Scream Tracker 3, the "left" channels are evaluated before the "right" channels, which is not emulated here! if(!(GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT)) || !m_PlayState.m_nPatternDelay) { if(!(GetType() & (MOD_TYPE_S3M)) || (param & 0x0F) != 0) { // While Impulse Tracker *does* count S60 as a valid row delay (and thus ignores any other row delay commands on the right), // Scream Tracker 3 simply ignores such commands. m_PlayState.m_nPatternDelay = 1 + (param & 0x0F); } } } } } if(GetType() == MOD_TYPE_MTM && cmd == CMD_MODCMDEX && (param & 0xF0) == 0xD0) { // Apparently, retrigger and note delay have the same behaviour in MultiTracker: // They both restart the note at tick x, and if there is a note on the same row, // this note is started on the first tick. nStartTick = 0; param = 0x90 | (param & 0x0F); } if(nStartTick != 0 && pChn->rowCommand.note == NOTE_KEYOFF && pChn->rowCommand.volcmd == VOLCMD_PANNING && m_playBehaviour[kFT2PanWithDelayedNoteOff]) { // FT2 compatibility: If there's a delayed note off, panning commands are ignored. WTF! // Test case: PanOff.xm pChn->rowCommand.volcmd = VOLCMD_NONE; } bool triggerNote = (m_PlayState.m_nTickCount == nStartTick); // Can be delayed by a note delay effect if(m_playBehaviour[kFT2OutOfRangeDelay] && nStartTick >= m_PlayState.m_nMusicSpeed) { // FT2 compatibility: Note delays greater than the song speed should be ignored. // However, EEx pattern delay is *not* considered at all. // Test case: DelayCombination.xm, PortaDelay.xm triggerNote = false; } else if(m_playBehaviour[kRowDelayWithNoteDelay] && nStartTick > 0 && tickCount == nStartTick) { // IT compatibility: Delayed notes (using SDx) that are on the same row as a Row Delay effect are retriggered. // ProTracker / Scream Tracker 3 / FastTracker 2 do the same. // Test case: PatternDelay-NoteDelay.it, PatternDelay-NoteDelay.xm, PatternDelaysRetrig.mod triggerNote = true; } // IT compatibility: Tick-0 vs non-tick-0 effect distinction is always based on tick delay. // Test case: SlideDelay.it if(m_playBehaviour[kITFirstTickHandling]) { pChn->isFirstTick = tickCount == nStartTick; } // FT2 compatibility: Note + portamento + note delay = no portamento // Test case: PortaDelay.xm if(m_playBehaviour[kFT2PortaDelay] && nStartTick != 0) { bPorta = false; } if(m_SongFlags[SONG_PT_MODE] && instr && !m_PlayState.m_nTickCount) { // Instrument number resets the stacked ProTracker offset. // Test case: ptoffset.mod pChn->proTrackerOffset = 0; // ProTracker compatibility: Sample properties are always loaded on the first tick, even when there is a note delay. // Test case: InstrDelay.mod if(!triggerNote && pChn->IsSamplePlaying()) { pChn->nNewIns = static_cast<ModCommand::INSTR>(instr); if(instr <= GetNumSamples()) { pChn->nVolume = Samples[instr].nVolume; pChn->nFineTune = Samples[instr].nFineTune; } } } // Handles note/instrument/volume changes if(triggerNote) { ModCommand::NOTE note = pChn->rowCommand.note; if(instr) pChn->nNewIns = static_cast<ModCommand::INSTR>(instr); if(ModCommand::IsNote(note) && m_playBehaviour[kFT2Transpose]) { // Notes that exceed FT2's limit are completely ignored. // Test case: NoteLimit.xm int transpose = pChn->nTranspose; if(instr && !bPorta) { // Refresh transpose // Test case: NoteLimit2.xm SAMPLEINDEX sample = SAMPLEINDEX_INVALID; if(GetNumInstruments()) { // Instrument mode if(instr <= GetNumInstruments() && Instruments[instr] != nullptr) { sample = Instruments[instr]->Keyboard[note - NOTE_MIN]; } } else { // Sample mode sample = static_cast<SAMPLEINDEX>(instr); } if(sample <= GetNumSamples()) { transpose = GetSample(sample).RelativeTone; } } const int computedNote = note + transpose; if((computedNote < NOTE_MIN + 11 || computedNote > NOTE_MIN + 130)) { note = NOTE_NONE; } } else if((GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) && GetNumInstruments() != 0 && ModCommand::IsNoteOrEmpty(static_cast<ModCommand::NOTE>(note))) { // IT compatibility: Invalid instrument numbers do nothing, but they are remembered for upcoming notes and do not trigger a note in that case. // Test case: InstrumentNumberChange.it INSTRUMENTINDEX instrToCheck = static_cast<INSTRUMENTINDEX>((instr != 0) ? instr : pChn->nOldIns); if(instrToCheck != 0 && (instrToCheck > GetNumInstruments() || Instruments[instrToCheck] == nullptr)) { note = NOTE_NONE; instr = 0; } } // XM: FT2 ignores a note next to a K00 effect, and a fade-out seems to be done when no volume envelope is present (not exactly the Kxx behaviour) if(cmd == CMD_KEYOFF && param == 0 && m_playBehaviour[kFT2KeyOff]) { note = NOTE_NONE; instr = 0; } bool retrigEnv = note == NOTE_NONE && instr != 0; // Apparently, any note number in a pattern causes instruments to recall their original volume settings - no matter if there's a Note Off next to it or whatever. // Test cases: keyoff+instr.xm, delay.xm bool reloadSampleSettings = (m_playBehaviour[kFT2ReloadSampleSettings] && instr != 0); // ProTracker Compatibility: If a sample was stopped before, lone instrument numbers can retrigger it // Test case: PTSwapEmpty.mod bool keepInstr = (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (m_playBehaviour[kMODSampleSwap] && !pChn->IsSamplePlaying() && pChn->pModSample != nullptr && !pChn->pModSample->HasSampleData()); // Now it's time for some FT2 crap... if (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)) { // XM: Key-Off + Sample == Note Cut (BUT: Only if no instr number or volume effect is present!) // Test case: NoteOffVolume.xm if(note == NOTE_KEYOFF && ((!instr && volcmd != VOLCMD_VOLUME && cmd != CMD_VOLUME) || !m_playBehaviour[kFT2KeyOff]) && (pChn->pModInstrument == nullptr || !pChn->pModInstrument->VolEnv.dwFlags[ENV_ENABLED])) { pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->nVolume = 0; note = NOTE_NONE; instr = 0; retrigEnv = false; // FT2 Compatbility: Start fading the note for notes with no delay. Only relevant when a volume command is encountered after the note-off. // Test case: NoteOffFadeNoEnv.xm if(m_SongFlags[SONG_FIRSTTICK] && m_playBehaviour[kFT2NoteOffFlags]) pChn->dwFlags.set(CHN_NOTEFADE); } else if(m_playBehaviour[kFT2RetrigWithNoteDelay] && !m_SongFlags[SONG_FIRSTTICK]) { // FT2 Compatibility: Some special hacks for rogue note delays... (EDx with x > 0) // Apparently anything that is next to a note delay behaves totally unpredictable in FT2. Swedish tracker logic. :) retrigEnv = true; // Portamento + Note Delay = No Portamento // Test case: porta-delay.xm bPorta = false; if(note == NOTE_NONE) { // If there's a note delay but no real note, retrig the last note. // Test case: delay2.xm, delay3.xm note = static_cast<ModCommand::NOTE>(pChn->nNote - pChn->nTranspose); } else if(note >= NOTE_MIN_SPECIAL) { // Gah! Even Note Off + Note Delay will cause envelopes to *retrigger*! How stupid is that? // ... Well, and that is actually all it does if there's an envelope. No fade out, no nothing. *sigh* // Test case: OffDelay.xm note = NOTE_NONE; keepInstr = false; reloadSampleSettings = true; } else { // Normal note keepInstr = true; reloadSampleSettings = true; } } } if((retrigEnv && !m_playBehaviour[kFT2ReloadSampleSettings]) || reloadSampleSettings) { const ModSample *oldSample = nullptr; // Reset default volume when retriggering envelopes if(GetNumInstruments()) { oldSample = pChn->pModSample; } else if (instr <= GetNumSamples()) { // Case: Only samples are used; no instruments. oldSample = &Samples[instr]; } if(oldSample != nullptr) { if(!oldSample->uFlags[SMP_NODEFAULTVOLUME]) pChn->nVolume = oldSample->nVolume; if(reloadSampleSettings) { // Also reload panning pChn->nPan = oldSample->nPan; } } } // FT2 compatibility: Instrument number disables tremor effect // Test case: TremorInstr.xm, TremoRecover.xm if(m_playBehaviour[kFT2Tremor] && instr != 0) { pChn->nTremorCount = 0x20; } if(retrigEnv) //Case: instrument with no note data. { //IT compatibility: Instrument with no note. if(m_playBehaviour[kITInstrWithoutNote] || GetType() == MOD_TYPE_PLM) { // IT compatibility: Completely retrigger note after sample end to also reset portamento. // Test case: PortaResetAfterRetrigger.it bool triggerAfterSmpEnd = m_playBehaviour[kITMultiSampleInstrumentNumber] && !pChn->IsSamplePlaying(); if(GetNumInstruments()) { // Instrument mode if(instr <= GetNumInstruments() && (pChn->pModInstrument != Instruments[instr] || triggerAfterSmpEnd)) note = pChn->nNote; } else { // Sample mode if(instr < MAX_SAMPLES && (pChn->pModSample != &Samples[instr] || triggerAfterSmpEnd)) note = pChn->nNote; } } if (GetNumInstruments() && (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) { pChn->ResetEnvelopes(); pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->dwFlags.reset(CHN_NOTEFADE); pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; pChn->nFadeOutVol = 65536; // FT2 Compatbility: Reset key-off status with instrument number // Test case: NoteOffInstrChange.xm if(m_playBehaviour[kFT2NoteOffFlags]) pChn->dwFlags.reset(CHN_KEYOFF); } if (!keepInstr) instr = 0; } // Note Cut/Off/Fade => ignore instrument if (note >= NOTE_MIN_SPECIAL) { // IT compatibility: Default volume of sample is recalled if instrument number is next to a note-off. // Test case: NoteOffInstr.it, noteoff2.it if(m_playBehaviour[kITInstrWithNoteOff] && instr) { SAMPLEINDEX smp = static_cast<SAMPLEINDEX>(instr); if(GetNumInstruments()) { smp = 0; if(instr <= GetNumInstruments() && Instruments[instr] != nullptr && ModCommand::IsNote(pChn->nLastNote)) { smp = Instruments[instr]->Keyboard[pChn->nLastNote - NOTE_MIN]; } } if(smp > 0 && smp <= GetNumSamples() && !Samples[smp].uFlags[SMP_NODEFAULTVOLUME]) pChn->nVolume = Samples[smp].nVolume; } instr = 0; } if(ModCommand::IsNote(note)) { pChn->nNewNote = pChn->nLastNote = note; // New Note Action ? if(!bPorta) { CheckNNA(nChn, instr, note, false); } } if(note) { if(pChn->nRestorePanOnNewNote > 0) { pChn->nPan = pChn->nRestorePanOnNewNote - 1; pChn->nRestorePanOnNewNote = 0; } if(pChn->nRestoreResonanceOnNewNote > 0) { pChn->nResonance = pChn->nRestoreResonanceOnNewNote - 1; pChn->nRestoreResonanceOnNewNote = 0; } if(pChn->nRestoreCutoffOnNewNote > 0) { pChn->nCutOff = pChn->nRestoreCutoffOnNewNote - 1; pChn->nRestoreCutoffOnNewNote = 0; } } // Instrument Change ? if(instr) { const ModSample *oldSample = pChn->pModSample; //const ModInstrument *oldInstrument = pChn->pModInstrument; InstrumentChange(pChn, instr, bPorta, true); // IT compatibility: Keep new instrument number for next instrument-less note even if sample playback is stopped // Test case: StoppedInstrSwap.it if(GetType() == MOD_TYPE_MOD) { // Test case: PortaSwapPT.mod if(!bPorta || !m_playBehaviour[kMODSampleSwap]) pChn->nNewIns = 0; } else { if(!m_playBehaviour[kITInstrWithNoteOff] || ModCommand::IsNote(note)) pChn->nNewIns = 0; } if(m_playBehaviour[kITPortamentoSwapResetsPos]) { // Test cases: PortaInsNum.it, PortaSample.it if(ModCommand::IsNote(note) && oldSample != pChn->pModSample) { //const bool newInstrument = oldInstrument != pChn->pModInstrument && pChn->pModInstrument->Keyboard[pChn->nNewNote - NOTE_MIN] != 0; pChn->position.Set(0); } } else if ((GetType() & (MOD_TYPE_S3M | MOD_TYPE_IT | MOD_TYPE_MPT) && oldSample != pChn->pModSample && ModCommand::IsNote(note))) { // Special IT case: portamento+note causes sample change -> ignore portamento bPorta = false; } else if(m_playBehaviour[kMODSampleSwap] && pChn->increment.IsZero()) { // If channel was paused and is resurrected by a lone instrument number, reset the sample position. // Test case: PTSwapEmpty.mod pChn->position.Set(0); } } // New Note ? if (note) { if ((!instr) && (pChn->nNewIns) && (note < 0x80)) { InstrumentChange(pChn, pChn->nNewIns, bPorta, pChn->pModSample == nullptr && pChn->pModInstrument == nullptr, !(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))); pChn->nNewIns = 0; } NoteChange(pChn, note, bPorta, !(GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))); if ((bPorta) && (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) && (instr)) { pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->ResetEnvelopes(); pChn->nAutoVibDepth = 0; pChn->nAutoVibPos = 0; } } // Tick-0 only volume commands if (volcmd == VOLCMD_VOLUME) { if (vol > 64) vol = 64; pChn->nVolume = vol << 2; pChn->dwFlags.set(CHN_FASTVOLRAMP); } else if (volcmd == VOLCMD_PANNING) { Panning(pChn, vol, Pan6bit); } #ifndef NO_PLUGINS if (m_nInstruments) ProcessMidiOut(nChn); #endif // NO_PLUGINS } if(m_playBehaviour[kST3NoMutedChannels] && ChnSettings[nChn].dwFlags[CHN_MUTE]) // not even effects are processed on muted S3M channels continue; // Volume Column Effect (except volume & panning) /* A few notes, paraphrased from ITTECH.TXT by Storlek (creator of schismtracker): Ex/Fx/Gx are shared with Exx/Fxx/Gxx; Ex/Fx are 4x the 'normal' slide value Gx is linked with Ex/Fx if Compat Gxx is off, just like Gxx is with Exx/Fxx Gx values: 1, 4, 8, 16, 32, 64, 96, 128, 255 Ax/Bx/Cx/Dx values are used directly (i.e. D9 == D09), and are NOT shared with Dxx (value is stored into nOldVolParam and used by A0/B0/C0/D0) Hx uses the same value as Hxx and Uxx, and affects the *depth* so... hxx = (hx | (oldhxx & 0xf0)) ??? TODO is this done correctly? */ bool doVolumeColumn = m_PlayState.m_nTickCount >= nStartTick; // FT2 compatibility: If there's a note delay, volume column effects are NOT executed // on the first tick and, if there's an instrument number, on the delayed tick. // Test case: VolColDelay.xm, PortaDelay.xm if(m_playBehaviour[kFT2VolColDelay] && nStartTick != 0) { doVolumeColumn = m_PlayState.m_nTickCount != 0 && (m_PlayState.m_nTickCount != nStartTick || (pChn->rowCommand.instr == 0 && volcmd != VOLCMD_TONEPORTAMENTO)); } if(volcmd > VOLCMD_PANNING && doVolumeColumn) { if (volcmd == VOLCMD_TONEPORTAMENTO) { uint32 porta = 0; if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DMF | MOD_TYPE_DBM | MOD_TYPE_IMF | MOD_TYPE_PSM | MOD_TYPE_J2B | MOD_TYPE_ULT | MOD_TYPE_OKT | MOD_TYPE_MT2 | MOD_TYPE_MDL)) { porta = ImpulseTrackerPortaVolCmd[vol & 0x0F]; } else { if(cmd == CMD_TONEPORTAMENTO && GetType() == MOD_TYPE_XM) { // Yes, FT2 is *that* weird. If there is a Mx command in the volume column // and a normal 3xx command, the 3xx command is ignored but the Mx command's // effectiveness is doubled. // Test case: TonePortamentoMemory.xm cmd = CMD_NONE; vol *= 2; } porta = vol << 4; // FT2 compatibility: If there's a portamento and a note delay, execute the portamento, but don't update the parameter // Test case: PortaDelay.xm if(m_playBehaviour[kFT2PortaDelay] && nStartTick != 0) { porta = 0; } } TonePortamento(pChn, porta); } else { // FT2 Compatibility: FT2 ignores some volume commands with parameter = 0. if(m_playBehaviour[kFT2VolColMemory] && vol == 0) { switch(volcmd) { case VOLCMD_VOLUME: case VOLCMD_PANNING: case VOLCMD_VIBRATODEPTH: break; case VOLCMD_PANSLIDELEFT: // FT2 Compatibility: Pan slide left with zero parameter causes panning to be set to full left on every non-row tick. // Test case: PanSlideZero.xm if(!m_SongFlags[SONG_FIRSTTICK]) { pChn->nPan = 0; } MPT_FALLTHROUGH; default: // no memory here. volcmd = VOLCMD_NONE; } } else if(!m_playBehaviour[kITVolColMemory]) { // IT Compatibility: Effects in the volume column don't have an unified memory. // Test case: VolColMemory.it if(vol) pChn->nOldVolParam = static_cast<ModCommand::PARAM>(vol); else vol = pChn->nOldVolParam; } switch(volcmd) { case VOLCMD_VOLSLIDEUP: case VOLCMD_VOLSLIDEDOWN: // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it if(vol == 0 && m_playBehaviour[kITVolColMemory]) { vol = pChn->nOldVolParam; if(vol == 0) break; } else { pChn->nOldVolParam = static_cast<ModCommand::PARAM>(vol); } VolumeSlide(pChn, static_cast<ModCommand::PARAM>(volcmd == VOLCMD_VOLSLIDEUP ? (vol << 4) : vol)); break; case VOLCMD_FINEVOLUP: // IT Compatibility: Fine volume slides in the volume column are only executed on the first tick, not on multiples of the first tick in case of pattern delay // Test case: FineVolColSlide.it if(m_PlayState.m_nTickCount == nStartTick || !m_playBehaviour[kITVolColMemory]) { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it FineVolumeUp(pChn, static_cast<ModCommand::PARAM>(vol), m_playBehaviour[kITVolColMemory]); } break; case VOLCMD_FINEVOLDOWN: // IT Compatibility: Fine volume slides in the volume column are only executed on the first tick, not on multiples of the first tick in case of pattern delay // Test case: FineVolColSlide.it if(m_PlayState.m_nTickCount == nStartTick || !m_playBehaviour[kITVolColMemory]) { // IT Compatibility: Volume column volume slides have their own memory // Test case: VolColMemory.it FineVolumeDown(pChn, static_cast<ModCommand::PARAM>(vol), m_playBehaviour[kITVolColMemory]); } break; case VOLCMD_VIBRATOSPEED: // FT2 does not automatically enable vibrato with the "set vibrato speed" command if(m_playBehaviour[kFT2VolColVibrato]) pChn->nVibratoSpeed = vol & 0x0F; else Vibrato(pChn, vol << 4); break; case VOLCMD_VIBRATODEPTH: Vibrato(pChn, vol); break; case VOLCMD_PANSLIDELEFT: PanningSlide(pChn, static_cast<ModCommand::PARAM>(vol), !m_playBehaviour[kFT2VolColMemory]); break; case VOLCMD_PANSLIDERIGHT: PanningSlide(pChn, static_cast<ModCommand::PARAM>(vol << 4), !m_playBehaviour[kFT2VolColMemory]); break; case VOLCMD_PORTAUP: // IT compatibility (one of the first testcases - link effect memory) PortamentoUp(nChn, static_cast<ModCommand::PARAM>(vol << 2), m_playBehaviour[kITVolColFinePortamento]); break; case VOLCMD_PORTADOWN: // IT compatibility (one of the first testcases - link effect memory) PortamentoDown(nChn, static_cast<ModCommand::PARAM>(vol << 2), m_playBehaviour[kITVolColFinePortamento]); break; case VOLCMD_OFFSET: if (triggerNote && pChn->pModSample && vol <= CountOf(pChn->pModSample->cues)) { SmpLength offset; if(vol == 0) offset = pChn->oldOffset; else offset = pChn->oldOffset = pChn->pModSample->cues[vol - 1]; SampleOffset(*pChn, offset); } break; } } } // Effects if(cmd != CMD_NONE) switch (cmd) { // Set Volume case CMD_VOLUME: if(m_SongFlags[SONG_FIRSTTICK]) { pChn->nVolume = (param < 64) ? param * 4 : 256; pChn->dwFlags.set(CHN_FASTVOLRAMP); } break; // Portamento Up case CMD_PORTAMENTOUP: if ((!param) && (GetType() & MOD_TYPE_MOD)) break; PortamentoUp(nChn, static_cast<ModCommand::PARAM>(param)); break; // Portamento Down case CMD_PORTAMENTODOWN: if ((!param) && (GetType() & MOD_TYPE_MOD)) break; PortamentoDown(nChn, static_cast<ModCommand::PARAM>(param)); break; // Volume Slide case CMD_VOLUMESLIDE: if (param || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param)); break; // Tone-Portamento case CMD_TONEPORTAMENTO: TonePortamento(pChn, param); break; // Tone-Portamento + Volume Slide case CMD_TONEPORTAVOL: if ((param) || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param)); TonePortamento(pChn, 0); break; // Vibrato case CMD_VIBRATO: Vibrato(pChn, param); break; // Vibrato + Volume Slide case CMD_VIBRATOVOL: if ((param) || (GetType() != MOD_TYPE_MOD)) VolumeSlide(pChn, static_cast<ModCommand::PARAM>(param)); Vibrato(pChn, 0); break; // Set Speed case CMD_SPEED: if(m_SongFlags[SONG_FIRSTTICK]) SetSpeed(m_PlayState, param); break; // Set Tempo case CMD_TEMPO: if(m_playBehaviour[kMODVBlankTiming]) { // ProTracker MODs with VBlank timing: All Fxx parameters set the tick count. if(m_SongFlags[SONG_FIRSTTICK] && param != 0) SetSpeed(m_PlayState, param); break; } { param = CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn); if (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT)) { if (param) pChn->nOldTempo = static_cast<ModCommand::PARAM>(param); else param = pChn->nOldTempo; } TEMPO t(param, 0); LimitMax(t, GetModSpecifications().GetTempoMax()); SetTempo(t); } break; // Set Offset case CMD_OFFSET: if (triggerNote) { // FT2 compatibility: Portamento + Offset = Ignore offset // Test case: porta-offset.xm if(bPorta && GetType() == MOD_TYPE_XM) { break; } bool isExtended = false; SmpLength offset = CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn, &isExtended); if(!isExtended) { // No X-param (normal behaviour) offset <<= 8; if (offset) pChn->oldOffset = offset; else offset = pChn->oldOffset; offset += static_cast<SmpLength>(pChn->nOldHiOffset) << 16; } SampleOffset(*pChn, offset); } break; // Disorder Tracker 2 percentage offset case CMD_OFFSETPERCENTAGE: if(triggerNote) { SampleOffset(*pChn, Util::muldiv_unsigned(pChn->nLength, param, 255)); } break; // Arpeggio case CMD_ARPEGGIO: // IT compatibility 01. Don't ignore Arpeggio if no note is playing (also valid for ST3) if(m_PlayState.m_nTickCount) break; if((!pChn->nPeriod || !pChn->nNote) && (pChn->pModInstrument == nullptr || !pChn->pModInstrument->HasValidMIDIChannel()) // Plugin arpeggio && !m_playBehaviour[kITArpeggio] && (GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT))) break; if (!param && (GetType() & (MOD_TYPE_XM | MOD_TYPE_MOD))) break; // Only important when editing MOD/XM files (000 effects are removed when loading files where this means "no effect") pChn->nCommand = CMD_ARPEGGIO; if (param) pChn->nArpeggio = static_cast<ModCommand::PARAM>(param); break; // Retrig case CMD_RETRIG: if (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) { if (!(param & 0xF0)) param |= pChn->nRetrigParam & 0xF0; if (!(param & 0x0F)) param |= pChn->nRetrigParam & 0x0F; param |= 0x100; // increment retrig count on first row } // IT compatibility 15. Retrigger if(m_playBehaviour[kITRetrigger]) { if (param) pChn->nRetrigParam = static_cast<uint8>(param & 0xFF); RetrigNote(nChn, pChn->nRetrigParam, (volcmd == VOLCMD_OFFSET) ? vol + 1 : 0); } else { // XM Retrig if (param) pChn->nRetrigParam = static_cast<uint8>(param & 0xFF); else param = pChn->nRetrigParam; RetrigNote(nChn, param, (volcmd == VOLCMD_OFFSET) ? vol + 1 : 0); } break; // Tremor case CMD_TREMOR: if(!m_SongFlags[SONG_FIRSTTICK]) { break; } // IT compatibility 12. / 13. Tremor (using modified DUMB's Tremor logic here because of old effects - http://dumb.sf.net/) if(m_playBehaviour[kITTremor]) { if(param && !m_SongFlags[SONG_ITOLDEFFECTS]) { // Old effects have different length interpretation (+1 for both on and off) if(param & 0xF0) param -= 0x10; if(param & 0x0F) param -= 0x01; } pChn->nTremorCount |= 0x80; // set on/off flag } else if(m_playBehaviour[kFT2Tremor]) { // XM Tremor. Logic is being processed in sndmix.cpp pChn->nTremorCount |= 0x80; // set on/off flag } pChn->nCommand = CMD_TREMOR; if (param) pChn->nTremorParam = static_cast<ModCommand::PARAM>(param); break; // Set Global Volume case CMD_GLOBALVOLUME: // IT compatibility: Only apply global volume on first tick (and multiples) // Test case: GlobalVolFirstTick.it if(!m_SongFlags[SONG_FIRSTTICK]) break; // ST3 applies global volume on tick 1 and does other weird things, but we won't emulate this for now. // if(((GetType() & MOD_TYPE_S3M) && m_nTickCount != 1) // || (!(GetType() & MOD_TYPE_S3M) && !m_SongFlags[SONG_FIRSTTICK])) // { // break; // } // FT2 compatibility: On channels that are "left" of the global volume command, the new global volume is not applied // until the second tick of the row. Since we apply global volume on the mix buffer rather than note volumes, this // cannot be fixed for now. // Test case: GlobalVolume.xm // if(IsCompatibleMode(TRK_FASTTRACKER2) && m_SongFlags[SONG_FIRSTTICK] && m_nMusicSpeed > 1) // { // break; // } if (!(GetType() & GLOBALVOL_7BIT_FORMATS)) param *= 2; // IT compatibility 16. ST3 and IT ignore out-of-range values. // Test case: globalvol-invalid.it if(param <= 128) { m_PlayState.m_nGlobalVolume = param * 2; } else if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_S3M))) { m_PlayState.m_nGlobalVolume = 256; } break; // Global Volume Slide case CMD_GLOBALVOLSLIDE: //IT compatibility 16. Saving last global volume slide param per channel (FT2/IT) if(m_playBehaviour[kPerChannelGlobalVolSlide]) GlobalVolSlide(static_cast<ModCommand::PARAM>(param), pChn->nOldGlobalVolSlide); else GlobalVolSlide(static_cast<ModCommand::PARAM>(param), m_PlayState.Chn[0].nOldGlobalVolSlide); break; // Set 8-bit Panning case CMD_PANNING8: if(m_SongFlags[SONG_FIRSTTICK]) { Panning(pChn, param, Pan8bit); } break; // Panning Slide case CMD_PANNINGSLIDE: PanningSlide(pChn, static_cast<ModCommand::PARAM>(param)); break; // Tremolo case CMD_TREMOLO: Tremolo(pChn, param); break; // Fine Vibrato case CMD_FINEVIBRATO: FineVibrato(pChn, param); break; // MOD/XM Exx Extended Commands case CMD_MODCMDEX: ExtendedMODCommands(nChn, static_cast<ModCommand::PARAM>(param)); break; // S3M/IT Sxx Extended Commands case CMD_S3MCMDEX: if(m_playBehaviour[kST3EffectMemory] && param == 0) { param = pChn->nArpeggio; // S00 uses the last non-zero effect parameter as memory, like other effects including Arpeggio, so we "borrow" our memory there. } ExtendedS3MCommands(nChn, static_cast<ModCommand::PARAM>(param)); break; // Key Off case CMD_KEYOFF: // This is how Key Off is supposed to sound... (in FT2 at least) if(m_playBehaviour[kFT2KeyOff]) { if (m_PlayState.m_nTickCount == param) { // XM: Key-Off + Sample == Note Cut if(pChn->pModInstrument == nullptr || !pChn->pModInstrument->VolEnv.dwFlags[ENV_ENABLED]) { if(param == 0 && (pChn->rowCommand.instr || pChn->rowCommand.volcmd != VOLCMD_NONE)) // FT2 is weird.... { pChn->dwFlags.set(CHN_NOTEFADE); } else { pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->nVolume = 0; } } KeyOff(pChn); } } // This is how it's NOT supposed to sound... else { if(m_SongFlags[SONG_FIRSTTICK]) KeyOff(pChn); } break; // Extra-fine porta up/down case CMD_XFINEPORTAUPDOWN: switch(param & 0xF0) { case 0x10: ExtraFinePortamentoUp(pChn, param & 0x0F); break; case 0x20: ExtraFinePortamentoDown(pChn, param & 0x0F); break; // ModPlug XM Extensions (ignore in compatible mode) case 0x50: case 0x60: case 0x70: case 0x90: case 0xA0: if(!m_playBehaviour[kFT2RestrictXCommand]) ExtendedS3MCommands(nChn, static_cast<ModCommand::PARAM>(param)); break; } break; // Set Channel Global Volume case CMD_CHANNELVOLUME: if(!m_SongFlags[SONG_FIRSTTICK]) break; if (param <= 64) { pChn->nGlobalVol = param; pChn->dwFlags.set(CHN_FASTVOLRAMP); } break; // Channel volume slide case CMD_CHANNELVOLSLIDE: ChannelVolSlide(pChn, static_cast<ModCommand::PARAM>(param)); break; // Panbrello (IT) case CMD_PANBRELLO: Panbrello(pChn, param); break; // Set Envelope Position case CMD_SETENVPOSITION: if(m_SongFlags[SONG_FIRSTTICK]) { pChn->VolEnv.nEnvPosition = param; // FT2 compatibility: FT2 only sets the position of the panning envelope if the volume envelope's sustain flag is set // Test case: SetEnvPos.xm if(!m_playBehaviour[kFT2SetPanEnvPos] || pChn->VolEnv.flags[ENV_SUSTAIN]) { pChn->PanEnv.nEnvPosition = param; pChn->PitchEnv.nEnvPosition = param; } } break; // Position Jump case CMD_POSITIONJUMP: m_PlayState.m_nNextPatStartRow = 0; // FT2 E60 bug nPosJump = static_cast<ORDERINDEX>(CalculateXParam(m_PlayState.m_nPattern, m_PlayState.m_nRow, nChn)); // see https://forum.openmpt.org/index.php?topic=2769.0 - FastTracker resets Dxx if Bxx is called _after_ Dxx // Test case: PatternJump.mod if((GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM)) && nBreakRow != ROWINDEX_INVALID) { nBreakRow = 0; } break; // Pattern Break case CMD_PATTERNBREAK: { ROWINDEX row = PatternBreak(m_PlayState, nChn, static_cast<ModCommand::PARAM>(param)); if(row != ROWINDEX_INVALID) { nBreakRow = row; if(m_SongFlags[SONG_PATTERNLOOP]) { //If song is set to loop and a pattern break occurs we should stay on the same pattern. //Use nPosJump to force playback to "jump to this pattern" rather than move to next, as by default. //rewbs.to nPosJump = m_PlayState.m_nCurrentOrder; } } } break; // IMF / PTM Note Slides case CMD_NOTESLIDEUP: case CMD_NOTESLIDEDOWN: case CMD_NOTESLIDEUPRETRIG: case CMD_NOTESLIDEDOWNRETRIG: // Note that this command seems to be a bit buggy in Polytracker... Luckily, no tune seems to seriously use this // (Vic uses it e.g. in Spaceman or Perfect Reason to slide effect samples, noone will notice the difference :) NoteSlide(pChn, param, cmd == CMD_NOTESLIDEUP || cmd == CMD_NOTESLIDEUPRETRIG, cmd == CMD_NOTESLIDEUPRETRIG || cmd == CMD_NOTESLIDEDOWNRETRIG); break; // PTM Reverse sample + offset (executed on every tick) case CMD_REVERSEOFFSET: ReverseSampleOffset(*pChn, static_cast<ModCommand::PARAM>(param)); break; #ifndef NO_PLUGINS // DBM: Toggle DSP Echo case CMD_DBMECHO: if(m_PlayState.m_nTickCount == 0) { uint32 chns = (param >> 4), enable = (param & 0x0F); if(chns > 1 || enable > 2) { break; } CHANNELINDEX firstChn = nChn, lastChn = nChn; if(chns == 1) { firstChn = 0; lastChn = m_nChannels - 1; } for(CHANNELINDEX c = firstChn; c <= lastChn; c++) { ChnSettings[c].dwFlags.set(CHN_NOFX, enable == 1); m_PlayState.Chn[c].dwFlags.set(CHN_NOFX, enable == 1); } } break; #endif // NO_PLUGINS } if(m_playBehaviour[kST3EffectMemory] && param != 0) { UpdateS3MEffectMemory(pChn, static_cast<ModCommand::PARAM>(param)); } if(pChn->rowCommand.instr) { // Not necessarily consistent with actually playing instrument for IT compatibility pChn->nOldIns = pChn->rowCommand.instr; } } // for(...) end // Navigation Effects if(m_SongFlags[SONG_FIRSTTICK]) { const bool doPatternLoop = (nPatLoopRow != ROWINDEX_INVALID); const bool doBreakRow = (nBreakRow != ROWINDEX_INVALID); const bool doPosJump = (nPosJump != ORDERINDEX_INVALID); // Pattern Loop if(doPatternLoop) { m_PlayState.m_nNextOrder = m_PlayState.m_nCurrentOrder; m_PlayState.m_nNextRow = nPatLoopRow; if(m_PlayState.m_nPatternDelay) { m_PlayState.m_nNextRow++; } // IT Compatibility: If the restart row is past the end of the current pattern // (e.g. when continued from a previous pattern without explicit SB0 effect), continue the next pattern. // Test case: LoopStartAfterPatternEnd.it if(nPatLoopRow >= Patterns[m_PlayState.m_nPattern].GetNumRows()) { m_PlayState.m_nNextOrder++; m_PlayState.m_nNextRow = 0; } // As long as the pattern loop is running, mark the looped rows as not visited yet visitedSongRows.ResetPatternLoop(m_PlayState.m_nCurrentOrder, nPatLoopRow); } // Pattern Break / Position Jump only if no loop running // Exception: FastTracker 2 in all cases, Impulse Tracker in case of position jump // Test case for FT2 exception: PatLoop-Jumps.xm, PatLoop-Various.xm // Test case for IT: exception: LoopBreak.it if((doBreakRow || doPosJump) && (!doPatternLoop || m_playBehaviour[kFT2PatternLoopWithJumps] || (m_playBehaviour[kITPatternLoopWithJumps] && doPosJump))) { if(!doPosJump) nPosJump = m_PlayState.m_nCurrentOrder + 1; if(!doBreakRow) nBreakRow = 0; m_SongFlags.set(SONG_BREAKTOROW); if(nPosJump >= Order().size()) { nPosJump = Order().GetRestartPos(); } // IT / FT2 compatibility: don't reset loop count on pattern break. // Test case: gm-trippy01.it, PatLoop-Break.xm, PatLoop-Weird.xm, PatLoop-Break.mod if(nPosJump != m_PlayState.m_nCurrentOrder && !m_playBehaviour[kITPatternLoopBreak] && !m_playBehaviour[kFT2PatternLoopWithJumps] && GetType() != MOD_TYPE_MOD) { for(CHANNELINDEX i = 0; i < GetNumChannels(); i++) { m_PlayState.Chn[i].nPatternLoopCount = 0; } } m_PlayState.m_nNextRow = nBreakRow; if(!m_SongFlags[SONG_PATTERNLOOP]) m_PlayState.m_nNextOrder = nPosJump; } } return true; } //////////////////////////////////////////////////////////// // Channels effects // Update the effect memory of all S3M effects that use the last non-zero effect parameter as memory (Dxy, Exx, Fxx, Ixy, Jxy, Kxy, Lxy, Qxy, Rxy, Sxy) // Test case: ParamMemory.s3m void CSoundFile::UpdateS3MEffectMemory(ModChannel *pChn, ModCommand::PARAM param) const { pChn->nOldVolumeSlide = param; // Dxy / Kxy / Lxy pChn->nOldPortaUp = param; // Exx / Fxx pChn->nOldPortaDown = param; // Exx / Fxx pChn->nTremorParam = param; // Ixy pChn->nArpeggio = param; // Jxy pChn->nRetrigParam = param; // Qxy pChn->nTremoloDepth = (param & 0x0F) << 2; // Rxy pChn->nTremoloSpeed = (param >> 4) & 0x0F; // Rxy // Sxy is not handled here. } // Calculate full parameter for effects that support parameter extension at the given pattern location. // maxCommands sets the maximum number of XParam commands to look at for this effect // isExtended returns if the command is actually using any XParam extensions. uint32 CSoundFile::CalculateXParam(PATTERNINDEX pat, ROWINDEX row, CHANNELINDEX chn, bool *isExtended) const { if(isExtended != nullptr) *isExtended = false; ROWINDEX maxCommands = 4; const ModCommand *m = Patterns[pat].GetpModCommand(row, chn); uint32 val = m->param; switch(m->command) { case CMD_OFFSET: // 24 bit command maxCommands = 2; break; case CMD_TEMPO: case CMD_PATTERNBREAK: case CMD_POSITIONJUMP: // 16 bit command maxCommands = 1; break; default: return val; } const bool xmTempoFix = m->command == CMD_TEMPO && GetType() == MOD_TYPE_XM; ROWINDEX numRows = std::min(Patterns[pat].GetNumRows() - row - 1, maxCommands); while(numRows > 0) { m += Patterns[pat].GetNumChannels(); if(m->command != CMD_XPARAM) { break; } if(xmTempoFix && val < 256) { // With XM, 0x20 is the lowest tempo. Anything below changes ticks per row. val -= 0x20; } val = (val << 8) | m->param; numRows--; if(isExtended != nullptr) *isExtended = true; } return val; } ROWINDEX CSoundFile::PatternBreak(PlayState &state, CHANNELINDEX chn, uint8 param) const { if(param >= 64 && (GetType() & MOD_TYPE_S3M)) { // ST3 ignores invalid pattern breaks. return ROWINDEX_INVALID; } state.m_nNextPatStartRow = 0; // FT2 E60 bug return static_cast<ROWINDEX>(CalculateXParam(state.m_nPattern, state.m_nRow, chn)); } void CSoundFile::PortamentoUp(CHANNELINDEX nChn, ModCommand::PARAM param, const bool doFinePortamentoAsRegular) { ModChannel *pChn = &m_PlayState.Chn[nChn]; if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaDown = param; pChn->nOldPortaUp = param; } else { param = pChn->nOldPortaUp; } const bool doFineSlides = !doFinePortamentoAsRegular && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_AMF0 | MOD_TYPE_DIGI | MOD_TYPE_STP | MOD_TYPE_DTM)); // Process MIDI pitch bend for instrument plugins MidiPortamento(nChn, param, doFineSlides); if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning) { // Portamento for instruments with custom tuning if(param >= 0xF0 && !doFinePortamentoAsRegular) PortamentoFineMPT(pChn, param - 0xF0); else if(param >= 0xE0 && !doFinePortamentoAsRegular) PortamentoExtraFineMPT(pChn, param - 0xE0); else PortamentoMPT(pChn, param); return; } else if(GetType() == MOD_TYPE_PLM) { // A normal portamento up or down makes a follow-up tone portamento go the same direction. pChn->nPortamentoDest = 1; } if (doFineSlides && param >= 0xE0) { if (param & 0x0F) { if ((param & 0xF0) == 0xF0) { FinePortamentoUp(pChn, param & 0x0F); return; } else if ((param & 0xF0) == 0xE0 && GetType() != MOD_TYPE_DBM) { ExtraFinePortamentoUp(pChn, param & 0x0F); return; } } if(GetType() != MOD_TYPE_DBM) { // DBM only has fine slides, no extra-fine slides. return; } } // Regular Slide if(!pChn->isFirstTick || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]) || GetType() == MOD_TYPE_669) { DoFreqSlide(pChn, -int(param) * 4); } } void CSoundFile::PortamentoDown(CHANNELINDEX nChn, ModCommand::PARAM param, const bool doFinePortamentoAsRegular) { ModChannel *pChn = &m_PlayState.Chn[nChn]; if(param) { // FT2 compatibility: Separate effect memory for all portamento commands // Test case: Porta-LinkMem.xm if(!m_playBehaviour[kFT2PortaUpDownMemory]) pChn->nOldPortaUp = param; pChn->nOldPortaDown = param; } else { param = pChn->nOldPortaDown; } const bool doFineSlides = !doFinePortamentoAsRegular && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_AMF0 | MOD_TYPE_DIGI | MOD_TYPE_STP | MOD_TYPE_DTM)); // Process MIDI pitch bend for instrument plugins MidiPortamento(nChn, -static_cast<int>(param), doFineSlides); if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning) { // Portamento for instruments with custom tuning if(param >= 0xF0 && !doFinePortamentoAsRegular) PortamentoFineMPT(pChn, -static_cast<int>(param - 0xF0)); else if(param >= 0xE0 && !doFinePortamentoAsRegular) PortamentoExtraFineMPT(pChn, -static_cast<int>(param - 0xE0)); else PortamentoMPT(pChn, -static_cast<int>(param)); return; } else if(GetType() == MOD_TYPE_PLM) { // A normal portamento up or down makes a follow-up tone portamento go the same direction. pChn->nPortamentoDest = 65535; } if(doFineSlides && param >= 0xE0) { if (param & 0x0F) { if ((param & 0xF0) == 0xF0) { FinePortamentoDown(pChn, param & 0x0F); return; } else if ((param & 0xF0) == 0xE0 && GetType() != MOD_TYPE_DBM) { ExtraFinePortamentoDown(pChn, param & 0x0F); return; } } if(GetType() != MOD_TYPE_DBM) { // DBM only has fine slides, no extra-fine slides. return; } } if(!pChn->isFirstTick || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]) || GetType() == MOD_TYPE_669) { DoFreqSlide(pChn, int(param) * 4); } } // Send portamento commands to plugins void CSoundFile::MidiPortamento(CHANNELINDEX nChn, int param, bool doFineSlides) { int actualParam = mpt::abs(param); int pitchBend = 0; // Old MIDI Pitch Bends: // - Applied on every tick // - No fine pitch slides (they are interpreted as normal slides) // New MIDI Pitch Bends: // - Behaviour identical to sample pitch bends if the instrument's PWD parameter corresponds to the actual VSTi setting. if(doFineSlides && actualParam >= 0xE0 && !m_playBehaviour[kOldMIDIPitchBends]) { if(m_PlayState.Chn[nChn].isFirstTick) { // Extra fine slide... pitchBend = (actualParam & 0x0F) * sgn(param); if(actualParam >= 0xF0) { // ... or just a fine slide! pitchBend *= 4; } } } else if(!m_PlayState.Chn[nChn].isFirstTick || m_playBehaviour[kOldMIDIPitchBends]) { // Regular slide pitchBend = param * 4; } if(pitchBend) { #ifndef NO_PLUGINS IMixPlugin *plugin = GetChannelInstrumentPlugin(nChn); if(plugin != nullptr) { int8 pwd = 13; // Early OpenMPT legacy... Actually it's not *exactly* 13, but close enough... if(m_PlayState.Chn[nChn].pModInstrument != nullptr) { pwd = m_PlayState.Chn[nChn].pModInstrument->midiPWD; } plugin->MidiPitchBend(GetBestMidiChannel(nChn), pitchBend, pwd); } #endif // NO_PLUGINS } } void CSoundFile::FinePortamentoUp(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldFinePortaUpDown = (pChn->nOldFinePortaUpDown & 0x0F) | (param << 4); else param = (pChn->nOldFinePortaUpDown >> 4); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { const auto oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideUpTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) { if(m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod < Util::MaxValueOfType(pChn->nPeriod)) pChn->nPeriod++; else if(!m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod > 1) pChn->nPeriod--; } } else { pChn->nPeriod -= (int)(param * 4); if (pChn->nPeriod < 1) { pChn->nPeriod = 1; if(GetType() == MOD_TYPE_S3M) { pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } } } } void CSoundFile::FinePortamentoDown(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldFinePortaUpDown = (pChn->nOldFinePortaUpDown & 0xF0) | (param & 0x0F); else param = (pChn->nOldFinePortaUpDown & 0x0F); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if (m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { const auto oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetLinearSlideDownTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) { if(!m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod < Util::MaxValueOfType(pChn->nPeriod)) pChn->nPeriod++; else if(m_playBehaviour[kHertzInLinearMode] && pChn->nPeriod > 1) pChn->nPeriod--; } } else { pChn->nPeriod += (int)(param * 4); if (pChn->nPeriod > 0xFFFF) pChn->nPeriod = 0xFFFF; } } } } void CSoundFile::ExtraFinePortamentoUp(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldExtraFinePortaUpDown = (pChn->nOldExtraFinePortaUpDown & 0x0F) | (param << 4); else param = (pChn->nOldExtraFinePortaUpDown >> 4); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { int oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetFineLinearSlideUpTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) pChn->nPeriod++; } else { pChn->nPeriod -= (int)(param); if (pChn->nPeriod < 1) { pChn->nPeriod = 1; if(GetType() == MOD_TYPE_S3M) { pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } } } } void CSoundFile::ExtraFinePortamentoDown(ModChannel *pChn, ModCommand::PARAM param) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: E1x / E2x / X1x / X2x memory is not linked // Test case: Porta-LinkMem.xm if(param) pChn->nOldExtraFinePortaUpDown = (pChn->nOldExtraFinePortaUpDown & 0xF0) | (param & 0x0F); else param = (pChn->nOldExtraFinePortaUpDown & 0x0F); } else if(GetType() == MOD_TYPE_MT2) { if(param) pChn->nOldFinePortaUpDown = param; else param = pChn->nOldFinePortaUpDown; } if(pChn->isFirstTick) { if ((pChn->nPeriod) && (param)) { if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { int oldPeriod = pChn->nPeriod; pChn->nPeriod = Util::muldivr(pChn->nPeriod, GetFineLinearSlideDownTable(this, param & 0x0F), 65536); if(oldPeriod == pChn->nPeriod) pChn->nPeriod--; } else { pChn->nPeriod += (int)(param); if (pChn->nPeriod > 0xFFFF) pChn->nPeriod = 0xFFFF; } } } } // Implemented for IMF compatibility, can't actually save this in any formats // Slide up / down every x ticks by y semitones void CSoundFile::NoteSlide(ModChannel *pChn, uint32 param, bool slideUp, bool retrig) const { uint8 x, y; if(m_SongFlags[SONG_FIRSTTICK]) { x = param & 0xF0; if (x) pChn->nNoteSlideSpeed = (x >> 4); y = param & 0x0F; if (y) pChn->nNoteSlideStep = y; pChn->nNoteSlideCounter = pChn->nNoteSlideSpeed; } else { if (--pChn->nNoteSlideCounter == 0) { pChn->nNoteSlideCounter = pChn->nNoteSlideSpeed; // update it pChn->nPeriod = GetPeriodFromNote ((slideUp ? 1 : -1) * pChn->nNoteSlideStep + GetNoteFromPeriod(pChn->nPeriod), 8363, 0); if(retrig) { pChn->position.Set(0); } } } } // Portamento Slide void CSoundFile::TonePortamento(ModChannel *pChn, uint32 param) const { pChn->dwFlags.set(CHN_PORTAMENTO); //IT compatibility 03: Share effect memory with portamento up/down if((!m_SongFlags[SONG_ITCOMPATGXX] && m_playBehaviour[kITPortaMemoryShare]) || GetType() == MOD_TYPE_PLM) { if(param == 0) param = pChn->nOldPortaUp; pChn->nOldPortaUp = pChn->nOldPortaDown = static_cast<uint8>(param); } if(GetType() == MOD_TYPE_MPT && pChn->pModInstrument && pChn->pModInstrument->pTuning) { //Behavior: Param tells number of finesteps(or 'fullsteps'(notes) with glissando) //to slide per row(not per tick). const int32 old_PortamentoTickSlide = (m_PlayState.m_nTickCount != 0) ? pChn->m_PortamentoTickSlide : 0; if(param) pChn->nPortamentoSlide = param; else if(pChn->nPortamentoSlide == 0) return; if((pChn->nPortamentoDest > 0 && pChn->nPortamentoSlide < 0) || (pChn->nPortamentoDest < 0 && pChn->nPortamentoSlide > 0)) pChn->nPortamentoSlide = -pChn->nPortamentoSlide; pChn->m_PortamentoTickSlide = static_cast<int32>((m_PlayState.m_nTickCount + 1.0) * pChn->nPortamentoSlide / m_PlayState.m_nMusicSpeed); if(pChn->dwFlags[CHN_GLISSANDO]) { pChn->m_PortamentoTickSlide *= pChn->pModInstrument->pTuning->GetFineStepCount() + 1; //With glissando interpreting param as notes instead of finesteps. } const int32 slide = pChn->m_PortamentoTickSlide - old_PortamentoTickSlide; if(mpt::abs(pChn->nPortamentoDest) <= mpt::abs(slide)) { if(pChn->nPortamentoDest != 0) { pChn->m_PortamentoFineSteps += pChn->nPortamentoDest; pChn->nPortamentoDest = 0; pChn->m_CalculateFreq = true; } } else { pChn->m_PortamentoFineSteps += slide; pChn->nPortamentoDest -= slide; pChn->m_CalculateFreq = true; } return; } //End candidate MPT behavior. bool doPorta = !pChn->isFirstTick || (GetType() & (MOD_TYPE_DBM | MOD_TYPE_669)) || (m_PlayState.m_nMusicSpeed == 1 && m_playBehaviour[kSlidesAtSpeed1]); if(GetType() == MOD_TYPE_PLM && param >= 0xF0) { param -= 0xF0; doPorta = pChn->isFirstTick; } if(param) { if(GetType() == MOD_TYPE_669) { param *= 10; } pChn->nPortamentoSlide = param * 4; } if(pChn->nPeriod && pChn->nPortamentoDest && doPorta) { if (pChn->nPeriod < pChn->nPortamentoDest) { int32 delta = pChn->nPortamentoSlide; if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { uint32 n = pChn->nPortamentoSlide / 4; if (n > 255) n = 255; // Return (a*b+c/2)/c - no divide error // Table is 65536*2(n/192) delta = Util::muldivr(pChn->nPeriod, LinearSlideUpTable[n], 65536) - pChn->nPeriod; if (delta < 1) delta = 1; } pChn->nPeriod += delta; if (pChn->nPeriod > pChn->nPortamentoDest) pChn->nPeriod = pChn->nPortamentoDest; } else if (pChn->nPeriod > pChn->nPortamentoDest) { int32 delta = -pChn->nPortamentoSlide; if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { uint32 n = pChn->nPortamentoSlide / 4; if (n > 255) n = 255; delta = Util::muldivr(pChn->nPeriod, LinearSlideDownTable[n], 65536) - pChn->nPeriod; if (delta > -1) delta = -1; } pChn->nPeriod += delta; if (pChn->nPeriod < pChn->nPortamentoDest) pChn->nPeriod = pChn->nPortamentoDest; } } // IT compatibility 23. Portamento with no note // ProTracker also disables portamento once the target is reached. // Test case: PortaTarget.mod if(pChn->nPeriod == pChn->nPortamentoDest && (m_playBehaviour[kITPortaTargetReached] || GetType() == MOD_TYPE_MOD)) pChn->nPortamentoDest = 0; } void CSoundFile::Vibrato(ModChannel *p, uint32 param) const { if (param & 0x0F) p->nVibratoDepth = (param & 0x0F) * 4; if (param & 0xF0) p->nVibratoSpeed = (param >> 4) & 0x0F; p->dwFlags.set(CHN_VIBRATO); } void CSoundFile::FineVibrato(ModChannel *p, uint32 param) const { if (param & 0x0F) p->nVibratoDepth = param & 0x0F; if (param & 0xF0) p->nVibratoSpeed = (param >> 4) & 0x0F; p->dwFlags.set(CHN_VIBRATO); // ST3 compatibility: Do not distinguish between vibrato types in effect memory // Test case: VibratoTypeChange.s3m if(m_playBehaviour[kST3VibratoMemory] && (param & 0x0F)) { p->nVibratoDepth *= 4u; } } void CSoundFile::Panbrello(ModChannel *p, uint32 param) const { if (param & 0x0F) p->nPanbrelloDepth = param & 0x0F; if (param & 0xF0) p->nPanbrelloSpeed = (param >> 4) & 0x0F; } void CSoundFile::Panning(ModChannel *pChn, uint32 param, PanningType panBits) const { // No panning in ProTracker mode if(m_playBehaviour[kMODIgnorePanning]) { return; } // IT Compatibility (and other trackers as well): panning disables surround (unless panning in rear channels is enabled, which is not supported by the original trackers anyway) if (!m_SongFlags[SONG_SURROUNDPAN] && (panBits == Pan8bit || m_playBehaviour[kPanOverride])) { pChn->dwFlags.reset(CHN_SURROUND); } if(panBits == Pan4bit) { // 0...15 panning pChn->nPan = (param * 256 + 8) / 15; } else if(panBits == Pan6bit) { // 0...64 panning if(param > 64) param = 64; pChn->nPan = param * 4; } else { if(!(GetType() & (MOD_TYPE_S3M | MOD_TYPE_DSM | MOD_TYPE_AMF | MOD_TYPE_MTM))) { // Real 8-bit panning pChn->nPan = param; } else { // 7-bit panning + surround if(param <= 0x80) { pChn->nPan = param << 1; } else if(param == 0xA4) { pChn->dwFlags.set(CHN_SURROUND); pChn->nPan = 0x80; } } } pChn->dwFlags.set(CHN_FASTVOLRAMP); pChn->nRestorePanOnNewNote = 0; //IT compatibility 20. Set pan overrides random pan if(m_playBehaviour[kPanOverride]) { pChn->nPanSwing = 0; pChn->nPanbrelloOffset = 0; } } void CSoundFile::VolumeSlide(ModChannel *pChn, ModCommand::PARAM param) { if (param) pChn->nOldVolumeSlide = param; else param = pChn->nOldVolumeSlide; if((GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MED | MOD_TYPE_DIGI | MOD_TYPE_STP | MOD_TYPE_DTM))) { // MOD / XM nibble priority if((param & 0xF0) != 0) { param &= 0xF0; } else { param &= 0x0F; } } int newvolume = pChn->nVolume; if(!(GetType() & (MOD_TYPE_MOD | MOD_TYPE_XM | MOD_TYPE_AMF0 | MOD_TYPE_MED | MOD_TYPE_DIGI))) { if ((param & 0x0F) == 0x0F) //Fine upslide or slide -15 { if (param & 0xF0) //Fine upslide { FineVolumeUp(pChn, (param >> 4), false); return; } else //Slide -15 { if(pChn->isFirstTick && !m_SongFlags[SONG_FASTVOLSLIDES]) { newvolume -= 0x0F * 4; } } } else if ((param & 0xF0) == 0xF0) //Fine downslide or slide +15 { if (param & 0x0F) //Fine downslide { FineVolumeDown(pChn, (param & 0x0F), false); return; } else //Slide +15 { if(pChn->isFirstTick && !m_SongFlags[SONG_FASTVOLSLIDES]) { newvolume += 0x0F * 4; } } } } if(!pChn->isFirstTick || m_SongFlags[SONG_FASTVOLSLIDES] || (m_PlayState.m_nMusicSpeed == 1 && GetType() == MOD_TYPE_DBM)) { // IT compatibility: Ignore slide commands with both nibbles set. if (param & 0x0F) { if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (param & 0xF0) == 0) newvolume -= (int)((param & 0x0F) * 4); } else { newvolume += (int)((param & 0xF0) >> 2); } if (GetType() == MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP); } newvolume = Clamp(newvolume, 0, 256); pChn->nVolume = newvolume; } void CSoundFile::PanningSlide(ModChannel *pChn, ModCommand::PARAM param, bool memory) { if(memory) { // FT2 compatibility: Use effect memory (lxx and rxx in XM shouldn't use effect memory). // Test case: PanSlideMem.xm if(param) pChn->nOldPanSlide = param; else param = pChn->nOldPanSlide; } if((GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { // XM nibble priority if((param & 0xF0) != 0) { param &= 0xF0; } else { param &= 0x0F; } } int32 nPanSlide = 0; if(!(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { if(m_SongFlags[SONG_FIRSTTICK]) { param = (param & 0xF0) / 4u; nPanSlide = - (int)param; } } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { if(m_SongFlags[SONG_FIRSTTICK]) { nPanSlide = (param & 0x0F) * 4u; } } else if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0x0F) { // IT compatibility: Ignore slide commands with both nibbles set. if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) || (param & 0xF0) == 0) nPanSlide = (int)((param & 0x0F) * 4u); } else { nPanSlide = -(int)((param & 0xF0) / 4u); } } } else { if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0xF0) { nPanSlide = (int)((param & 0xF0) / 4u); } else { nPanSlide = -(int)((param & 0x0F) * 4u); } // FT2 compatibility: FT2's panning slide is like IT's fine panning slide (not as deep) if(m_playBehaviour[kFT2PanSlide]) nPanSlide /= 4; } } if (nPanSlide) { nPanSlide += pChn->nPan; nPanSlide = Clamp(nPanSlide, 0, 256); pChn->nPan = nPanSlide; pChn->nRestorePanOnNewNote = 0; } } void CSoundFile::FineVolumeUp(ModChannel *pChn, ModCommand::PARAM param, bool volCol) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: EAx / EBx memory is not linked // Test case: FineVol-LinkMem.xm if(param) pChn->nOldFineVolUpDown = (param << 4) | (pChn->nOldFineVolUpDown & 0x0F); else param = (pChn->nOldFineVolUpDown >> 4); } else if(volCol) { if(param) pChn->nOldVolParam = param; else param = pChn->nOldVolParam; } else { if(param) pChn->nOldFineVolUpDown = param; else param = pChn->nOldFineVolUpDown; } if(pChn->isFirstTick) { pChn->nVolume += param * 4; if(pChn->nVolume > 256) pChn->nVolume = 256; if(GetType() & MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP); } } void CSoundFile::FineVolumeDown(ModChannel *pChn, ModCommand::PARAM param, bool volCol) const { if(GetType() == MOD_TYPE_XM) { // FT2 compatibility: EAx / EBx memory is not linked // Test case: FineVol-LinkMem.xm if(param) pChn->nOldFineVolUpDown = param | (pChn->nOldFineVolUpDown & 0xF0); else param = (pChn->nOldFineVolUpDown & 0x0F); } else if(volCol) { if(param) pChn->nOldVolParam = param; else param = pChn->nOldVolParam; } else { if(param) pChn->nOldFineVolUpDown = param; else param = pChn->nOldFineVolUpDown; } if(pChn->isFirstTick) { pChn->nVolume -= param * 4; if(pChn->nVolume < 0) pChn->nVolume = 0; if(GetType() & MOD_TYPE_MOD) pChn->dwFlags.set(CHN_FASTVOLRAMP); } } void CSoundFile::Tremolo(ModChannel *pChn, uint32 param) const { if (param & 0x0F) pChn->nTremoloDepth = (param & 0x0F) << 2; if (param & 0xF0) pChn->nTremoloSpeed = (param >> 4) & 0x0F; pChn->dwFlags.set(CHN_TREMOLO); } void CSoundFile::ChannelVolSlide(ModChannel *pChn, ModCommand::PARAM param) const { int32 nChnSlide = 0; if (param) pChn->nOldChnVolSlide = param; else param = pChn->nOldChnVolSlide; if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { if(m_SongFlags[SONG_FIRSTTICK]) nChnSlide = param >> 4; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { if(m_SongFlags[SONG_FIRSTTICK]) nChnSlide = - (int)(param & 0x0F); } else { if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0x0F) { if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_J2B | MOD_TYPE_DBM)) || (param & 0xF0) == 0) nChnSlide = -(int)(param & 0x0F); } else { nChnSlide = (int)((param & 0xF0) >> 4); } } } if (nChnSlide) { nChnSlide += pChn->nGlobalVol; nChnSlide = Clamp(nChnSlide, 0, 64); pChn->nGlobalVol = nChnSlide; } } void CSoundFile::ExtendedMODCommands(CHANNELINDEX nChn, ModCommand::PARAM param) { ModChannel *pChn = &m_PlayState.Chn[nChn]; uint8 command = param & 0xF0; param &= 0x0F; switch(command) { // E0x: Set Filter case 0x00: for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { m_PlayState.Chn[chn].dwFlags.set(CHN_AMIGAFILTER, !(param & 1)); } break; // E1x: Fine Portamento Up case 0x10: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoUp(pChn, param); break; // E2x: Fine Portamento Down case 0x20: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FinePortamentoDown(pChn, param); break; // E3x: Set Glissando Control case 0x30: pChn->dwFlags.set(CHN_GLISSANDO, param != 0); break; // E4x: Set Vibrato WaveForm case 0x40: pChn->nVibratoType = param & 0x07; break; // E5x: Set FineTune case 0x50: if(!m_SongFlags[SONG_FIRSTTICK]) { break; } if(GetType() & (MOD_TYPE_MOD | MOD_TYPE_DIGI | MOD_TYPE_AMF0 | MOD_TYPE_MED)) { pChn->nFineTune = MOD2XMFineTune(param); if(pChn->nPeriod && pChn->rowCommand.IsNote()) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed); } else if(pChn->rowCommand.IsNote()) { pChn->nFineTune = MOD2XMFineTune(param - 8); if(pChn->nPeriod) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed); } break; // E6x: Pattern Loop // E7x: Set Tremolo WaveForm case 0x70: pChn->nTremoloType = param & 0x07; break; // E8x: Set 4-bit Panning case 0x80: if(m_SongFlags[SONG_FIRSTTICK]) { Panning(pChn, param, Pan4bit); } break; // E9x: Retrig case 0x90: RetrigNote(nChn, param); break; // EAx: Fine Volume Up case 0xA0: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeUp(pChn, param, false); break; // EBx: Fine Volume Down case 0xB0: if ((param) || (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2))) FineVolumeDown(pChn, param, false); break; // ECx: Note Cut case 0xC0: NoteCut(nChn, param, false); break; // EDx: Note Delay // EEx: Pattern Delay case 0xF0: if(GetType() == MOD_TYPE_MOD) // MOD: Invert Loop { pChn->nEFxSpeed = param; if(m_SongFlags[SONG_FIRSTTICK]) InvertLoop(pChn); } else // XM: Set Active Midi Macro { pChn->nActiveMacro = param; } break; } } void CSoundFile::ExtendedS3MCommands(CHANNELINDEX nChn, ModCommand::PARAM param) { ModChannel *pChn = &m_PlayState.Chn[nChn]; uint8 command = param & 0xF0; param &= 0x0F; switch(command) { // S0x: Set Filter // S1x: Set Glissando Control case 0x10: pChn->dwFlags.set(CHN_GLISSANDO, param != 0); break; // S2x: Set FineTune case 0x20: if(!m_SongFlags[SONG_FIRSTTICK]) break; if(GetType() != MOD_TYPE_669) { pChn->nC5Speed = S3MFineTuneTable[param]; pChn->nFineTune = MOD2XMFineTune(param); if (pChn->nPeriod) pChn->nPeriod = GetPeriodFromNote(pChn->nNote, pChn->nFineTune, pChn->nC5Speed); } else if(pChn->pModSample != nullptr) { pChn->nC5Speed = pChn->pModSample->nC5Speed + param * 80; } break; // S3x: Set Vibrato Waveform case 0x30: if(GetType() == MOD_TYPE_S3M) { pChn->nVibratoType = param & 0x03; } else { // IT compatibility: Ignore waveform types > 3 if(m_playBehaviour[kITVibratoTremoloPanbrello]) pChn->nVibratoType = (param < 0x04) ? param : 0; else pChn->nVibratoType = param & 0x07; } break; // S4x: Set Tremolo Waveform case 0x40: if(GetType() == MOD_TYPE_S3M) { pChn->nTremoloType = param & 0x03; } else { // IT compatibility: Ignore waveform types > 3 if(m_playBehaviour[kITVibratoTremoloPanbrello]) pChn->nTremoloType = (param < 0x04) ? param : 0; else pChn->nTremoloType = param & 0x07; } break; // S5x: Set Panbrello Waveform case 0x50: // IT compatibility: Ignore waveform types > 3 if(m_playBehaviour[kITVibratoTremoloPanbrello]) { pChn->nPanbrelloType = (param < 0x04) ? param : 0; pChn->nPanbrelloPos = 0; } else { pChn->nPanbrelloType = param & 0x07; } break; // S6x: Pattern Delay for x frames case 0x60: if(m_SongFlags[SONG_FIRSTTICK] && m_PlayState.m_nTickCount == 0) { // Tick delays are added up. // Scream Tracker 3 does actually not support this command. // We'll use the same behaviour as for Impulse Tracker, as we can assume that // most S3Ms that make use of this command were made with Impulse Tracker. // MPT added this command to the XM format through the X6x effect, so we will use // the same behaviour here as well. // Test cases: PatternDelays.it, PatternDelays.s3m, PatternDelays.xm m_PlayState.m_nFrameDelay += param; } break; // S7x: Envelope Control / Instrument Control case 0x70: if(!m_SongFlags[SONG_FIRSTTICK]) break; switch(param) { case 0: case 1: case 2: { ModChannel *bkp = &m_PlayState.Chn[m_nChannels]; for (CHANNELINDEX i=m_nChannels; i<MAX_CHANNELS; i++, bkp++) { if (bkp->nMasterChn == nChn+1) { if (param == 1) { KeyOff(bkp); } else if (param == 2) { bkp->dwFlags.set(CHN_NOTEFADE); } else { bkp->dwFlags.set(CHN_NOTEFADE); bkp->nFadeOutVol = 0; } #ifndef NO_PLUGINS const ModInstrument *pIns = bkp->pModInstrument; IMixPlugin *pPlugin; if(pIns != nullptr && pIns->nMixPlug && (pPlugin = m_MixPlugins[pIns->nMixPlug - 1].pMixPlugin) != nullptr) { pPlugin->MidiCommand(GetBestMidiChannel(nChn), pIns->nMidiProgram, pIns->wMidiBank, bkp->nNote + NOTE_MAX_SPECIAL, 0, nChn); } #endif // NO_PLUGINS } } } break; case 3: pChn->nNNA = NNA_NOTECUT; break; case 4: pChn->nNNA = NNA_CONTINUE; break; case 5: pChn->nNNA = NNA_NOTEOFF; break; case 6: pChn->nNNA = NNA_NOTEFADE; break; case 7: pChn->VolEnv.flags.reset(ENV_ENABLED); break; case 8: pChn->VolEnv.flags.set(ENV_ENABLED); break; case 9: pChn->PanEnv.flags.reset(ENV_ENABLED); break; case 10: pChn->PanEnv.flags.set(ENV_ENABLED); break; case 11: pChn->PitchEnv.flags.reset(ENV_ENABLED); break; case 12: pChn->PitchEnv.flags.set(ENV_ENABLED); break; case 13: // S7D: Enable pitch envelope, force to play as pitch envelope case 14: // S7E: Enable pitch envelope, force to play as filter envelope if(GetType() == MOD_TYPE_MPT) { pChn->PitchEnv.flags.set(ENV_ENABLED); pChn->PitchEnv.flags.set(ENV_FILTER, param != 13); } break; } break; // S8x: Set 4-bit Panning case 0x80: if(m_SongFlags[SONG_FIRSTTICK]) { Panning(pChn, param, Pan4bit); } break; // S9x: Sound Control case 0x90: ExtendedChannelEffect(pChn, param); break; // SAx: Set 64k Offset case 0xA0: if(m_SongFlags[SONG_FIRSTTICK]) { pChn->nOldHiOffset = static_cast<uint8>(param); if (!m_playBehaviour[kITHighOffsetNoRetrig] && pChn->rowCommand.IsNote()) { SmpLength pos = param << 16; if (pos < pChn->nLength) pChn->position.SetInt(pos); } } break; // SBx: Pattern Loop // SCx: Note Cut case 0xC0: if(param == 0) { //IT compatibility 22. SC0 == SC1 if(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT)) param = 1; // ST3 doesn't cut notes with SC0 else if(GetType() == MOD_TYPE_S3M) return; } // S3M/IT compatibility: Note Cut really cuts notes and does not just mute them (so that following volume commands could restore the sample) // Test case: scx.it NoteCut(nChn, param, m_playBehaviour[kITSCxStopsSample] || GetType() == MOD_TYPE_S3M); break; // SDx: Note Delay // SEx: Pattern Delay for x rows // SFx: S3M: Not used, IT: Set Active Midi Macro case 0xF0: if(GetType() != MOD_TYPE_S3M) { pChn->nActiveMacro = static_cast<uint8>(param); } break; } } void CSoundFile::ExtendedChannelEffect(ModChannel *pChn, uint32 param) { // S9x and X9x commands (S3M/XM/IT only) if(!m_SongFlags[SONG_FIRSTTICK]) return; switch(param & 0x0F) { // S90: Surround Off case 0x00: pChn->dwFlags.reset(CHN_SURROUND); break; // S91: Surround On case 0x01: pChn->dwFlags.set(CHN_SURROUND); pChn->nPan = 128; break; //////////////////////////////////////////////////////////// // ModPlug Extensions // S98: Reverb Off case 0x08: pChn->dwFlags.reset(CHN_REVERB); pChn->dwFlags.set(CHN_NOREVERB); break; // S99: Reverb On case 0x09: pChn->dwFlags.reset(CHN_NOREVERB); pChn->dwFlags.set(CHN_REVERB); break; // S9A: 2-Channels surround mode case 0x0A: m_SongFlags.reset(SONG_SURROUNDPAN); break; // S9B: 4-Channels surround mode case 0x0B: m_SongFlags.set(SONG_SURROUNDPAN); break; // S9C: IT Filter Mode case 0x0C: m_SongFlags.reset(SONG_MPTFILTERMODE); break; // S9D: MPT Filter Mode case 0x0D: m_SongFlags.set(SONG_MPTFILTERMODE); break; // S9E: Go forward case 0x0E: pChn->dwFlags.reset(CHN_PINGPONGFLAG); break; // S9F: Go backward (and set playback position to the end if sample just started) case 0x0F: if(pChn->position.IsZero() && pChn->nLength && (pChn->rowCommand.IsNote() || !pChn->dwFlags[CHN_LOOP])) { pChn->position.Set(pChn->nLength - 1, SamplePosition::fractMax); } pChn->dwFlags.set(CHN_PINGPONGFLAG); break; } } void CSoundFile::InvertLoop(ModChannel *pChn) { // EFx implementation for MOD files (PT 1.1A and up: Invert Loop) // This effect trashes samples. Thanks to 8bitbubsy for making this work. :) if(GetType() != MOD_TYPE_MOD || pChn->nEFxSpeed == 0) return; // we obviously also need a sample for this ModSample *pModSample = const_cast<ModSample *>(pChn->pModSample); if(pModSample == nullptr || !pModSample->HasSampleData() || !pModSample->uFlags[CHN_LOOP] || pModSample->uFlags[CHN_16BIT]) return; pChn->nEFxDelay += ModEFxTable[pChn->nEFxSpeed & 0x0F]; if((pChn->nEFxDelay & 0x80) == 0) return; // only applied if the "delay" reaches 128 pChn->nEFxDelay = 0; if (++pChn->nEFxOffset >= pModSample->nLoopEnd - pModSample->nLoopStart) pChn->nEFxOffset = 0; // TRASH IT!!! (Yes, the sample!) uint8 &sample = mpt::byte_cast<uint8 *>(pModSample->sampleb())[pModSample->nLoopStart + pChn->nEFxOffset]; sample = ~sample; ctrlSmp::PrecomputeLoops(*pModSample, *this, false); } // Process a MIDI Macro. // Parameters: // [in] nChn: Mod channel to apply macro on // [in] isSmooth: If true, internal macros are interpolated between two rows // [in] macro: Actual MIDI Macro string // [in] param: Parameter for parametric macros (Z00 - Z7F) // [in] plugin: Plugin to send MIDI message to (if not specified but needed, it is autodetected) void CSoundFile::ProcessMIDIMacro(CHANNELINDEX nChn, bool isSmooth, const char *macro, uint8 param, PLUGINDEX plugin) { ModChannel &chn = m_PlayState.Chn[nChn]; const ModInstrument *pIns = GetNumInstruments() ? chn.pModInstrument : nullptr; uint8 out[MACRO_LENGTH]; uint32 outPos = 0; // output buffer position, which also equals the number of complete bytes const uint8 lastZxxParam = chn.lastZxxParam; bool firstNibble = true; for(uint32 pos = 0; pos < (MACRO_LENGTH - 1) && macro[pos]; pos++) { bool isNibble = false; // did we parse a nibble or a byte value? uint8 data = 0; // data that has just been parsed // Parse next macro byte... See Impulse Tracker's MIDI.TXT for detailed information on each possible character. if(macro[pos] >= '0' && macro[pos] <= '9') { isNibble = true; data = static_cast<uint8>(macro[pos] - '0'); } else if(macro[pos] >= 'A' && macro[pos] <= 'F') { isNibble = true; data = static_cast<uint8>(macro[pos] - 'A' + 0x0A); } else if(macro[pos] == 'c') { // MIDI channel isNibble = true; data = GetBestMidiChannel(nChn); } else if(macro[pos] == 'n') { // Last triggered note if(ModCommand::IsNote(chn.nLastNote)) { data = chn.nLastNote - NOTE_MIN; } } else if(macro[pos] == 'v') { // Velocity // This is "almost" how IT does it - apparently, IT seems to lag one row behind on global volume or channel volume changes. const int swing = (m_playBehaviour[kITSwingBehaviour] || m_playBehaviour[kMPTOldSwingBehaviour]) ? chn.nVolSwing : 0; const int vol = Util::muldiv((chn.nVolume + swing) * m_PlayState.m_nGlobalVolume, chn.nGlobalVol * chn.nInsVol, 1 << 20); data = static_cast<uint8>(Clamp(vol / 2, 1, 127)); //data = (unsigned char)MIN((chn.nVolume * chn.nGlobalVol * m_nGlobalVolume) >> (1 + 6 + 8), 127); } else if(macro[pos] == 'u') { // Calculated volume // Same note as with velocity applies here, but apparently also for instrument / sample volumes? const int vol = Util::muldiv(chn.nCalcVolume * m_PlayState.m_nGlobalVolume, chn.nGlobalVol * chn.nInsVol, 1 << 26); data = static_cast<uint8>(Clamp(vol / 2, 1, 127)); //data = (unsigned char)MIN((chn.nCalcVolume * chn.nGlobalVol * m_nGlobalVolume) >> (7 + 6 + 8), 127); } else if(macro[pos] == 'x') { // Pan set data = static_cast<uint8>(std::min(chn.nPan / 2, 127)); } else if(macro[pos] == 'y') { // Calculated pan data = static_cast<uint8>(std::min(chn.nRealPan / 2, 127)); } else if(macro[pos] == 'a') { // High byte of bank select if(pIns && pIns->wMidiBank) { data = static_cast<uint8>(((pIns->wMidiBank - 1) >> 7) & 0x7F); } } else if(macro[pos] == 'b') { // Low byte of bank select if(pIns && pIns->wMidiBank) { data = static_cast<uint8>((pIns->wMidiBank - 1) & 0x7F); } } else if(macro[pos] == 'o') { // Offset (ignoring high offset) data = static_cast<uint8>((chn.oldOffset >> 8) & 0xFF); } else if(macro[pos] == 'h') { // Host channel number data = static_cast<uint8>((nChn >= GetNumChannels() ? (chn.nMasterChn - 1) : nChn) & 0x7F); } else if(macro[pos] == 'm') { // Loop direction (judging from the character, it was supposed to be loop type, though) data = chn.dwFlags[CHN_PINGPONGFLAG] ? 1 : 0; } else if(macro[pos] == 'p') { // Program select if(pIns && pIns->nMidiProgram) { data = static_cast<uint8>((pIns->nMidiProgram - 1) & 0x7F); } } else if(macro[pos] == 'z') { // Zxx parameter data = param & 0x7F; if(isSmooth && chn.lastZxxParam < 0x80 && (outPos < 3 || out[outPos - 3] != 0xF0 || out[outPos - 2] < 0xF0)) { // Interpolation for external MIDI messages - interpolation for internal messages // is handled separately to allow for more than 7-bit granularity where it's possible data = static_cast<uint8>(CalculateSmoothParamChange((float)lastZxxParam, (float)data)); } chn.lastZxxParam = data; } else if(macro[pos] == 's') { // SysEx Checksum (not an original Impulse Tracker macro variable, but added for convenience) uint32 startPos = outPos; while(startPos > 0 && out[--startPos] != 0xF0); if(outPos - startPos < 5 || out[startPos] != 0xF0) { continue; } for(uint32 p = startPos + 5; p != outPos; p++) { data += out[p]; } data = (~data + 1) & 0x7F; } else { // Unrecognized byte (e.g. space char) continue; } // Append parsed data if(isNibble) // parsed a nibble (constant or 'c' variable) { if(firstNibble) { out[outPos] = data; } else { out[outPos] = (out[outPos] << 4) | data; outPos++; } firstNibble = !firstNibble; } else // parsed a byte (variable) { if(!firstNibble) // From MIDI.TXT: '9n' is exactly the same as '09 n' or '9 n' -- so finish current byte first { outPos++; } out[outPos++] = data; firstNibble = true; } } if(!firstNibble) { // Finish current byte outPos++; } // Macro string has been parsed and translated, now send the message(s)... uint32 sendPos = 0; uint8 runningStatus = 0; while(sendPos < outPos) { uint32 sendLen = 0; if(out[sendPos] == 0xF0) { // SysEx start if((outPos - sendPos >= 4) && (out[sendPos + 1] == 0xF0 || out[sendPos + 1] == 0xF1)) { // Internal macro (normal (F0F0) or extended (F0F1)), 4 bytes long sendLen = 4; } else { // SysEx message, find end of message for(uint32 i = sendPos + 1; i < outPos; i++) { if(out[i] == 0xF7) { // Found end of SysEx message sendLen = i - sendPos + 1; break; } } if(sendLen == 0) { // Didn't find end, so "invent" end of SysEx message out[outPos++] = 0xF7; sendLen = outPos - sendPos; } } } else if(!(out[sendPos] & 0x80)) { // Missing status byte? Try inserting running status if(runningStatus != 0) { sendPos--; out[sendPos] = runningStatus; } else { // No running status to re-use; skip this byte sendPos++; } continue; } else { // Other MIDI messages sendLen = std::min<uint32>(MIDIEvents::GetEventLength(out[sendPos]), outPos - sendPos); } if(sendLen == 0) { break; } if(out[sendPos] < 0xF0) { runningStatus = out[sendPos]; } uint32 bytesSent = SendMIDIData(nChn, isSmooth, out + sendPos, sendLen, plugin); // If there's no error in the macro data (e.g. unrecognized internal MIDI macro), we have sendLen == bytesSent. if(bytesSent > 0) { sendPos += bytesSent; } else { sendPos += sendLen; } } } // Calculate smooth MIDI macro slide parameter for current tick. float CSoundFile::CalculateSmoothParamChange(float currentValue, float param) const { MPT_ASSERT(GetNumTicksOnCurrentRow() > m_PlayState.m_nTickCount); const uint32 ticksLeft = GetNumTicksOnCurrentRow() - m_PlayState.m_nTickCount; if(ticksLeft > 1) { // Slide param const float step = (param - currentValue) / (float)ticksLeft; return (currentValue + step); } else { // On last tick, set exact value. return param; } } // Process exactly one MIDI message parsed by ProcessMIDIMacro. Returns bytes sent on success, 0 on (parse) failure. uint32 CSoundFile::SendMIDIData(CHANNELINDEX nChn, bool isSmooth, const unsigned char *macro, uint32 macroLen, PLUGINDEX plugin) { if(macroLen < 1) { return 0; } if(macro[0] == 0xFA || macro[0] == 0xFC || macro[0] == 0xFF) { // Start Song, Stop Song, MIDI Reset - both interpreted internally and sent to plugins for(CHANNELINDEX chn = 0; chn < GetNumChannels(); chn++) { m_PlayState.Chn[chn].nCutOff = 0x7F; m_PlayState.Chn[chn].nResonance = 0x00; } } ModChannel &chn = m_PlayState.Chn[nChn]; if(macro[0] == 0xF0 && (macro[1] == 0xF0 || macro[1] == 0xF1)) { // Internal device. if(macroLen < 4) { return 0; } const bool isExtended = (macro[1] == 0xF1); const uint8 macroCode = macro[2]; const uint8 param = macro[3]; if(macroCode == 0x00 && !isExtended && param < 0x80) { // F0.F0.00.xx: Set CutOff if(!isSmooth) { chn.nCutOff = param; } else { chn.nCutOff = Util::Round<uint8>(CalculateSmoothParamChange(chn.nCutOff, param)); } chn.nRestoreCutoffOnNewNote = 0; SetupChannelFilter(&chn, !chn.dwFlags[CHN_FILTER]); return 4; } else if(macroCode == 0x01 && !isExtended && param < 0x80) { // F0.F0.01.xx: Set Resonance if(!isSmooth) { chn.nResonance = param; } else { chn.nResonance = (uint8)CalculateSmoothParamChange((float)chn.nResonance, (float)param); } chn.nRestoreResonanceOnNewNote = 0; SetupChannelFilter(&chn, !chn.dwFlags[CHN_FILTER]); return 4; } else if(macroCode == 0x02 && !isExtended) { // F0.F0.02.xx: Set filter mode (high nibble determines filter mode) if(param < 0x20) { chn.nFilterMode = (param >> 4); SetupChannelFilter(&chn, !chn.dwFlags[CHN_FILTER]); } return 4; #ifndef NO_PLUGINS } else if(macroCode == 0x03 && !isExtended) { // F0.F0.03.xx: Set plug dry/wet const PLUGINDEX nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted); if ((nPlug) && (nPlug <= MAX_MIXPLUGINS) && param < 0x80) { const float newRatio = (0x7F - (param & 0x7F)) / 127.0f; if(!isSmooth) { m_MixPlugins[nPlug - 1].fDryRatio = newRatio; } else { m_MixPlugins[nPlug - 1].fDryRatio = CalculateSmoothParamChange(m_MixPlugins[nPlug - 1].fDryRatio, newRatio); } } return 4; } else if((macroCode & 0x80) || isExtended) { // F0.F0.{80|n}.xx / F0.F1.n.xx: Set VST effect parameter n to xx const PLUGINDEX nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted); const uint32 plugParam = isExtended ? (0x80 + macroCode) : (macroCode & 0x7F); if((nPlug) && (nPlug <= MAX_MIXPLUGINS)) { IMixPlugin *pPlugin = m_MixPlugins[nPlug - 1].pMixPlugin; if(pPlugin && param < 0x80) { const float fParam = param / 127.0f; if(!isSmooth) { pPlugin->SetParameter(plugParam, fParam); } else { pPlugin->SetParameter(plugParam, CalculateSmoothParamChange(pPlugin->GetParameter(plugParam), fParam)); } } } return 4; #endif // NO_PLUGINS } // If we reach this point, the internal macro was invalid. } else { #ifndef NO_PLUGINS // Not an internal device. Pass on to appropriate plugin. const CHANNELINDEX plugChannel = (nChn < GetNumChannels()) ? nChn + 1 : chn.nMasterChn; if(plugChannel > 0 && plugChannel <= GetNumChannels()) // XXX do we need this? I guess it might be relevant for previewing notes in the pattern... Or when using this mechanism for volume/panning! { PLUGINDEX nPlug = 0; if(!chn.dwFlags[CHN_NOFX]) { nPlug = (plugin != 0) ? plugin : GetBestPlugin(nChn, PrioritiseChannel, EvenIfMuted); } if(nPlug > 0 && nPlug <= MAX_MIXPLUGINS) { IMixPlugin *pPlugin = m_MixPlugins[nPlug - 1].pMixPlugin; if (pPlugin != nullptr) { if(macro[0] == 0xF0) { pPlugin->MidiSysexSend(macro, macroLen); } else { uint32 len = std::min<uint32>(MIDIEvents::GetEventLength(macro[0]), macroLen); uint32 curData = 0; memcpy(&curData, macro, len); pPlugin->MidiSend(curData); } } } } #else MPT_UNREFERENCED_PARAMETER(plugin); #endif // NO_PLUGINS return macroLen; } return 0; } void CSoundFile::SendMIDINote(CHANNELINDEX chn, uint16 note, uint16 volume) { #ifndef NO_PLUGINS auto &channel = m_PlayState.Chn[chn]; const ModInstrument *pIns = channel.pModInstrument; // instro sends to a midi chan if (pIns && pIns->HasValidMIDIChannel()) { PLUGINDEX nPlug = pIns->nMixPlug; if ((nPlug) && (nPlug <= MAX_MIXPLUGINS)) { IMixPlugin *pPlug = m_MixPlugins[nPlug-1].pMixPlugin; if (pPlug != nullptr) { pPlug->MidiCommand(GetBestMidiChannel(chn), pIns->nMidiProgram, pIns->wMidiBank, note, volume, chn); if(note < NOTE_MIN_SPECIAL) channel.nLeftVU = channel.nRightVU = 0xFF; } } } #endif // NO_PLUGINS } void CSoundFile::SampleOffset(ModChannel &chn, SmpLength param) const { chn.proTrackerOffset += param; if(param >= chn.nLoopEnd && GetType() == MOD_TYPE_MTM && chn.dwFlags[CHN_LOOP] && chn.nLoopEnd > 0) { // Offset wrap-around param = (param - chn.nLoopStart) % (chn.nLoopEnd - chn.nLoopStart) + chn.nLoopStart; } if(GetType() == MOD_TYPE_MDL && chn.dwFlags[CHN_16BIT]) { // Digitrakker really uses byte offsets, not sample offsets. WTF! param /= 2u; } if(chn.rowCommand.IsNote()) { // IT compatibility: If this note is not mapped to a sample, ignore it. // Test case: empty_sample_offset.it if(chn.pModInstrument != nullptr) { SAMPLEINDEX smp = chn.pModInstrument->Keyboard[chn.rowCommand.note - NOTE_MIN]; if(smp == 0 || smp > GetNumSamples()) return; } if(m_SongFlags[SONG_PT_MODE]) { // ProTracker compatbility: PT1/2-style funky 9xx offset command // Test case: ptoffset.mod chn.position.Set(chn.proTrackerOffset); chn.proTrackerOffset += param; } else { chn.position.Set(param); } if (chn.position.GetUInt() >= chn.nLength || (chn.dwFlags[CHN_LOOP] && chn.position.GetUInt() >= chn.nLoopEnd)) { // Offset beyond sample size if (!(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MOD | MOD_TYPE_MTM))) { // IT Compatibility: Offset if(m_playBehaviour[kITOffset]) { if(m_SongFlags[SONG_ITOLDEFFECTS]) chn.position.Set(chn.nLength); // Old FX: Clip to end of sample else chn.position.Set(0); // Reset to beginning of sample } else { chn.position.Set(chn.nLoopStart); if(m_SongFlags[SONG_ITOLDEFFECTS] && chn.nLength > 4) { chn.position.Set(chn.nLength - 2); } } } else if(m_playBehaviour[kFT2OffsetOutOfRange] || GetType() == MOD_TYPE_MTM) { // FT2 Compatibility: Don't play note if offset is beyond sample length // Test case: 3xx-no-old-samp.xm chn.dwFlags.set(CHN_FASTVOLRAMP); chn.nPeriod = 0; } else if(GetType() == MOD_TYPE_MOD && chn.dwFlags[CHN_LOOP]) { chn.position.Set(chn.nLoopStart); } } } else if ((param < chn.nLength) && (GetType() & (MOD_TYPE_MTM | MOD_TYPE_DMF | MOD_TYPE_MDL | MOD_TYPE_PLM))) { // Some trackers can also call offset effects without notes next to them... chn.position.Set(param); } } // void CSoundFile::ReverseSampleOffset(ModChannel &chn, ModCommand::PARAM param) const { if(chn.pModSample != nullptr) { chn.dwFlags.set(CHN_PINGPONGFLAG); chn.dwFlags.reset(CHN_LOOP); chn.nLength = chn.pModSample->nLength; // If there was a loop, extend sample to whole length. chn.position.Set((chn.nLength - 1) - std::min<SmpLength>(SmpLength(param) << 8, chn.nLength - 1), 0); } } void CSoundFile::RetrigNote(CHANNELINDEX nChn, int param, int offset) { // Retrig: bit 8 is set if it's the new XM retrig ModChannel &chn = m_PlayState.Chn[nChn]; int retrigSpeed = param & 0x0F; int16 retrigCount = chn.nRetrigCount; bool doRetrig = false; // IT compatibility 15. Retrigger if(m_playBehaviour[kITRetrigger]) { if(m_PlayState.m_nTickCount == 0 && chn.rowCommand.note) { chn.nRetrigCount = param & 0xf; } else if(!chn.nRetrigCount || !--chn.nRetrigCount) { chn.nRetrigCount = param & 0xf; doRetrig = true; } } else if(m_playBehaviour[kFT2Retrigger] && (param & 0x100)) { // Buggy-like-hell FT2 Rxy retrig! // Test case: retrig.xm if(m_SongFlags[SONG_FIRSTTICK]) { // Here are some really stupid things FT2 does on the first tick. // Test case: RetrigTick0.xm if(chn.rowCommand.instr > 0 && chn.rowCommand.IsNoteOrEmpty()) retrigCount = 1; if(chn.rowCommand.volcmd == VOLCMD_VOLUME && chn.rowCommand.vol != 0) { // I guess this condition simply checked if the volume byte was != 0 in FT2. chn.nRetrigCount = retrigCount; return; } } if(retrigCount >= retrigSpeed) { if(!m_SongFlags[SONG_FIRSTTICK] || !chn.rowCommand.IsNote()) { doRetrig = true; retrigCount = 0; } } } else { // old routines if (GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT)) { if (!retrigSpeed) retrigSpeed = 1; if ((retrigCount) && (!(retrigCount % retrigSpeed))) doRetrig = true; retrigCount++; } else if(GetType() == MOD_TYPE_MTM) { // In MultiTracker, E9x retriggers the last note at exactly the x-th tick of the row doRetrig = m_PlayState.m_nTickCount == static_cast<uint32>(param & 0x0F) && retrigSpeed != 0; } else { int realspeed = retrigSpeed; // FT2 bug: if a retrig (Rxy) occurs together with a volume command, the first retrig interval is increased by one tick if ((param & 0x100) && (chn.rowCommand.volcmd == VOLCMD_VOLUME) && (chn.rowCommand.param & 0xF0)) realspeed++; if(!m_SongFlags[SONG_FIRSTTICK] || (param & 0x100)) { if (!realspeed) realspeed = 1; if ((!(param & 0x100)) && (m_PlayState.m_nMusicSpeed) && (!(m_PlayState.m_nTickCount % realspeed))) doRetrig = true; retrigCount++; } else if (GetType() & (MOD_TYPE_XM|MOD_TYPE_MT2)) retrigCount = 0; if (retrigCount >= realspeed) { if ((m_PlayState.m_nTickCount) || ((param & 0x100) && (!chn.rowCommand.note))) doRetrig = true; } if(m_playBehaviour[kFT2Retrigger] && param == 0) { // E90 = Retrig instantly, and only once doRetrig = (m_PlayState.m_nTickCount == 0); } } } // IT compatibility: If a sample is shorter than the retrig time (i.e. it stops before the retrig counter hits zero), it is not retriggered. // Test case: retrig-short.it if(chn.nLength == 0 && m_playBehaviour[kITShortSampleRetrig] && !chn.HasMIDIOutput()) { return; } if(doRetrig) { uint32 dv = (param >> 4) & 0x0F; int vol = chn.nVolume; if (dv) { // FT2 compatibility: Retrig + volume will not change volume of retrigged notes if(!m_playBehaviour[kFT2Retrigger] || !(chn.rowCommand.volcmd == VOLCMD_VOLUME)) { if (retrigTable1[dv]) vol = (vol * retrigTable1[dv]) >> 4; else vol += ((int)retrigTable2[dv]) << 2; } Limit(vol, 0, 256); chn.dwFlags.set(CHN_FASTVOLRAMP); } uint32 note = chn.nNewNote; int32 oldPeriod = chn.nPeriod; if (note >= NOTE_MIN && note <= NOTE_MAX && chn.nLength) CheckNNA(nChn, 0, note, true); bool resetEnv = false; if(GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2)) { if((chn.rowCommand.instr) && (param < 0x100)) { InstrumentChange(&chn, chn.rowCommand.instr, false, false); resetEnv = true; } if (param < 0x100) resetEnv = true; } bool fading = chn.dwFlags[CHN_NOTEFADE]; // IT compatibility: Really weird combination of envelopes and retrigger (see Storlek's q.it testcase) // Test case: retrig.it NoteChange(&chn, note, m_playBehaviour[kITRetrigger], resetEnv); // XM compatibility: Prevent NoteChange from resetting the fade flag in case an instrument number + note-off is present. // Test case: RetrigFade.xm if(fading && GetType() == MOD_TYPE_XM) chn.dwFlags.set(CHN_NOTEFADE); chn.nVolume = vol; if(m_nInstruments) { chn.rowCommand.note = static_cast<ModCommand::NOTE>(note); // No retrig without note... #ifndef NO_PLUGINS ProcessMidiOut(nChn); //Send retrig to Midi #endif // NO_PLUGINS } if ((GetType() & (MOD_TYPE_IT|MOD_TYPE_MPT)) && (!chn.rowCommand.note) && (oldPeriod)) chn.nPeriod = oldPeriod; if (!(GetType() & (MOD_TYPE_S3M|MOD_TYPE_IT|MOD_TYPE_MPT))) retrigCount = 0; // IT compatibility: see previous IT compatibility comment =) if(m_playBehaviour[kITRetrigger]) chn.position.Set(0); offset--; if(offset >= 0 && offset <= static_cast<int>(CountOf(chn.pModSample->cues)) && chn.pModSample != nullptr) { if(offset == 0) offset = chn.oldOffset; else offset = chn.oldOffset = chn.pModSample->cues[offset - 1]; SampleOffset(chn, offset); } } // buggy-like-hell FT2 Rxy retrig! if(m_playBehaviour[kFT2Retrigger] && (param & 0x100)) retrigCount++; // Now we can also store the retrig value for IT... if(!m_playBehaviour[kITRetrigger]) chn.nRetrigCount = retrigCount; } void CSoundFile::DoFreqSlide(ModChannel *pChn, int32 nFreqSlide) const { if(!pChn->nPeriod) return; if(GetType() == MOD_TYPE_669) { // Like other oldskool trackers, Composer 669 doesn't have linear slides... // But the slides are done in Hertz rather than periods, meaning that they // are more effective in the lower notes (rather than the higher notes). nFreqSlide *= -20; } if(m_SongFlags[SONG_LINEARSLIDES] && GetType() != MOD_TYPE_XM) { // IT Linear slides const auto nOldPeriod = pChn->nPeriod; uint32 n = mpt::abs(nFreqSlide) / 4u; LimitMax(n, 255u); if(n != 0) { pChn->nPeriod = Util::muldivr(pChn->nPeriod, nFreqSlide < 0 ? GetLinearSlideUpTable(this, n) : GetLinearSlideDownTable(this, n), 65536); if(pChn->nPeriod == nOldPeriod) { const bool incPeriod = m_playBehaviour[kHertzInLinearMode] == (nFreqSlide < 0); if(incPeriod && pChn->nPeriod < Util::MaxValueOfType(pChn->nPeriod)) pChn->nPeriod++; else if(!incPeriod && pChn->nPeriod > 1) pChn->nPeriod--; } } } else { pChn->nPeriod += nFreqSlide; } if (pChn->nPeriod < 1) { pChn->nPeriod = 1; if(GetType() == MOD_TYPE_S3M) { pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE | CHN_FASTVOLRAMP); } } } void CSoundFile::NoteCut(CHANNELINDEX nChn, uint32 nTick, bool cutSample) { if (m_PlayState.m_nTickCount == nTick) { ModChannel *pChn = &m_PlayState.Chn[nChn]; if(cutSample) { pChn->increment.Set(0); pChn->nFadeOutVol = 0; pChn->dwFlags.set(CHN_NOTEFADE); } else { pChn->nVolume = 0; } pChn->dwFlags.set(CHN_FASTVOLRAMP); // instro sends to a midi chan SendMIDINote(nChn, /*pChn->nNote+*/NOTE_MAX_SPECIAL, 0); } } void CSoundFile::KeyOff(ModChannel *pChn) const { const bool bKeyOn = !pChn->dwFlags[CHN_KEYOFF]; pChn->dwFlags.set(CHN_KEYOFF); if(pChn->pModInstrument != nullptr && !pChn->VolEnv.flags[ENV_ENABLED]) { pChn->dwFlags.set(CHN_NOTEFADE); } if (!pChn->nLength) return; if (pChn->dwFlags[CHN_SUSTAINLOOP] && pChn->pModSample && bKeyOn) { const ModSample *pSmp = pChn->pModSample; if(pSmp->uFlags[CHN_LOOP]) { if (pSmp->uFlags[CHN_PINGPONGLOOP]) pChn->dwFlags.set(CHN_PINGPONGLOOP); else pChn->dwFlags.reset(CHN_PINGPONGLOOP | CHN_PINGPONGFLAG); pChn->dwFlags.set(CHN_LOOP); pChn->nLength = pSmp->nLength; pChn->nLoopStart = pSmp->nLoopStart; pChn->nLoopEnd = pSmp->nLoopEnd; if (pChn->nLength > pChn->nLoopEnd) pChn->nLength = pChn->nLoopEnd; if(pChn->position.GetUInt() > pChn->nLength) { // Test case: SusAfterLoop.it pChn->position.Set(pChn->position.GetInt() - pChn->nLength + pChn->nLoopStart); } } else { pChn->dwFlags.reset(CHN_LOOP | CHN_PINGPONGLOOP | CHN_PINGPONGFLAG); pChn->nLength = pSmp->nLength; } } if (pChn->pModInstrument) { const ModInstrument *pIns = pChn->pModInstrument; if((pIns->VolEnv.dwFlags[ENV_LOOP] || (GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2 | MOD_TYPE_MDL))) && pIns->nFadeOut != 0) { pChn->dwFlags.set(CHN_NOTEFADE); } if (pIns->VolEnv.nReleaseNode != ENV_RELEASE_NODE_UNSET && pChn->VolEnv.nEnvValueAtReleaseJump == NOT_YET_RELEASED) { pChn->VolEnv.nEnvValueAtReleaseJump = pIns->VolEnv.GetValueFromPosition(pChn->VolEnv.nEnvPosition, 256); pChn->VolEnv.nEnvPosition = pIns->VolEnv[pIns->VolEnv.nReleaseNode].tick; } } } ////////////////////////////////////////////////////////// // CSoundFile: Global Effects void CSoundFile::SetSpeed(PlayState &playState, uint32 param) const { #ifdef MODPLUG_TRACKER // FT2 appears to be decrementing the tick count before checking for zero, // so it effectively counts down 65536 ticks with speed = 0 (song speed is a 16-bit variable in FT2) if(GetType() == MOD_TYPE_XM && !param) { playState.m_nMusicSpeed = uint16_max; } #endif // MODPLUG_TRACKER if(param > 0) playState.m_nMusicSpeed = param; if(GetType() == MOD_TYPE_STM && param > 0) { playState.m_nMusicSpeed = std::max<uint32>(param >> 4u, 1); playState.m_nMusicTempo = ConvertST2Tempo(static_cast<uint8>(param)); } } // Convert a ST2 tempo byte to classic tempo and speed combination TEMPO CSoundFile::ConvertST2Tempo(uint8 tempo) { static const uint8 ST2TempoFactor[] = { 140, 50, 25, 15, 10, 7, 6, 4, 3, 3, 2, 2, 2, 2, 1, 1 }; static const uint32 st2MixingRate = 23863; // Highest possible setting in ST2 // This underflows at tempo 06...0F, and the resulting tick lengths depend on the mixing rate. int32 samplesPerTick = st2MixingRate / (49 - ((ST2TempoFactor[tempo >> 4u] * (tempo & 0x0F)) >> 4u)); if(samplesPerTick <= 0) samplesPerTick += 65536; return TEMPO().SetRaw(Util::muldivrfloor(st2MixingRate, 5 * TEMPO::fractFact, samplesPerTick * 2)); } void CSoundFile::SetTempo(TEMPO param, bool setFromUI) { const CModSpecifications &specs = GetModSpecifications(); // Anything lower than the minimum tempo is considered to be a tempo slide const TEMPO minTempo = (GetType() == MOD_TYPE_MDL) ? TEMPO(1, 0) : TEMPO(32, 0); if(setFromUI) { // Set tempo from UI - ignore slide commands and such. m_PlayState.m_nMusicTempo = Clamp(param, specs.GetTempoMin(), specs.GetTempoMax()); } else if(param >= minTempo && m_SongFlags[SONG_FIRSTTICK] == !m_playBehaviour[kMODTempoOnSecondTick]) { // ProTracker sets the tempo after the first tick. // Note: The case of one tick per row is handled in ProcessRow() instead. // Test case: TempoChange.mod m_PlayState.m_nMusicTempo = std::min(param, specs.GetTempoMax()); } else if(param < minTempo && !m_SongFlags[SONG_FIRSTTICK]) { // Tempo Slide TEMPO tempDiff(param.GetInt() & 0x0F, 0); if((param.GetInt() & 0xF0) == 0x10) m_PlayState.m_nMusicTempo += tempDiff; else m_PlayState.m_nMusicTempo -= tempDiff; TEMPO tempoMin = specs.GetTempoMin(), tempoMax = specs.GetTempoMax(); if(m_playBehaviour[kTempoClamp]) // clamp tempo correctly in compatible mode { tempoMax.Set(255); } Limit(m_PlayState.m_nMusicTempo, tempoMin, tempoMax); } } ROWINDEX CSoundFile::PatternLoop(ModChannel *pChn, uint32 param) { if (param) { // Loop Repeat if(pChn->nPatternLoopCount) { // There's a loop left pChn->nPatternLoopCount--; if(!pChn->nPatternLoopCount) { // IT compatibility 10. Pattern loops (+ same fix for S3M files) // When finishing a pattern loop, the next loop without a dedicated SB0 starts on the first row after the previous loop. if(m_playBehaviour[kITPatternLoopTargetReset] || (GetType() == MOD_TYPE_S3M)) { pChn->nPatternLoop = m_PlayState.m_nRow + 1; } return ROWINDEX_INVALID; } } else { // First time we get into the loop => Set loop count. // IT compatibility 10. Pattern loops (+ same fix for XM / MOD / S3M files) if(!m_playBehaviour[kITFT2PatternLoop] && !(GetType() & (MOD_TYPE_MOD | MOD_TYPE_S3M))) { ModChannel *p = m_PlayState.Chn; for(CHANNELINDEX i = 0; i < GetNumChannels(); i++, p++) if (p != pChn) { // Loop on other channel if(p->nPatternLoopCount) return ROWINDEX_INVALID; } } pChn->nPatternLoopCount = static_cast<uint8>(param); } m_PlayState.m_nNextPatStartRow = pChn->nPatternLoop; // Nasty FT2 E60 bug emulation! return pChn->nPatternLoop; } else { // Loop Start pChn->nPatternLoop = m_PlayState.m_nRow; } return ROWINDEX_INVALID; } void CSoundFile::GlobalVolSlide(ModCommand::PARAM param, uint8 &nOldGlobalVolSlide) { int32 nGlbSlide = 0; if (param) nOldGlobalVolSlide = param; else param = nOldGlobalVolSlide; if((GetType() & (MOD_TYPE_XM | MOD_TYPE_MT2))) { // XM nibble priority if((param & 0xF0) != 0) { param &= 0xF0; } else { param &= 0x0F; } } if (((param & 0x0F) == 0x0F) && (param & 0xF0)) { if(m_SongFlags[SONG_FIRSTTICK]) nGlbSlide = (param >> 4) * 2; } else if (((param & 0xF0) == 0xF0) && (param & 0x0F)) { if(m_SongFlags[SONG_FIRSTTICK]) nGlbSlide = - (int)((param & 0x0F) * 2); } else { if(!m_SongFlags[SONG_FIRSTTICK]) { if (param & 0xF0) { // IT compatibility: Ignore slide commands with both nibbles set. if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM)) || (param & 0x0F) == 0) nGlbSlide = (int)((param & 0xF0) >> 4) * 2; } else { nGlbSlide = -(int)((param & 0x0F) * 2); } } } if (nGlbSlide) { if(!(GetType() & (MOD_TYPE_IT | MOD_TYPE_MPT | MOD_TYPE_IMF | MOD_TYPE_J2B | MOD_TYPE_MID | MOD_TYPE_AMS | MOD_TYPE_AMS2 | MOD_TYPE_DBM))) nGlbSlide *= 2; nGlbSlide += m_PlayState.m_nGlobalVolume; Limit(nGlbSlide, 0, 256); m_PlayState.m_nGlobalVolume = nGlbSlide; } } ////////////////////////////////////////////////////// // Note/Period/Frequency functions // Find lowest note which has same or lower period as a given period (i.e. the note has the same or higher frequency) uint32 CSoundFile::GetNoteFromPeriod(uint32 period, int32 nFineTune, uint32 nC5Speed) const { if(!period) return 0; if(m_playBehaviour[kFT2Periods]) { // FT2's "RelocateTon" function actually rounds up and down, while GetNoteFromPeriod normally just truncates. nFineTune += 64; } // This essentially implements std::lower_bound, with the difference that we don't need an iterable container. uint32 minNote = NOTE_MIN, maxNote = NOTE_MAX, count = maxNote - minNote + 1; const bool periodIsFreq = PeriodsAreFrequencies(); while(count > 0) { const uint32 step = count / 2, midNote = minNote + step; uint32 n = GetPeriodFromNote(midNote, nFineTune, nC5Speed); if((n > period && !periodIsFreq) || (n < period && periodIsFreq) || !n) { minNote = midNote + 1; count -= step + 1; } else { count = step; } } return minNote; } uint32 CSoundFile::GetPeriodFromNote(uint32 note, int32 nFineTune, uint32 nC5Speed) const { if (note == NOTE_NONE || (note >= NOTE_MIN_SPECIAL)) return 0; note -= NOTE_MIN; if (!UseFinetuneAndTranspose()) { if(GetType() & (MOD_TYPE_MDL | MOD_TYPE_DTM)) { // MDL uses non-linear slides, but their effectiveness does not depend on the middle-C frequency. return (FreqS3MTable[note % 12u] << 4) >> (note / 12); } if(m_SongFlags[SONG_LINEARSLIDES] || GetType() == MOD_TYPE_669) { // In IT linear slide mode, directly use frequency in Hertz rather than periods. if(m_playBehaviour[kHertzInLinearMode] || GetType() == MOD_TYPE_669) return Util::muldiv_unsigned(nC5Speed, LinearSlideUpTable[(note % 12u) * 16u] << (note / 12u), 65536 << 5); else return (FreqS3MTable[note % 12u] << 5) >> (note / 12); } else { if (!nC5Speed) nC5Speed = 8363; LimitMax(nC5Speed, uint32_max >> (note / 12u)); //(a*b)/c return Util::muldiv_unsigned(8363, (FreqS3MTable[note % 12u] << 5), nC5Speed << (note / 12u)); //8363 * freq[note%12] / nC5Speed * 2^(5-note/12) } } else if (GetType() == MOD_TYPE_XM) { if (note < 12) note = 12; note -= 12; // FT2 Compatibility: The lower three bits of the finetune are truncated. // Test case: Finetune-Precision.xm if(m_playBehaviour[kFT2FinetunePrecision]) { nFineTune &= ~7; } if(m_SongFlags[SONG_LINEARSLIDES]) { int l = ((NOTE_MAX - note) << 6) - (nFineTune / 2); if (l < 1) l = 1; return static_cast<uint32>(l); } else { int finetune = nFineTune; uint32 rnote = (note % 12) << 3; uint32 roct = note / 12; int rfine = finetune / 16; int i = rnote + rfine + 8; Limit(i , 0, 103); uint32 per1 = XMPeriodTable[i]; if(finetune < 0) { rfine--; finetune = -finetune; } else rfine++; i = rnote+rfine+8; if (i < 0) i = 0; if (i >= 104) i = 103; uint32 per2 = XMPeriodTable[i]; rfine = finetune & 0x0F; per1 *= 16-rfine; per2 *= rfine; return ((per1 + per2) << 1) >> roct; } } else { nFineTune = XM2MODFineTune(nFineTune); if ((nFineTune) || (note < 36) || (note >= 36 + 6 * 12)) return (ProTrackerTunedPeriods[nFineTune * 12u + note % 12u] << 5) >> (note / 12u); else return (ProTrackerPeriodTable[note - 36] << 2); } } // Converts period value to sample frequency. Return value is fixed point, with FREQ_FRACBITS fractional bits. uint32 CSoundFile::GetFreqFromPeriod(uint32 period, uint32 c5speed, int32 nPeriodFrac) const { if (!period) return 0; if (GetType() == MOD_TYPE_XM) { if(m_playBehaviour[kFT2Periods]) { // FT2 compatibility: Period is a 16-bit value in FT2, and it overflows happily. // Test case: FreqWraparound.xm period &= 0xFFFF; } if(m_SongFlags[SONG_LINEARSLIDES]) { uint32 octave; if(m_playBehaviour[kFT2Periods]) { // Under normal circumstances, this calculation returns the same values as the non-compatible one. // However, once the 12 octaves are exceeded (through portamento slides), the octave shift goes // crazy in FT2, meaning that the frequency wraps around randomly... // The entries in FT2's conversion table are four times as big, hence we have to do an additional shift by two bits. // Test case: FreqWraparound.xm // 12 octaves * (12 * 64) LUT entries = 9216, add 767 for rounding uint32 div = ((9216u + 767u - period) / 768); octave = ((14 - div) & 0x1F); } else { octave = (period / 768) + 2; } return (XMLinearTable[period % 768] << (FREQ_FRACBITS + 2)) >> octave; } else { if(!period) period = 1; return ((8363 * 1712L) << FREQ_FRACBITS) / period; } } else if (UseFinetuneAndTranspose()) { return ((3546895L * 4) << FREQ_FRACBITS) / period; } else if(GetType() == MOD_TYPE_669) { // We only really use c5speed for the finetune pattern command. All samples in 669 files have the same middle-C speed (imported as 8363 Hz). return (period + c5speed - 8363) << FREQ_FRACBITS; } else if(GetType() & (MOD_TYPE_MDL | MOD_TYPE_DTM)) { LimitMax(period, Util::MaxValueOfType(period) >> 8); if (!c5speed) c5speed = 8363; return Util::muldiv_unsigned(c5speed, (1712L << 7) << FREQ_FRACBITS, (period << 8) + nPeriodFrac); } else { LimitMax(period, Util::MaxValueOfType(period) >> 8); if(m_SongFlags[SONG_LINEARSLIDES]) { if(m_playBehaviour[kHertzInLinearMode]) { // IT linear slides already use frequencies instead of periods. static_assert(FREQ_FRACBITS <= 8, "Check this shift operator"); return uint32(((uint64(period) << 8) + nPeriodFrac) >> (8 - FREQ_FRACBITS)); } else { if (!c5speed) c5speed = 8363; return Util::muldiv_unsigned(c5speed, (1712L << 8) << FREQ_FRACBITS, (period << 8) + nPeriodFrac); } } else { return Util::muldiv_unsigned(8363, (1712L << 8) << FREQ_FRACBITS, (period << 8) + nPeriodFrac); } } } PLUGINDEX CSoundFile::GetBestPlugin(CHANNELINDEX nChn, PluginPriority priority, PluginMutePriority respectMutes) const { if (nChn >= MAX_CHANNELS) //Check valid channel number { return 0; } //Define search source order PLUGINDEX nPlugin = 0; switch (priority) { case ChannelOnly: nPlugin = GetChannelPlugin(nChn, respectMutes); break; case InstrumentOnly: nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes); break; case PrioritiseInstrument: nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes); if ((!nPlugin) || (nPlugin > MAX_MIXPLUGINS)) { nPlugin = GetChannelPlugin(nChn, respectMutes); } break; case PrioritiseChannel: nPlugin = GetChannelPlugin(nChn, respectMutes); if ((!nPlugin) || (nPlugin > MAX_MIXPLUGINS)) { nPlugin = GetActiveInstrumentPlugin(nChn, respectMutes); } break; } return nPlugin; // 0 Means no plugin found. } PLUGINDEX CSoundFile::GetChannelPlugin(CHANNELINDEX nChn, PluginMutePriority respectMutes) const { const ModChannel &channel = m_PlayState.Chn[nChn]; PLUGINDEX nPlugin; if((respectMutes == RespectMutes && channel.dwFlags[CHN_MUTE]) || channel.dwFlags[CHN_NOFX]) { nPlugin = 0; } else { // If it looks like this is an NNA channel, we need to find the master channel. // This ensures we pick up the right ChnSettings. // NB: nMasterChn == 0 means no master channel, so we need to -1 to get correct index. if (nChn >= m_nChannels && channel.nMasterChn > 0) { nChn = channel.nMasterChn - 1; } if(nChn < MAX_BASECHANNELS) { nPlugin = ChnSettings[nChn].nMixPlugin; } else { nPlugin = 0; } } return nPlugin; } PLUGINDEX CSoundFile::GetActiveInstrumentPlugin(CHANNELINDEX nChn, PluginMutePriority respectMutes) const { // Unlike channel settings, pModInstrument is copied from the original chan to the NNA chan, // so we don't need to worry about finding the master chan. PLUGINDEX plug = 0; if(m_PlayState.Chn[nChn].pModInstrument != nullptr) { if(respectMutes == RespectMutes && m_PlayState.Chn[nChn].pModSample && m_PlayState.Chn[nChn].pModSample->uFlags[CHN_MUTE]) { plug = 0; } else { plug = m_PlayState.Chn[nChn].pModInstrument->nMixPlug; } } return plug; } // Retrieve the plugin that is associated with the channel's current instrument. // No plugin is returned if the channel is muted or if the instrument doesn't have a MIDI channel set up, // As this is meant to be used with instrument plugins. IMixPlugin *CSoundFile::GetChannelInstrumentPlugin(CHANNELINDEX chn) const { #ifndef NO_PLUGINS if(m_PlayState.Chn[chn].dwFlags[CHN_MUTE | CHN_SYNCMUTE]) { // Don't process portamento on muted channels. Note that this might have a side-effect // on other channels which trigger notes on the same MIDI channel of the same plugin, // as those won't be pitch-bent anymore. return nullptr; } if(m_PlayState.Chn[chn].HasMIDIOutput()) { const ModInstrument *pIns = m_PlayState.Chn[chn].pModInstrument; // Instrument sends to a MIDI channel if(pIns->nMixPlug != 0 && pIns->nMixPlug <= MAX_MIXPLUGINS) { return m_MixPlugins[pIns->nMixPlug - 1].pMixPlugin; } } #else MPT_UNREFERENCED_PARAMETER(chn); #endif // NO_PLUGINS return nullptr; } // Get the MIDI channel currently associated with a given tracker channel uint8 CSoundFile::GetBestMidiChannel(CHANNELINDEX nChn) const { if(nChn >= MAX_CHANNELS) { return 0; } const ModInstrument *ins = m_PlayState.Chn[nChn].pModInstrument; if(ins != nullptr) { if(ins->nMidiChannel == MidiMappedChannel) { // For mapped channels, return their pattern channel, modulo 16 (because there are only 16 MIDI channels) return (m_PlayState.Chn[nChn].nMasterChn ? (m_PlayState.Chn[nChn].nMasterChn - 1) : nChn) % 16; } else if(ins->HasValidMIDIChannel()) { return (ins->nMidiChannel - 1) & 0x0F; } } return 0; } #ifdef MODPLUG_TRACKER void CSoundFile::HandlePatternTransitionEvents() { // MPT sequence override if(m_PlayState.m_nSeqOverride != ORDERINDEX_INVALID && m_PlayState.m_nSeqOverride < Order().size()) { if(m_SongFlags[SONG_PATTERNLOOP]) { m_PlayState.m_nPattern = Order()[m_PlayState.m_nSeqOverride]; } m_PlayState.m_nCurrentOrder = m_PlayState.m_nSeqOverride; m_PlayState.m_nSeqOverride = ORDERINDEX_INVALID; } // Channel mutes for (CHANNELINDEX chan = 0; chan < GetNumChannels(); chan++) { if (m_bChannelMuteTogglePending[chan]) { if(GetpModDoc()) { GetpModDoc()->MuteChannel(chan, !GetpModDoc()->IsChannelMuted(chan)); } m_bChannelMuteTogglePending[chan] = false; } } } #endif // MODPLUG_TRACKER // Update time signatures (global or pattern-specific). Don't forget to call this when changing the RPB/RPM settings anywhere! void CSoundFile::UpdateTimeSignature() { if(!Patterns.IsValidIndex(m_PlayState.m_nPattern) || !Patterns[m_PlayState.m_nPattern].GetOverrideSignature()) { m_PlayState.m_nCurrentRowsPerBeat = m_nDefaultRowsPerBeat; m_PlayState.m_nCurrentRowsPerMeasure = m_nDefaultRowsPerMeasure; } else { m_PlayState.m_nCurrentRowsPerBeat = Patterns[m_PlayState.m_nPattern].GetRowsPerBeat(); m_PlayState.m_nCurrentRowsPerMeasure = Patterns[m_PlayState.m_nPattern].GetRowsPerMeasure(); } } void CSoundFile::PortamentoMPT(ModChannel* pChn, int param) { //Behavior: Modifies portamento by param-steps on every tick. //Note that step meaning depends on tuning. pChn->m_PortamentoFineSteps += param; pChn->m_CalculateFreq = true; } void CSoundFile::PortamentoFineMPT(ModChannel* pChn, int param) { //Behavior: Divides portamento change between ticks/row. For example //if Ticks/row == 6, and param == +-6, portamento goes up/down by one tuning-dependent //fine step every tick. if(m_PlayState.m_nTickCount == 0) pChn->nOldFinePortaUpDown = 0; const int tickParam = static_cast<int>((m_PlayState.m_nTickCount + 1.0) * param / m_PlayState.m_nMusicSpeed); pChn->m_PortamentoFineSteps += (param >= 0) ? tickParam - pChn->nOldFinePortaUpDown : tickParam + pChn->nOldFinePortaUpDown; if(m_PlayState.m_nTickCount + 1 == m_PlayState.m_nMusicSpeed) pChn->nOldFinePortaUpDown = static_cast<int8>(mpt::abs(param)); else pChn->nOldFinePortaUpDown = static_cast<int8>(mpt::abs(tickParam)); pChn->m_CalculateFreq = true; } void CSoundFile::PortamentoExtraFineMPT(ModChannel* pChn, int param) { // This kinda behaves like regular fine portamento. // It changes the pitch by n finetune steps on the first tick. if(pChn->isFirstTick) { pChn->m_PortamentoFineSteps += param; pChn->m_CalculateFreq = true; } } OPENMPT_NAMESPACE_END
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_65_0
crossvul-cpp_data_bad_1183_1
// This file is part of The New Aspell // Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #include "settings.h" //#include "iostream.hpp" #include "config.hpp" #include "file_util.hpp" #include "fstream.hpp" #include "errors.hpp" #include "string_list.hpp" #ifdef USE_FILE_LOCKS # include <fcntl.h> # include <unistd.h> # include <sys/types.h> #endif #include <stdio.h> #include <sys/stat.h> #include <dirent.h> #ifdef WIN32 # include <io.h> # define ACCESS _access # include <windows.h> # include <winbase.h> #else # include <unistd.h> # define ACCESS access #endif namespace acommon { // Return false if file is already an absolute path and does not need // a directory prepended. bool need_dir(ParmString file) { if (file[0] == '/' || (file[0] == '.' && file[1] == '/') #ifdef WIN32 || (asc_isalpha(file[0]) && file[1] == ':') || file[0] == '\\' || (file[0] == '.' && file[1] == '\\') #endif ) return false; else return true; } String add_possible_dir(ParmString dir, ParmString file) { if (need_dir(file)) { String path; path += dir; path += '/'; path += file; return path; } else { return file; } } String figure_out_dir(ParmString dir, ParmString file) { String temp; int s = file.size() - 1; while (s != -1 && file[s] != '/') --s; if (need_dir(file)) { temp += dir; temp += '/'; } if (s != -1) { temp.append(file, s); } return temp; } time_t get_modification_time(FStream & f) { struct stat s; fstat(f.file_no(), &s); return s.st_mtime; } PosibErr<void> open_file_readlock(FStream & in, ParmString file) { RET_ON_ERR(in.open(file, "r")); #ifdef USE_FILE_LOCKS int fd = in.file_no(); struct flock fl; fl.l_type = F_RDLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fcntl(fd, F_SETLKW, &fl); // ignore errors #endif return no_err; } PosibErr<bool> open_file_writelock(FStream & inout, ParmString file) { typedef PosibErr<bool> Ret; #ifndef USE_FILE_LOCKS bool exists = file_exists(file); #endif { Ret pe = inout.open(file, "r+"); if (pe.get_err() != 0) pe = inout.open(file, "w+"); if (pe.has_err()) return pe; } #ifdef USE_FILE_LOCKS int fd = inout.file_no(); struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fcntl(fd, F_SETLKW, &fl); // ignore errors struct stat s; fstat(fd, &s); return s.st_size != 0; #else return exists; #endif } void truncate_file(FStream & f, ParmString name) { #ifdef USE_FILE_LOCKS f.restart(); ftruncate(f.file_no(),0); #else f.close(); f.open(name, "w+"); #endif } bool remove_file(ParmString name) { return remove(name) == 0; } bool file_exists(ParmString name) { return ACCESS(name, F_OK) == 0; } bool rename_file(ParmString orig_name, ParmString new_name) { remove(new_name); return rename(orig_name, new_name) == 0; } const char * get_file_name(const char * path) { const char * file_name; if (path != 0) { file_name = strrchr(path,'/'); if (file_name == 0) file_name = path; } else { file_name = 0; } return file_name; } unsigned find_file(const Config * config, const char * option, String & filename) { StringList sl; config->retrieve_list(option, &sl); return find_file(sl, filename); } unsigned find_file(const StringList & sl, String & filename) { StringListEnumeration els = sl.elements_obj(); const char * dir; String path; while ( (dir = els.next()) != 0 ) { path = dir; if (path.back() != '/') path += '/'; unsigned dir_len = path.size(); path += filename; if (file_exists(path)) { filename.swap(path); return dir_len; } } return 0; } PathBrowser::PathBrowser(const StringList & sl, const char * suf) : dir_handle(0) { els = sl.elements(); suffix = suf; } PathBrowser::~PathBrowser() { delete els; if (dir_handle) closedir((DIR *)dir_handle); } const char * PathBrowser::next() { if (dir_handle == 0) goto get_next_dir; begin: { struct dirent * entry = readdir((DIR *)dir_handle); if (entry == 0) goto try_again; const char * name = entry->d_name; unsigned name_len = strlen(name); if (suffix.size() != 0 && !(name_len > suffix.size() && memcmp(name + name_len - suffix.size(), suffix.str(), suffix.size()) == 0)) goto begin; path = dir; if (path.back() != '/') path += '/'; path += name; } return path.str(); try_again: if (dir_handle) closedir((DIR *)dir_handle); dir_handle = 0; get_next_dir: dir = els->next(); if (!dir) return 0; dir_handle = opendir(dir); if (dir_handle == 0) goto try_again; goto begin; } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_1183_1
crossvul-cpp_data_bad_4256_3
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ESTreeIRGen.h" #include "llvh/ADT/SmallString.h" namespace hermes { namespace irgen { //===----------------------------------------------------------------------===// // FunctionContext FunctionContext::FunctionContext( ESTreeIRGen *irGen, Function *function, sem::FunctionInfo *semInfo) : irGen_(irGen), semInfo_(semInfo), oldContext_(irGen->functionContext_), builderSaveState_(irGen->Builder), function(function), scope(irGen->nameTable_) { irGen->functionContext_ = this; // Initialize it to LiteraUndefined by default to avoid corner cases. this->capturedNewTarget = irGen->Builder.getLiteralUndefined(); if (semInfo_) { // Allocate the label table. Each label definition will be encountered in // the AST before it is referenced (because of the nature of JavaScript), at // which point we will initialize the GotoLabel structure with basic blocks // targets. labels_.resize(semInfo_->labelCount); } } FunctionContext::~FunctionContext() { irGen_->functionContext_ = oldContext_; } Identifier FunctionContext::genAnonymousLabelName(StringRef hint) { llvh::SmallString<16> buf; llvh::raw_svector_ostream nameBuilder{buf}; nameBuilder << "?anon_" << anonymousLabelCounter++ << "_" << hint; return function->getContext().getIdentifier(nameBuilder.str()); } //===----------------------------------------------------------------------===// // ESTreeIRGen void ESTreeIRGen::genFunctionDeclaration( ESTree::FunctionDeclarationNode *func) { if (func->_async) { Builder.getModule()->getContext().getSourceErrorManager().error( func->getSourceRange(), Twine("async functions are unsupported")); return; } // Find the name of the function. Identifier functionName = getNameFieldFromID(func->_id); LLVM_DEBUG(dbgs() << "IRGen function \"" << functionName << "\".\n"); auto *funcStorage = nameTable_.lookup(functionName); assert( funcStorage && "function declaration variable should have been hoisted"); Function *newFunc = func->_generator ? genGeneratorFunction(functionName, nullptr, func) : genES5Function(functionName, nullptr, func); // Store the newly created closure into a frame variable with the same name. auto *newClosure = Builder.createCreateFunctionInst(newFunc); emitStore(Builder, newClosure, funcStorage, true); } Value *ESTreeIRGen::genFunctionExpression( ESTree::FunctionExpressionNode *FE, Identifier nameHint) { if (FE->_async) { Builder.getModule()->getContext().getSourceErrorManager().error( FE->getSourceRange(), Twine("async functions are unsupported")); return Builder.getLiteralUndefined(); } LLVM_DEBUG( dbgs() << "Creating anonymous closure. " << Builder.getInsertionBlock()->getParent()->getInternalName() << ".\n"); NameTableScopeTy newScope(nameTable_); Variable *tempClosureVar = nullptr; Identifier originalNameIden = nameHint; if (FE->_id) { auto closureName = genAnonymousLabelName("closure"); tempClosureVar = Builder.createVariable( curFunction()->function->getFunctionScope(), Variable::DeclKind::Var, closureName); // Insert the synthesized variable into the name table, so it can be // looked up internally as well. nameTable_.insertIntoScope( &curFunction()->scope, tempClosureVar->getName(), tempClosureVar); // Alias the lexical name to the synthesized variable. originalNameIden = getNameFieldFromID(FE->_id); nameTable_.insert(originalNameIden, tempClosureVar); } Function *newFunc = FE->_generator ? genGeneratorFunction(originalNameIden, tempClosureVar, FE) : genES5Function(originalNameIden, tempClosureVar, FE); Value *closure = Builder.createCreateFunctionInst(newFunc); if (tempClosureVar) emitStore(Builder, closure, tempClosureVar, true); return closure; } Value *ESTreeIRGen::genArrowFunctionExpression( ESTree::ArrowFunctionExpressionNode *AF, Identifier nameHint) { LLVM_DEBUG( dbgs() << "Creating arrow function. " << Builder.getInsertionBlock()->getParent()->getInternalName() << ".\n"); if (AF->_async) { Builder.getModule()->getContext().getSourceErrorManager().error( AF->getSourceRange(), Twine("async functions are unsupported")); return Builder.getLiteralUndefined(); } auto *newFunc = Builder.createFunction( nameHint, Function::DefinitionKind::ES6Arrow, ESTree::isStrict(AF->strictness), AF->getSourceRange()); { FunctionContext newFunctionContext{this, newFunc, AF->getSemInfo()}; // Propagate captured "this", "new.target" and "arguments" from parents. auto *prev = curFunction()->getPreviousContext(); curFunction()->capturedThis = prev->capturedThis; curFunction()->capturedNewTarget = prev->capturedNewTarget; curFunction()->capturedArguments = prev->capturedArguments; emitFunctionPrologue( AF, Builder.createBasicBlock(newFunc), InitES5CaptureState::No, DoEmitParameters::Yes); genStatement(AF->_body); emitFunctionEpilogue(Builder.getLiteralUndefined()); } // Emit CreateFunctionInst after we have restored the builder state. return Builder.createCreateFunctionInst(newFunc); } #ifndef HERMESVM_LEAN namespace { ESTree::NodeKind getLazyFunctionKind(ESTree::FunctionLikeNode *node) { if (node->isMethodDefinition) { // This is not a regular function expression but getter/setter. // If we want to reparse it later, we have to start from an // identifier and not from a 'function' keyword. return ESTree::NodeKind::Property; } return node->getKind(); } } // namespace Function *ESTreeIRGen::genES5Function( Identifier originalName, Variable *lazyClosureAlias, ESTree::FunctionLikeNode *functionNode, bool isGeneratorInnerFunction) { assert(functionNode && "Function AST cannot be null"); auto *body = ESTree::getBlockStatement(functionNode); assert(body && "body of ES5 function cannot be null"); Function *newFunction = isGeneratorInnerFunction ? Builder.createGeneratorInnerFunction( originalName, Function::DefinitionKind::ES5Function, ESTree::isStrict(functionNode->strictness), functionNode->getSourceRange(), /* insertBefore */ nullptr) : Builder.createFunction( originalName, Function::DefinitionKind::ES5Function, ESTree::isStrict(functionNode->strictness), functionNode->getSourceRange(), /* isGlobal */ false, /* insertBefore */ nullptr); newFunction->setLazyClosureAlias(lazyClosureAlias); if (auto *bodyBlock = llvh::dyn_cast<ESTree::BlockStatementNode>(body)) { if (bodyBlock->isLazyFunctionBody) { // Set the AST position and variable context so we can continue later. newFunction->setLazyScope(saveCurrentScope()); auto &lazySource = newFunction->getLazySource(); lazySource.bufferId = bodyBlock->bufferId; lazySource.nodeKind = getLazyFunctionKind(functionNode); lazySource.functionRange = functionNode->getSourceRange(); // Set the function's .length. newFunction->setExpectedParamCountIncludingThis( countExpectedArgumentsIncludingThis(functionNode)); return newFunction; } } FunctionContext newFunctionContext{ this, newFunction, functionNode->getSemInfo()}; if (isGeneratorInnerFunction) { // StartGeneratorInst // ResumeGeneratorInst // at the beginning of the function, to allow for the first .next() call. auto *initGenBB = Builder.createBasicBlock(newFunction); Builder.setInsertionBlock(initGenBB); Builder.createStartGeneratorInst(); auto *prologueBB = Builder.createBasicBlock(newFunction); auto *prologueResumeIsReturn = Builder.createAllocStackInst( genAnonymousLabelName("isReturn_prologue")); genResumeGenerator(nullptr, prologueResumeIsReturn, prologueBB); if (hasSimpleParams(functionNode)) { // If there are simple params, then we don't need an extra yield/resume. // They can simply be initialized on the first call to `.next`. Builder.setInsertionBlock(prologueBB); emitFunctionPrologue( functionNode, prologueBB, InitES5CaptureState::Yes, DoEmitParameters::Yes); } else { // If there are non-simple params, then we must add a new yield/resume. // The `.next()` call will occur once in the outer function, before // the iterator is returned to the caller of the `function*`. auto *entryPointBB = Builder.createBasicBlock(newFunction); auto *entryPointResumeIsReturn = Builder.createAllocStackInst(genAnonymousLabelName("isReturn_entry")); // Initialize parameters. Builder.setInsertionBlock(prologueBB); emitFunctionPrologue( functionNode, prologueBB, InitES5CaptureState::Yes, DoEmitParameters::Yes); Builder.createSaveAndYieldInst( Builder.getLiteralUndefined(), entryPointBB); // Actual entry point of function from the caller's perspective. Builder.setInsertionBlock(entryPointBB); genResumeGenerator( nullptr, entryPointResumeIsReturn, Builder.createBasicBlock(newFunction)); } } else { emitFunctionPrologue( functionNode, Builder.createBasicBlock(newFunction), InitES5CaptureState::Yes, DoEmitParameters::Yes); } genStatement(body); emitFunctionEpilogue(Builder.getLiteralUndefined()); return curFunction()->function; } #endif Function *ESTreeIRGen::genGeneratorFunction( Identifier originalName, Variable *lazyClosureAlias, ESTree::FunctionLikeNode *functionNode) { assert(functionNode && "Function AST cannot be null"); // Build the outer function which creates the generator. // Does not have an associated source range. auto *outerFn = Builder.createGeneratorFunction( originalName, Function::DefinitionKind::ES5Function, ESTree::isStrict(functionNode->strictness), /* insertBefore */ nullptr); auto *innerFn = genES5Function( genAnonymousLabelName(originalName.isValid() ? originalName.str() : ""), lazyClosureAlias, functionNode, true); { FunctionContext outerFnContext{this, outerFn, functionNode->getSemInfo()}; emitFunctionPrologue( functionNode, Builder.createBasicBlock(outerFn), InitES5CaptureState::Yes, DoEmitParameters::No); // Create a generator function, which will store the arguments. auto *gen = Builder.createCreateGeneratorInst(innerFn); if (!hasSimpleParams(functionNode)) { // If there are non-simple params, step the inner function once to // initialize them. Value *next = Builder.createLoadPropertyInst(gen, "next"); Builder.createCallInst(next, gen, {}); } emitFunctionEpilogue(gen); } return outerFn; } void ESTreeIRGen::initCaptureStateInES5FunctionHelper() { // Capture "this", "new.target" and "arguments" if there are inner arrows. if (!curFunction()->getSemInfo()->containsArrowFunctions) return; auto *scope = curFunction()->function->getFunctionScope(); // "this". curFunction()->capturedThis = Builder.createVariable( scope, Variable::DeclKind::Var, genAnonymousLabelName("this")); emitStore( Builder, Builder.getFunction()->getThisParameter(), curFunction()->capturedThis, true); // "new.target". curFunction()->capturedNewTarget = Builder.createVariable( scope, Variable::DeclKind::Var, genAnonymousLabelName("new.target")); emitStore( Builder, Builder.createGetNewTargetInst(), curFunction()->capturedNewTarget, true); // "arguments". if (curFunction()->getSemInfo()->containsArrowFunctionsUsingArguments) { curFunction()->capturedArguments = Builder.createVariable( scope, Variable::DeclKind::Var, genAnonymousLabelName("arguments")); emitStore( Builder, curFunction()->createArgumentsInst, curFunction()->capturedArguments, true); } } void ESTreeIRGen::emitFunctionPrologue( ESTree::FunctionLikeNode *funcNode, BasicBlock *entry, InitES5CaptureState doInitES5CaptureState, DoEmitParameters doEmitParameters) { auto *newFunc = curFunction()->function; auto *semInfo = curFunction()->getSemInfo(); LLVM_DEBUG( dbgs() << "Hoisting " << (semInfo->varDecls.size() + semInfo->closures.size()) << " variable decls.\n"); Builder.setLocation(newFunc->getSourceRange().Start); // Start pumping instructions into the entry basic block. Builder.setInsertionBlock(entry); // Always insert a CreateArgumentsInst. We will delete it later if it is // unused. curFunction()->createArgumentsInst = Builder.createCreateArgumentsInst(); // Create variable declarations for each of the hoisted variables and // functions. Initialize only the variables to undefined. for (auto decl : semInfo->varDecls) { auto res = declareVariableOrGlobalProperty( newFunc, decl.kind, getNameFieldFromID(decl.identifier)); // If this is not a frame variable or it was already declared, skip. auto *var = llvh::dyn_cast<Variable>(res.first); if (!var || !res.second) continue; // Otherwise, initialize it to undefined. Builder.createStoreFrameInst(Builder.getLiteralUndefined(), var); if (var->getRelatedVariable()) { Builder.createStoreFrameInst( Builder.getLiteralUndefined(), var->getRelatedVariable()); } } for (auto *fd : semInfo->closures) { declareVariableOrGlobalProperty( newFunc, VarDecl::Kind::Var, getNameFieldFromID(fd->_id)); } // Always create the "this" parameter. It needs to be created before we // initialized the ES5 capture state. Builder.createParameter(newFunc, "this"); if (doInitES5CaptureState != InitES5CaptureState::No) initCaptureStateInES5FunctionHelper(); // Construct the parameter list. Create function parameters and register // them in the scope. if (doEmitParameters == DoEmitParameters::Yes) { emitParameters(funcNode); } else { newFunc->setExpectedParamCountIncludingThis( countExpectedArgumentsIncludingThis(funcNode)); } // Generate the code for import declarations before generating the rest of the // body. for (auto importDecl : semInfo->imports) { genImportDeclaration(importDecl); } // Generate and initialize the code for the hoisted function declarations // before generating the rest of the body. for (auto funcDecl : semInfo->closures) { genFunctionDeclaration(funcDecl); } } void ESTreeIRGen::emitParameters(ESTree::FunctionLikeNode *funcNode) { auto *newFunc = curFunction()->function; LLVM_DEBUG(dbgs() << "IRGen function parameters.\n"); // Create a variable for every parameter. for (auto paramDecl : funcNode->getSemInfo()->paramNames) { Identifier paramName = getNameFieldFromID(paramDecl.identifier); LLVM_DEBUG(dbgs() << "Adding parameter: " << paramName << "\n"); auto *paramStorage = Builder.createVariable( newFunc->getFunctionScope(), Variable::DeclKind::Var, paramName); // Register the storage for the parameter. nameTable_.insert(paramName, paramStorage); } // FIXME: T42569352 TDZ for parameters used in initializer expressions. uint32_t paramIndex = uint32_t{0} - 1; for (auto &elem : ESTree::getParams(funcNode)) { ESTree::Node *param = &elem; ESTree::Node *init = nullptr; ++paramIndex; if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(param)) { createLRef(rest->_argument, true) .emitStore(genBuiltinCall( BuiltinMethod::HermesBuiltin_copyRestArgs, Builder.getLiteralNumber(paramIndex))); break; } // Unpack the optional initialization. if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(param)) { param = assign->_left; init = assign->_right; } Identifier formalParamName = llvh::isa<ESTree::IdentifierNode>(param) ? getNameFieldFromID(param) : genAnonymousLabelName("param"); auto *formalParam = Builder.createParameter(newFunc, formalParamName); createLRef(param, true) .emitStore( emitOptionalInitialization(formalParam, init, formalParamName)); } newFunc->setExpectedParamCountIncludingThis( countExpectedArgumentsIncludingThis(funcNode)); } uint32_t ESTreeIRGen::countExpectedArgumentsIncludingThis( ESTree::FunctionLikeNode *funcNode) { // Start at 1 to account for "this". uint32_t count = 1; for (auto &param : ESTree::getParams(funcNode)) { if (llvh::isa<ESTree::AssignmentPatternNode>(param)) { // Found an initializer, stop counting expected arguments. break; } ++count; } return count; } void ESTreeIRGen::emitFunctionEpilogue(Value *returnValue) { if (returnValue) { Builder.setLocation(SourceErrorManager::convertEndToLocation( Builder.getFunction()->getSourceRange())); Builder.createReturnInst(returnValue); } // Delete CreateArgumentsInst if it is unused. if (!curFunction()->createArgumentsInst->hasUsers()) curFunction()->createArgumentsInst->eraseFromParent(); curFunction()->function->clearStatementCount(); } void ESTreeIRGen::genDummyFunction(Function *dummy) { IRBuilder builder{dummy}; builder.createParameter(dummy, "this"); BasicBlock *firstBlock = builder.createBasicBlock(dummy); builder.setInsertionBlock(firstBlock); builder.createUnreachableInst(); builder.createReturnInst(builder.getLiteralUndefined()); } /// Generate a function which immediately throws the specified SyntaxError /// message. Function *ESTreeIRGen::genSyntaxErrorFunction( Module *M, Identifier originalName, SMRange sourceRange, StringRef error) { IRBuilder builder{M}; Function *function = builder.createFunction( originalName, Function::DefinitionKind::ES5Function, true, sourceRange, false); builder.createParameter(function, "this"); BasicBlock *firstBlock = builder.createBasicBlock(function); builder.setInsertionBlock(firstBlock); builder.createThrowInst(builder.createCallInst( emitLoad( builder, builder.createGlobalObjectProperty("SyntaxError", false)), builder.getLiteralUndefined(), builder.getLiteralString(error))); return function; } } // namespace irgen } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_4256_3
crossvul-cpp_data_bad_1309_0
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include "opencv2/core/hal/intrin.hpp" #include "opencl_kernels_video.hpp" using namespace std; #define EPS 0.001F #define INF 1E+10F namespace cv { class DISOpticalFlowImpl CV_FINAL : public DISOpticalFlow { public: DISOpticalFlowImpl(); void calc(InputArray I0, InputArray I1, InputOutputArray flow) CV_OVERRIDE; void collectGarbage() CV_OVERRIDE; protected: //!< algorithm parameters int finest_scale, coarsest_scale; int patch_size; int patch_stride; int grad_descent_iter; int variational_refinement_iter; float variational_refinement_alpha; float variational_refinement_gamma; float variational_refinement_delta; bool use_mean_normalization; bool use_spatial_propagation; protected: //!< some auxiliary variables int border_size; int w, h; //!< flow buffer width and height on the current scale int ws, hs; //!< sparse flow buffer width and height on the current scale public: int getFinestScale() const CV_OVERRIDE { return finest_scale; } void setFinestScale(int val) CV_OVERRIDE { finest_scale = val; } int getPatchSize() const CV_OVERRIDE { return patch_size; } void setPatchSize(int val) CV_OVERRIDE { patch_size = val; } int getPatchStride() const CV_OVERRIDE { return patch_stride; } void setPatchStride(int val) CV_OVERRIDE { patch_stride = val; } int getGradientDescentIterations() const CV_OVERRIDE { return grad_descent_iter; } void setGradientDescentIterations(int val) CV_OVERRIDE { grad_descent_iter = val; } int getVariationalRefinementIterations() const CV_OVERRIDE { return variational_refinement_iter; } void setVariationalRefinementIterations(int val) CV_OVERRIDE { variational_refinement_iter = val; } float getVariationalRefinementAlpha() const CV_OVERRIDE { return variational_refinement_alpha; } void setVariationalRefinementAlpha(float val) CV_OVERRIDE { variational_refinement_alpha = val; } float getVariationalRefinementDelta() const CV_OVERRIDE { return variational_refinement_delta; } void setVariationalRefinementDelta(float val) CV_OVERRIDE { variational_refinement_delta = val; } float getVariationalRefinementGamma() const CV_OVERRIDE { return variational_refinement_gamma; } void setVariationalRefinementGamma(float val) CV_OVERRIDE { variational_refinement_gamma = val; } bool getUseMeanNormalization() const CV_OVERRIDE { return use_mean_normalization; } void setUseMeanNormalization(bool val) CV_OVERRIDE { use_mean_normalization = val; } bool getUseSpatialPropagation() const CV_OVERRIDE { return use_spatial_propagation; } void setUseSpatialPropagation(bool val) CV_OVERRIDE { use_spatial_propagation = val; } protected: //!< internal buffers vector<Mat_<uchar> > I0s; //!< Gaussian pyramid for the current frame vector<Mat_<uchar> > I1s; //!< Gaussian pyramid for the next frame vector<Mat_<uchar> > I1s_ext; //!< I1s with borders vector<Mat_<short> > I0xs; //!< Gaussian pyramid for the x gradient of the current frame vector<Mat_<short> > I0ys; //!< Gaussian pyramid for the y gradient of the current frame vector<Mat_<float> > Ux; //!< x component of the flow vectors vector<Mat_<float> > Uy; //!< y component of the flow vectors vector<Mat_<float> > initial_Ux; //!< x component of the initial flow field, if one was passed as an input vector<Mat_<float> > initial_Uy; //!< y component of the initial flow field, if one was passed as an input Mat_<Vec2f> U; //!< a buffer for the merged flow Mat_<float> Sx; //!< intermediate sparse flow representation (x component) Mat_<float> Sy; //!< intermediate sparse flow representation (y component) /* Structure tensor components: */ Mat_<float> I0xx_buf; //!< sum of squares of x gradient values Mat_<float> I0yy_buf; //!< sum of squares of y gradient values Mat_<float> I0xy_buf; //!< sum of x and y gradient products /* Extra buffers that are useful if patch mean-normalization is used: */ Mat_<float> I0x_buf; //!< sum of x gradient values Mat_<float> I0y_buf; //!< sum of y gradient values /* Auxiliary buffers used in structure tensor computation: */ Mat_<float> I0xx_buf_aux; Mat_<float> I0yy_buf_aux; Mat_<float> I0xy_buf_aux; Mat_<float> I0x_buf_aux; Mat_<float> I0y_buf_aux; vector<Ptr<VariationalRefinement> > variational_refinement_processors; private: //!< private methods and parallel sections void prepareBuffers(Mat &I0, Mat &I1, Mat &flow, bool use_flow); void precomputeStructureTensor(Mat &dst_I0xx, Mat &dst_I0yy, Mat &dst_I0xy, Mat &dst_I0x, Mat &dst_I0y, Mat &I0x, Mat &I0y); struct PatchInverseSearch_ParBody : public ParallelLoopBody { DISOpticalFlowImpl *dis; int nstripes, stripe_sz; int hs; Mat *Sx, *Sy, *Ux, *Uy, *I0, *I1, *I0x, *I0y; int num_iter, pyr_level; PatchInverseSearch_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _hs, Mat &dst_Sx, Mat &dst_Sy, Mat &src_Ux, Mat &src_Uy, Mat &_I0, Mat &_I1, Mat &_I0x, Mat &_I0y, int _num_iter, int _pyr_level); void operator()(const Range &range) const CV_OVERRIDE; }; struct Densification_ParBody : public ParallelLoopBody { DISOpticalFlowImpl *dis; int nstripes, stripe_sz; int h; Mat *Ux, *Uy, *Sx, *Sy, *I0, *I1; Densification_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _h, Mat &dst_Ux, Mat &dst_Uy, Mat &src_Sx, Mat &src_Sy, Mat &_I0, Mat &_I1); void operator()(const Range &range) const CV_OVERRIDE; }; #ifdef HAVE_OPENCL vector<UMat> u_I0s; //!< Gaussian pyramid for the current frame vector<UMat> u_I1s; //!< Gaussian pyramid for the next frame vector<UMat> u_I1s_ext; //!< I1s with borders vector<UMat> u_I0xs; //!< Gaussian pyramid for the x gradient of the current frame vector<UMat> u_I0ys; //!< Gaussian pyramid for the y gradient of the current frame vector<UMat> u_Ux; //!< x component of the flow vectors vector<UMat> u_Uy; //!< y component of the flow vectors vector<UMat> u_initial_Ux; //!< x component of the initial flow field, if one was passed as an input vector<UMat> u_initial_Uy; //!< y component of the initial flow field, if one was passed as an input UMat u_U; //!< a buffer for the merged flow UMat u_Sx; //!< intermediate sparse flow representation (x component) UMat u_Sy; //!< intermediate sparse flow representation (y component) /* Structure tensor components: */ UMat u_I0xx_buf; //!< sum of squares of x gradient values UMat u_I0yy_buf; //!< sum of squares of y gradient values UMat u_I0xy_buf; //!< sum of x and y gradient products /* Extra buffers that are useful if patch mean-normalization is used: */ UMat u_I0x_buf; //!< sum of x gradient values UMat u_I0y_buf; //!< sum of y gradient values /* Auxiliary buffers used in structure tensor computation: */ UMat u_I0xx_buf_aux; UMat u_I0yy_buf_aux; UMat u_I0xy_buf_aux; UMat u_I0x_buf_aux; UMat u_I0y_buf_aux; bool ocl_precomputeStructureTensor(UMat &dst_I0xx, UMat &dst_I0yy, UMat &dst_I0xy, UMat &dst_I0x, UMat &dst_I0y, UMat &I0x, UMat &I0y); void ocl_prepareBuffers(UMat &I0, UMat &I1, UMat &flow, bool use_flow); bool ocl_calc(InputArray I0, InputArray I1, InputOutputArray flow); bool ocl_Densification(UMat &dst_Ux, UMat &dst_Uy, UMat &src_Sx, UMat &src_Sy, UMat &_I0, UMat &_I1); bool ocl_PatchInverseSearch(UMat &src_Ux, UMat &src_Uy, UMat &I0, UMat &I1, UMat &I0x, UMat &I0y, int num_iter, int pyr_level); #endif }; DISOpticalFlowImpl::DISOpticalFlowImpl() { finest_scale = 2; patch_size = 8; patch_stride = 4; grad_descent_iter = 16; variational_refinement_iter = 5; variational_refinement_alpha = 20.f; variational_refinement_gamma = 10.f; variational_refinement_delta = 5.f; border_size = 16; use_mean_normalization = true; use_spatial_propagation = true; coarsest_scale = 10; /* Use separate variational refinement instances for different scales to avoid repeated memory allocation: */ int max_possible_scales = 10; ws = hs = w = h = 0; for (int i = 0; i < max_possible_scales; i++) variational_refinement_processors.push_back(VariationalRefinement::create()); } void DISOpticalFlowImpl::prepareBuffers(Mat &I0, Mat &I1, Mat &flow, bool use_flow) { I0s.resize(coarsest_scale + 1); I1s.resize(coarsest_scale + 1); I1s_ext.resize(coarsest_scale + 1); I0xs.resize(coarsest_scale + 1); I0ys.resize(coarsest_scale + 1); Ux.resize(coarsest_scale + 1); Uy.resize(coarsest_scale + 1); Mat flow_uv[2]; if (use_flow) { split(flow, flow_uv); initial_Ux.resize(coarsest_scale + 1); initial_Uy.resize(coarsest_scale + 1); } int fraction = 1; int cur_rows = 0, cur_cols = 0; for (int i = 0; i <= coarsest_scale; i++) { /* Avoid initializing the pyramid levels above the finest scale, as they won't be used anyway */ if (i == finest_scale) { cur_rows = I0.rows / fraction; cur_cols = I0.cols / fraction; I0s[i].create(cur_rows, cur_cols); resize(I0, I0s[i], I0s[i].size(), 0.0, 0.0, INTER_AREA); I1s[i].create(cur_rows, cur_cols); resize(I1, I1s[i], I1s[i].size(), 0.0, 0.0, INTER_AREA); /* These buffers are reused in each scale so we initialize them once on the finest scale: */ Sx.create(cur_rows / patch_stride, cur_cols / patch_stride); Sy.create(cur_rows / patch_stride, cur_cols / patch_stride); I0xx_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0yy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0xy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0x_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0y_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0xx_buf_aux.create(cur_rows, cur_cols / patch_stride); I0yy_buf_aux.create(cur_rows, cur_cols / patch_stride); I0xy_buf_aux.create(cur_rows, cur_cols / patch_stride); I0x_buf_aux.create(cur_rows, cur_cols / patch_stride); I0y_buf_aux.create(cur_rows, cur_cols / patch_stride); U.create(cur_rows, cur_cols); } else if (i > finest_scale) { cur_rows = I0s[i - 1].rows / 2; cur_cols = I0s[i - 1].cols / 2; I0s[i].create(cur_rows, cur_cols); resize(I0s[i - 1], I0s[i], I0s[i].size(), 0.0, 0.0, INTER_AREA); I1s[i].create(cur_rows, cur_cols); resize(I1s[i - 1], I1s[i], I1s[i].size(), 0.0, 0.0, INTER_AREA); } if (i >= finest_scale) { I1s_ext[i].create(cur_rows + 2 * border_size, cur_cols + 2 * border_size); copyMakeBorder(I1s[i], I1s_ext[i], border_size, border_size, border_size, border_size, BORDER_REPLICATE); I0xs[i].create(cur_rows, cur_cols); I0ys[i].create(cur_rows, cur_cols); spatialGradient(I0s[i], I0xs[i], I0ys[i]); Ux[i].create(cur_rows, cur_cols); Uy[i].create(cur_rows, cur_cols); variational_refinement_processors[i]->setAlpha(variational_refinement_alpha); variational_refinement_processors[i]->setDelta(variational_refinement_delta); variational_refinement_processors[i]->setGamma(variational_refinement_gamma); variational_refinement_processors[i]->setSorIterations(5); variational_refinement_processors[i]->setFixedPointIterations(variational_refinement_iter); if (use_flow) { resize(flow_uv[0], initial_Ux[i], Size(cur_cols, cur_rows)); initial_Ux[i] /= fraction; resize(flow_uv[1], initial_Uy[i], Size(cur_cols, cur_rows)); initial_Uy[i] /= fraction; } } fraction *= 2; } } /* This function computes the structure tensor elements (local sums of I0x^2, I0x*I0y and I0y^2). * A simple box filter is not used instead because we need to compute these sums on a sparse grid * and store them densely in the output buffers. */ void DISOpticalFlowImpl::precomputeStructureTensor(Mat &dst_I0xx, Mat &dst_I0yy, Mat &dst_I0xy, Mat &dst_I0x, Mat &dst_I0y, Mat &I0x, Mat &I0y) { float *I0xx_ptr = dst_I0xx.ptr<float>(); float *I0yy_ptr = dst_I0yy.ptr<float>(); float *I0xy_ptr = dst_I0xy.ptr<float>(); float *I0x_ptr = dst_I0x.ptr<float>(); float *I0y_ptr = dst_I0y.ptr<float>(); float *I0xx_aux_ptr = I0xx_buf_aux.ptr<float>(); float *I0yy_aux_ptr = I0yy_buf_aux.ptr<float>(); float *I0xy_aux_ptr = I0xy_buf_aux.ptr<float>(); float *I0x_aux_ptr = I0x_buf_aux.ptr<float>(); float *I0y_aux_ptr = I0y_buf_aux.ptr<float>(); /* Separable box filter: horizontal pass */ for (int i = 0; i < h; i++) { float sum_xx = 0.0f, sum_yy = 0.0f, sum_xy = 0.0f, sum_x = 0.0f, sum_y = 0.0f; short *x_row = I0x.ptr<short>(i); short *y_row = I0y.ptr<short>(i); for (int j = 0; j < patch_size; j++) { sum_xx += x_row[j] * x_row[j]; sum_yy += y_row[j] * y_row[j]; sum_xy += x_row[j] * y_row[j]; sum_x += x_row[j]; sum_y += y_row[j]; } I0xx_aux_ptr[i * ws] = sum_xx; I0yy_aux_ptr[i * ws] = sum_yy; I0xy_aux_ptr[i * ws] = sum_xy; I0x_aux_ptr[i * ws] = sum_x; I0y_aux_ptr[i * ws] = sum_y; int js = 1; for (int j = patch_size; j < w; j++) { sum_xx += (x_row[j] * x_row[j] - x_row[j - patch_size] * x_row[j - patch_size]); sum_yy += (y_row[j] * y_row[j] - y_row[j - patch_size] * y_row[j - patch_size]); sum_xy += (x_row[j] * y_row[j] - x_row[j - patch_size] * y_row[j - patch_size]); sum_x += (x_row[j] - x_row[j - patch_size]); sum_y += (y_row[j] - y_row[j - patch_size]); if ((j - patch_size + 1) % patch_stride == 0) { I0xx_aux_ptr[i * ws + js] = sum_xx; I0yy_aux_ptr[i * ws + js] = sum_yy; I0xy_aux_ptr[i * ws + js] = sum_xy; I0x_aux_ptr[i * ws + js] = sum_x; I0y_aux_ptr[i * ws + js] = sum_y; js++; } } } AutoBuffer<float> sum_xx(ws), sum_yy(ws), sum_xy(ws), sum_x(ws), sum_y(ws); for (int j = 0; j < ws; j++) { sum_xx[j] = 0.0f; sum_yy[j] = 0.0f; sum_xy[j] = 0.0f; sum_x[j] = 0.0f; sum_y[j] = 0.0f; } /* Separable box filter: vertical pass */ for (int i = 0; i < patch_size; i++) for (int j = 0; j < ws; j++) { sum_xx[j] += I0xx_aux_ptr[i * ws + j]; sum_yy[j] += I0yy_aux_ptr[i * ws + j]; sum_xy[j] += I0xy_aux_ptr[i * ws + j]; sum_x[j] += I0x_aux_ptr[i * ws + j]; sum_y[j] += I0y_aux_ptr[i * ws + j]; } for (int j = 0; j < ws; j++) { I0xx_ptr[j] = sum_xx[j]; I0yy_ptr[j] = sum_yy[j]; I0xy_ptr[j] = sum_xy[j]; I0x_ptr[j] = sum_x[j]; I0y_ptr[j] = sum_y[j]; } int is = 1; for (int i = patch_size; i < h; i++) { for (int j = 0; j < ws; j++) { sum_xx[j] += (I0xx_aux_ptr[i * ws + j] - I0xx_aux_ptr[(i - patch_size) * ws + j]); sum_yy[j] += (I0yy_aux_ptr[i * ws + j] - I0yy_aux_ptr[(i - patch_size) * ws + j]); sum_xy[j] += (I0xy_aux_ptr[i * ws + j] - I0xy_aux_ptr[(i - patch_size) * ws + j]); sum_x[j] += (I0x_aux_ptr[i * ws + j] - I0x_aux_ptr[(i - patch_size) * ws + j]); sum_y[j] += (I0y_aux_ptr[i * ws + j] - I0y_aux_ptr[(i - patch_size) * ws + j]); } if ((i - patch_size + 1) % patch_stride == 0) { for (int j = 0; j < ws; j++) { I0xx_ptr[is * ws + j] = sum_xx[j]; I0yy_ptr[is * ws + j] = sum_yy[j]; I0xy_ptr[is * ws + j] = sum_xy[j]; I0x_ptr[is * ws + j] = sum_x[j]; I0y_ptr[is * ws + j] = sum_y[j]; } is++; } } } DISOpticalFlowImpl::PatchInverseSearch_ParBody::PatchInverseSearch_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _hs, Mat &dst_Sx, Mat &dst_Sy, Mat &src_Ux, Mat &src_Uy, Mat &_I0, Mat &_I1, Mat &_I0x, Mat &_I0y, int _num_iter, int _pyr_level) : dis(&_dis), nstripes(_nstripes), hs(_hs), Sx(&dst_Sx), Sy(&dst_Sy), Ux(&src_Ux), Uy(&src_Uy), I0(&_I0), I1(&_I1), I0x(&_I0x), I0y(&_I0y), num_iter(_num_iter), pyr_level(_pyr_level) { stripe_sz = (int)ceil(hs / (double)nstripes); } /////////////////////////////////////////////* Patch processing functions *///////////////////////////////////////////// /* Some auxiliary macros */ #define HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION \ v_float32x4 w00v = v_setall_f32(w00); \ v_float32x4 w01v = v_setall_f32(w01); \ v_float32x4 w10v = v_setall_f32(w10); \ v_float32x4 w11v = v_setall_f32(w11); \ \ v_uint8x16 I0_row_16, I1_row_16, I1_row_shifted_16, I1_row_next_16, I1_row_next_shifted_16; \ v_uint16x8 I0_row_8, I1_row_8, I1_row_shifted_8, I1_row_next_8, I1_row_next_shifted_8, tmp; \ v_uint32x4 I0_row_4_left, I1_row_4_left, I1_row_shifted_4_left, I1_row_next_4_left, I1_row_next_shifted_4_left; \ v_uint32x4 I0_row_4_right, I1_row_4_right, I1_row_shifted_4_right, I1_row_next_4_right, \ I1_row_next_shifted_4_right; \ v_float32x4 I_diff_left, I_diff_right; \ \ /* Preload and expand the first row of I1: */ \ I1_row_16 = v_load(I1_ptr); \ I1_row_shifted_16 = v_extract<1>(I1_row_16, I1_row_16); \ v_expand(I1_row_16, I1_row_8, tmp); \ v_expand(I1_row_shifted_16, I1_row_shifted_8, tmp); \ v_expand(I1_row_8, I1_row_4_left, I1_row_4_right); \ v_expand(I1_row_shifted_8, I1_row_shifted_4_left, I1_row_shifted_4_right); \ I1_ptr += I1_stride; #define HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION \ /* Load the next row of I1: */ \ I1_row_next_16 = v_load(I1_ptr); \ /* Circular shift left by 1 element: */ \ I1_row_next_shifted_16 = v_extract<1>(I1_row_next_16, I1_row_next_16); \ /* Expand to 8 ushorts (we only need the first 8 values): */ \ v_expand(I1_row_next_16, I1_row_next_8, tmp); \ v_expand(I1_row_next_shifted_16, I1_row_next_shifted_8, tmp); \ /* Separate the left and right halves: */ \ v_expand(I1_row_next_8, I1_row_next_4_left, I1_row_next_4_right); \ v_expand(I1_row_next_shifted_8, I1_row_next_shifted_4_left, I1_row_next_shifted_4_right); \ \ /* Load current row of I0: */ \ I0_row_16 = v_load(I0_ptr); \ v_expand(I0_row_16, I0_row_8, tmp); \ v_expand(I0_row_8, I0_row_4_left, I0_row_4_right); \ \ /* Compute diffs between I0 and bilinearly interpolated I1: */ \ I_diff_left = w00v * v_cvt_f32(v_reinterpret_as_s32(I1_row_4_left)) + \ w01v * v_cvt_f32(v_reinterpret_as_s32(I1_row_shifted_4_left)) + \ w10v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_4_left)) + \ w11v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_shifted_4_left)) - \ v_cvt_f32(v_reinterpret_as_s32(I0_row_4_left)); \ I_diff_right = w00v * v_cvt_f32(v_reinterpret_as_s32(I1_row_4_right)) + \ w01v * v_cvt_f32(v_reinterpret_as_s32(I1_row_shifted_4_right)) + \ w10v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_4_right)) + \ w11v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_shifted_4_right)) - \ v_cvt_f32(v_reinterpret_as_s32(I0_row_4_right)); #define HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW \ I0_ptr += I0_stride; \ I1_ptr += I1_stride; \ \ I1_row_4_left = I1_row_next_4_left; \ I1_row_4_right = I1_row_next_4_right; \ I1_row_shifted_4_left = I1_row_next_shifted_4_left; \ I1_row_shifted_4_right = I1_row_next_shifted_4_right; /* This function essentially performs one iteration of gradient descent when finding the most similar patch in I1 for a * given one in I0. It assumes that I0_ptr and I1_ptr already point to the corresponding patches and w00, w01, w10, w11 * are precomputed bilinear interpolation weights. It returns the SSD (sum of squared differences) between these patches * and computes the values (dst_dUx, dst_dUy) that are used in the flow vector update. HAL acceleration is implemented * only for the default patch size (8x8). Everything is processed in floats as using fixed-point approximations harms * the quality significantly. */ inline float processPatch(float &dst_dUx, float &dst_dUy, uchar *I0_ptr, uchar *I1_ptr, short *I0x_ptr, short *I0y_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz) { float SSD = 0.0f; #if CV_SIMD128 if (patch_sz == 8) { /* Variables to accumulate the sums */ v_float32x4 Ux_vec = v_setall_f32(0); v_float32x4 Uy_vec = v_setall_f32(0); v_float32x4 SSD_vec = v_setall_f32(0); v_int16x8 I0x_row, I0y_row; v_int32x4 I0x_row_4_left, I0x_row_4_right, I0y_row_4_left, I0y_row_4_right; HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; I0x_row = v_load(I0x_ptr); v_expand(I0x_row, I0x_row_4_left, I0x_row_4_right); I0y_row = v_load(I0y_ptr); v_expand(I0y_row, I0y_row_4_left, I0y_row_4_right); /* Update the sums: */ Ux_vec += I_diff_left * v_cvt_f32(I0x_row_4_left) + I_diff_right * v_cvt_f32(I0x_row_4_right); Uy_vec += I_diff_left * v_cvt_f32(I0y_row_4_left) + I_diff_right * v_cvt_f32(I0y_row_4_right); SSD_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; I0x_ptr += I0_stride; I0y_ptr += I0_stride; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } /* Final reduce operations: */ dst_dUx = v_reduce_sum(Ux_vec); dst_dUy = v_reduce_sum(Uy_vec); SSD = v_reduce_sum(SSD_vec); } else { #endif dst_dUx = 0.0f; dst_dUy = 0.0f; float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; SSD += diff * diff; dst_dUx += diff * I0x_ptr[i * I0_stride + j]; dst_dUy += diff * I0y_ptr[i * I0_stride + j]; } #if CV_SIMD128 } #endif return SSD; } /* Same as processPatch, but with patch mean normalization, which improves robustness under changing * lighting conditions */ inline float processPatchMeanNorm(float &dst_dUx, float &dst_dUy, uchar *I0_ptr, uchar *I1_ptr, short *I0x_ptr, short *I0y_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz, float x_grad_sum, float y_grad_sum) { float sum_diff = 0.0, sum_diff_sq = 0.0; float sum_I0x_mul = 0.0, sum_I0y_mul = 0.0; float n = (float)patch_sz * patch_sz; #if CV_SIMD128 if (patch_sz == 8) { /* Variables to accumulate the sums */ v_float32x4 sum_I0x_mul_vec = v_setall_f32(0); v_float32x4 sum_I0y_mul_vec = v_setall_f32(0); v_float32x4 sum_diff_vec = v_setall_f32(0); v_float32x4 sum_diff_sq_vec = v_setall_f32(0); v_int16x8 I0x_row, I0y_row; v_int32x4 I0x_row_4_left, I0x_row_4_right, I0y_row_4_left, I0y_row_4_right; HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; I0x_row = v_load(I0x_ptr); v_expand(I0x_row, I0x_row_4_left, I0x_row_4_right); I0y_row = v_load(I0y_ptr); v_expand(I0y_row, I0y_row_4_left, I0y_row_4_right); /* Update the sums: */ sum_I0x_mul_vec += I_diff_left * v_cvt_f32(I0x_row_4_left) + I_diff_right * v_cvt_f32(I0x_row_4_right); sum_I0y_mul_vec += I_diff_left * v_cvt_f32(I0y_row_4_left) + I_diff_right * v_cvt_f32(I0y_row_4_right); sum_diff_sq_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; sum_diff_vec += I_diff_left + I_diff_right; I0x_ptr += I0_stride; I0y_ptr += I0_stride; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } /* Final reduce operations: */ sum_I0x_mul = v_reduce_sum(sum_I0x_mul_vec); sum_I0y_mul = v_reduce_sum(sum_I0y_mul_vec); sum_diff = v_reduce_sum(sum_diff_vec); sum_diff_sq = v_reduce_sum(sum_diff_sq_vec); } else { #endif float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; sum_diff += diff; sum_diff_sq += diff * diff; sum_I0x_mul += diff * I0x_ptr[i * I0_stride + j]; sum_I0y_mul += diff * I0y_ptr[i * I0_stride + j]; } #if CV_SIMD128 } #endif dst_dUx = sum_I0x_mul - sum_diff * x_grad_sum / n; dst_dUy = sum_I0y_mul - sum_diff * y_grad_sum / n; return sum_diff_sq - sum_diff * sum_diff / n; } /* Similar to processPatch, but compute only the sum of squared differences (SSD) between the patches */ inline float computeSSD(uchar *I0_ptr, uchar *I1_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz) { float SSD = 0.0f; #if CV_SIMD128 if (patch_sz == 8) { v_float32x4 SSD_vec = v_setall_f32(0); HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; SSD_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } SSD = v_reduce_sum(SSD_vec); } else { #endif float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; SSD += diff * diff; } #if CV_SIMD128 } #endif return SSD; } /* Same as computeSSD, but with patch mean normalization */ inline float computeSSDMeanNorm(uchar *I0_ptr, uchar *I1_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz) { float sum_diff = 0.0f, sum_diff_sq = 0.0f; float n = (float)patch_sz * patch_sz; #if CV_SIMD128 if (patch_sz == 8) { v_float32x4 sum_diff_vec = v_setall_f32(0); v_float32x4 sum_diff_sq_vec = v_setall_f32(0); HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; sum_diff_sq_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; sum_diff_vec += I_diff_left + I_diff_right; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } sum_diff = v_reduce_sum(sum_diff_vec); sum_diff_sq = v_reduce_sum(sum_diff_sq_vec); } else { #endif float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; sum_diff += diff; sum_diff_sq += diff * diff; } #if CV_SIMD128 } #endif return sum_diff_sq - sum_diff * sum_diff / n; } #undef HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION #undef HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION #undef HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DISOpticalFlowImpl::PatchInverseSearch_ParBody::operator()(const Range &range) const { // force separate processing of stripes if we are using spatial propagation: if (dis->use_spatial_propagation && range.end > range.start + 1) { for (int n = range.start; n < range.end; n++) (*this)(Range(n, n + 1)); return; } int psz = dis->patch_size; int psz2 = psz / 2; int w_ext = dis->w + 2 * dis->border_size; //!< width of I1_ext int bsz = dis->border_size; /* Input dense flow */ float *Ux_ptr = Ux->ptr<float>(); float *Uy_ptr = Uy->ptr<float>(); /* Output sparse flow */ float *Sx_ptr = Sx->ptr<float>(); float *Sy_ptr = Sy->ptr<float>(); uchar *I0_ptr = I0->ptr<uchar>(); uchar *I1_ptr = I1->ptr<uchar>(); short *I0x_ptr = I0x->ptr<short>(); short *I0y_ptr = I0y->ptr<short>(); /* Precomputed structure tensor */ float *xx_ptr = dis->I0xx_buf.ptr<float>(); float *yy_ptr = dis->I0yy_buf.ptr<float>(); float *xy_ptr = dis->I0xy_buf.ptr<float>(); /* And extra buffers for mean-normalization: */ float *x_ptr = dis->I0x_buf.ptr<float>(); float *y_ptr = dis->I0y_buf.ptr<float>(); bool use_temporal_candidates = false; float *initial_Ux_ptr = NULL, *initial_Uy_ptr = NULL; if (!dis->initial_Ux.empty()) { initial_Ux_ptr = dis->initial_Ux[pyr_level].ptr<float>(); initial_Uy_ptr = dis->initial_Uy[pyr_level].ptr<float>(); use_temporal_candidates = true; } int i, j, dir; int start_is, end_is, start_js, end_js; int start_i, start_j; float i_lower_limit = bsz - psz + 1.0f; float i_upper_limit = bsz + dis->h - 1.0f; float j_lower_limit = bsz - psz + 1.0f; float j_upper_limit = bsz + dis->w - 1.0f; float dUx, dUy, i_I1, j_I1, w00, w01, w10, w11, dx, dy; #define INIT_BILINEAR_WEIGHTS(Ux, Uy) \ i_I1 = min(max(i + Uy + bsz, i_lower_limit), i_upper_limit); \ j_I1 = min(max(j + Ux + bsz, j_lower_limit), j_upper_limit); \ \ w11 = (i_I1 - floor(i_I1)) * (j_I1 - floor(j_I1)); \ w10 = (i_I1 - floor(i_I1)) * (floor(j_I1) + 1 - j_I1); \ w01 = (floor(i_I1) + 1 - i_I1) * (j_I1 - floor(j_I1)); \ w00 = (floor(i_I1) + 1 - i_I1) * (floor(j_I1) + 1 - j_I1); #define COMPUTE_SSD(dst, Ux, Uy) \ INIT_BILINEAR_WEIGHTS(Ux, Uy); \ if (dis->use_mean_normalization) \ dst = computeSSDMeanNorm(I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, dis->w, w_ext, w00, \ w01, w10, w11, psz); \ else \ dst = computeSSD(I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, dis->w, w_ext, w00, w01, \ w10, w11, psz); int num_inner_iter = (int)floor(dis->grad_descent_iter / (float)num_iter); for (int iter = 0; iter < num_iter; iter++) { if (iter % 2 == 0) { dir = 1; start_is = min(range.start * stripe_sz, hs); end_is = min(range.end * stripe_sz, hs); start_js = 0; end_js = dis->ws; start_i = start_is * dis->patch_stride; start_j = 0; } else { dir = -1; start_is = min(range.end * stripe_sz, hs) - 1; end_is = min(range.start * stripe_sz, hs) - 1; start_js = dis->ws - 1; end_js = -1; start_i = start_is * dis->patch_stride; start_j = (dis->ws - 1) * dis->patch_stride; } i = start_i; for (int is = start_is; dir * is < dir * end_is; is += dir) { j = start_j; for (int js = start_js; dir * js < dir * end_js; js += dir) { if (iter == 0) { /* Using result form the previous pyramid level as the very first approximation: */ Sx_ptr[is * dis->ws + js] = Ux_ptr[(i + psz2) * dis->w + j + psz2]; Sy_ptr[is * dis->ws + js] = Uy_ptr[(i + psz2) * dis->w + j + psz2]; } float min_SSD = INF, cur_SSD; if (use_temporal_candidates || dis->use_spatial_propagation) { COMPUTE_SSD(min_SSD, Sx_ptr[is * dis->ws + js], Sy_ptr[is * dis->ws + js]); } if (use_temporal_candidates) { /* Try temporal candidates (vectors from the initial flow field that was passed to the function) */ COMPUTE_SSD(cur_SSD, initial_Ux_ptr[(i + psz2) * dis->w + j + psz2], initial_Uy_ptr[(i + psz2) * dis->w + j + psz2]); if (cur_SSD < min_SSD) { min_SSD = cur_SSD; Sx_ptr[is * dis->ws + js] = initial_Ux_ptr[(i + psz2) * dis->w + j + psz2]; Sy_ptr[is * dis->ws + js] = initial_Uy_ptr[(i + psz2) * dis->w + j + psz2]; } } if (dis->use_spatial_propagation) { /* Try spatial candidates: */ if (dir * js > dir * start_js) { COMPUTE_SSD(cur_SSD, Sx_ptr[is * dis->ws + js - dir], Sy_ptr[is * dis->ws + js - dir]); if (cur_SSD < min_SSD) { min_SSD = cur_SSD; Sx_ptr[is * dis->ws + js] = Sx_ptr[is * dis->ws + js - dir]; Sy_ptr[is * dis->ws + js] = Sy_ptr[is * dis->ws + js - dir]; } } /* Flow vectors won't actually propagate across different stripes, which is the reason for keeping * the number of stripes constant. It works well enough in practice and doesn't introduce any * visible seams. */ if (dir * is > dir * start_is) { COMPUTE_SSD(cur_SSD, Sx_ptr[(is - dir) * dis->ws + js], Sy_ptr[(is - dir) * dis->ws + js]); if (cur_SSD < min_SSD) { min_SSD = cur_SSD; Sx_ptr[is * dis->ws + js] = Sx_ptr[(is - dir) * dis->ws + js]; Sy_ptr[is * dis->ws + js] = Sy_ptr[(is - dir) * dis->ws + js]; } } } /* Use the best candidate as a starting point for the gradient descent: */ float cur_Ux = Sx_ptr[is * dis->ws + js]; float cur_Uy = Sy_ptr[is * dis->ws + js]; /* Computing the inverse of the structure tensor: */ float detH = xx_ptr[is * dis->ws + js] * yy_ptr[is * dis->ws + js] - xy_ptr[is * dis->ws + js] * xy_ptr[is * dis->ws + js]; if (abs(detH) < EPS) detH = EPS; float invH11 = yy_ptr[is * dis->ws + js] / detH; float invH12 = -xy_ptr[is * dis->ws + js] / detH; float invH22 = xx_ptr[is * dis->ws + js] / detH; float prev_SSD = INF, SSD; float x_grad_sum = x_ptr[is * dis->ws + js]; float y_grad_sum = y_ptr[is * dis->ws + js]; for (int t = 0; t < num_inner_iter; t++) { INIT_BILINEAR_WEIGHTS(cur_Ux, cur_Uy); if (dis->use_mean_normalization) SSD = processPatchMeanNorm(dUx, dUy, I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, I0x_ptr + i * dis->w + j, I0y_ptr + i * dis->w + j, dis->w, w_ext, w00, w01, w10, w11, psz, x_grad_sum, y_grad_sum); else SSD = processPatch(dUx, dUy, I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, I0x_ptr + i * dis->w + j, I0y_ptr + i * dis->w + j, dis->w, w_ext, w00, w01, w10, w11, psz); dx = invH11 * dUx + invH12 * dUy; dy = invH12 * dUx + invH22 * dUy; cur_Ux -= dx; cur_Uy -= dy; /* Break when patch distance stops decreasing */ if (SSD >= prev_SSD) break; prev_SSD = SSD; } /* If gradient descent converged to a flow vector that is very far from the initial approximation * (more than patch size) then we don't use it. Noticeably improves the robustness. */ if (norm(Vec2f(cur_Ux - Sx_ptr[is * dis->ws + js], cur_Uy - Sy_ptr[is * dis->ws + js])) <= psz) { Sx_ptr[is * dis->ws + js] = cur_Ux; Sy_ptr[is * dis->ws + js] = cur_Uy; } j += dir * dis->patch_stride; } i += dir * dis->patch_stride; } } #undef INIT_BILINEAR_WEIGHTS #undef COMPUTE_SSD } DISOpticalFlowImpl::Densification_ParBody::Densification_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _h, Mat &dst_Ux, Mat &dst_Uy, Mat &src_Sx, Mat &src_Sy, Mat &_I0, Mat &_I1) : dis(&_dis), nstripes(_nstripes), h(_h), Ux(&dst_Ux), Uy(&dst_Uy), Sx(&src_Sx), Sy(&src_Sy), I0(&_I0), I1(&_I1) { stripe_sz = (int)ceil(h / (double)nstripes); } /* This function transforms a sparse optical flow field obtained by PatchInverseSearch (which computes flow values * on a sparse grid defined by patch_stride) into a dense optical flow field by weighted averaging of values from the * overlapping patches. */ void DISOpticalFlowImpl::Densification_ParBody::operator()(const Range &range) const { int start_i = min(range.start * stripe_sz, h); int end_i = min(range.end * stripe_sz, h); /* Input sparse flow */ float *Sx_ptr = Sx->ptr<float>(); float *Sy_ptr = Sy->ptr<float>(); /* Output dense flow */ float *Ux_ptr = Ux->ptr<float>(); float *Uy_ptr = Uy->ptr<float>(); uchar *I0_ptr = I0->ptr<uchar>(); uchar *I1_ptr = I1->ptr<uchar>(); int psz = dis->patch_size; int pstr = dis->patch_stride; int i_l, i_u; int j_l, j_u; float i_m, j_m, diff; /* These values define the set of sparse grid locations that contain patches overlapping with the current dense flow * location */ int start_is, end_is; int start_js, end_js; /* Some helper macros for updating this set of sparse grid locations */ #define UPDATE_SPARSE_I_COORDINATES \ if (i % pstr == 0 && i + psz <= h) \ end_is++; \ if (i - psz >= 0 && (i - psz) % pstr == 0 && start_is < end_is) \ start_is++; #define UPDATE_SPARSE_J_COORDINATES \ if (j % pstr == 0 && j + psz <= dis->w) \ end_js++; \ if (j - psz >= 0 && (j - psz) % pstr == 0 && start_js < end_js) \ start_js++; start_is = 0; end_is = -1; for (int i = 0; i < start_i; i++) { UPDATE_SPARSE_I_COORDINATES; } for (int i = start_i; i < end_i; i++) { UPDATE_SPARSE_I_COORDINATES; start_js = 0; end_js = -1; for (int j = 0; j < dis->w; j++) { UPDATE_SPARSE_J_COORDINATES; float coef, sum_coef = 0.0f; float sum_Ux = 0.0f; float sum_Uy = 0.0f; /* Iterate through all the patches that overlap the current location (i,j) */ for (int is = start_is; is <= end_is; is++) for (int js = start_js; js <= end_js; js++) { j_m = min(max(j + Sx_ptr[is * dis->ws + js], 0.0f), dis->w - 1.0f - EPS); i_m = min(max(i + Sy_ptr[is * dis->ws + js], 0.0f), dis->h - 1.0f - EPS); j_l = (int)j_m; j_u = j_l + 1; i_l = (int)i_m; i_u = i_l + 1; diff = (j_m - j_l) * (i_m - i_l) * I1_ptr[i_u * dis->w + j_u] + (j_u - j_m) * (i_m - i_l) * I1_ptr[i_u * dis->w + j_l] + (j_m - j_l) * (i_u - i_m) * I1_ptr[i_l * dis->w + j_u] + (j_u - j_m) * (i_u - i_m) * I1_ptr[i_l * dis->w + j_l] - I0_ptr[i * dis->w + j]; coef = 1 / max(1.0f, abs(diff)); sum_Ux += coef * Sx_ptr[is * dis->ws + js]; sum_Uy += coef * Sy_ptr[is * dis->ws + js]; sum_coef += coef; } CV_DbgAssert(sum_coef != 0); Ux_ptr[i * dis->w + j] = sum_Ux / sum_coef; Uy_ptr[i * dis->w + j] = sum_Uy / sum_coef; } } #undef UPDATE_SPARSE_I_COORDINATES #undef UPDATE_SPARSE_J_COORDINATES } #ifdef HAVE_OPENCL bool DISOpticalFlowImpl::ocl_PatchInverseSearch(UMat &src_Ux, UMat &src_Uy, UMat &I0, UMat &I1, UMat &I0x, UMat &I0y, int num_iter, int pyr_level) { size_t globalSize[] = {(size_t)ws, (size_t)hs}; size_t localSize[] = {16, 16}; int idx; int num_inner_iter = (int)floor(grad_descent_iter / (float)num_iter); String subgroups_build_options; if (ocl::Device::getDefault().isExtensionSupported("cl_khr_subgroups")) subgroups_build_options = "-DCV_USE_SUBGROUPS=1"; for (int iter = 0; iter < num_iter; iter++) { if (iter == 0) { ocl::Kernel k1("dis_patch_inverse_search_fwd_1", ocl::video::dis_flow_oclsrc, subgroups_build_options); size_t global_sz[] = {(size_t)hs * 8}; size_t local_sz[] = {8}; idx = 0; idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(src_Ux)); idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(src_Uy)); idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k1.set(idx, (int)border_size); idx = k1.set(idx, (int)patch_size); idx = k1.set(idx, (int)patch_stride); idx = k1.set(idx, (int)w); idx = k1.set(idx, (int)h); idx = k1.set(idx, (int)ws); idx = k1.set(idx, (int)hs); idx = k1.set(idx, (int)pyr_level); idx = k1.set(idx, ocl::KernelArg::PtrWriteOnly(u_Sx)); idx = k1.set(idx, ocl::KernelArg::PtrWriteOnly(u_Sy)); if (!k1.run(1, global_sz, local_sz, false)) return false; ocl::Kernel k2("dis_patch_inverse_search_fwd_2", ocl::video::dis_flow_oclsrc); idx = 0; idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(src_Ux)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(src_Uy)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0x)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0y)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xx_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0yy_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xy_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0x_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0y_buf)); idx = k2.set(idx, (int)border_size); idx = k2.set(idx, (int)patch_size); idx = k2.set(idx, (int)patch_stride); idx = k2.set(idx, (int)w); idx = k2.set(idx, (int)h); idx = k2.set(idx, (int)ws); idx = k2.set(idx, (int)hs); idx = k2.set(idx, (int)num_inner_iter); idx = k2.set(idx, (int)pyr_level); idx = k2.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx)); idx = k2.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy)); if (!k2.run(2, globalSize, localSize, false)) return false; } else { ocl::Kernel k3("dis_patch_inverse_search_bwd_1", ocl::video::dis_flow_oclsrc, subgroups_build_options); size_t global_sz[] = {(size_t)hs * 8}; size_t local_sz[] = {8}; idx = 0; idx = k3.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k3.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k3.set(idx, (int)border_size); idx = k3.set(idx, (int)patch_size); idx = k3.set(idx, (int)patch_stride); idx = k3.set(idx, (int)w); idx = k3.set(idx, (int)h); idx = k3.set(idx, (int)ws); idx = k3.set(idx, (int)hs); idx = k3.set(idx, (int)pyr_level); idx = k3.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx)); idx = k3.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy)); if (!k3.run(1, global_sz, local_sz, false)) return false; ocl::Kernel k4("dis_patch_inverse_search_bwd_2", ocl::video::dis_flow_oclsrc); idx = 0; idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0x)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0y)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xx_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0yy_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xy_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0x_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0y_buf)); idx = k4.set(idx, (int)border_size); idx = k4.set(idx, (int)patch_size); idx = k4.set(idx, (int)patch_stride); idx = k4.set(idx, (int)w); idx = k4.set(idx, (int)h); idx = k4.set(idx, (int)ws); idx = k4.set(idx, (int)hs); idx = k4.set(idx, (int)num_inner_iter); idx = k4.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx)); idx = k4.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy)); if (!k4.run(2, globalSize, localSize, false)) return false; } } return true; } bool DISOpticalFlowImpl::ocl_Densification(UMat &dst_Ux, UMat &dst_Uy, UMat &src_Sx, UMat &src_Sy, UMat &_I0, UMat &_I1) { size_t globalSize[] = {(size_t)w, (size_t)h}; size_t localSize[] = {16, 16}; ocl::Kernel kernel("dis_densification", ocl::video::dis_flow_oclsrc); kernel.args(ocl::KernelArg::PtrReadOnly(src_Sx), ocl::KernelArg::PtrReadOnly(src_Sy), ocl::KernelArg::PtrReadOnly(_I0), ocl::KernelArg::PtrReadOnly(_I1), (int)patch_size, (int)patch_stride, (int)w, (int)h, (int)ws, ocl::KernelArg::PtrWriteOnly(dst_Ux), ocl::KernelArg::PtrWriteOnly(dst_Uy)); return kernel.run(2, globalSize, localSize, false); } void DISOpticalFlowImpl::ocl_prepareBuffers(UMat &I0, UMat &I1, UMat &flow, bool use_flow) { u_I0s.resize(coarsest_scale + 1); u_I1s.resize(coarsest_scale + 1); u_I1s_ext.resize(coarsest_scale + 1); u_I0xs.resize(coarsest_scale + 1); u_I0ys.resize(coarsest_scale + 1); u_Ux.resize(coarsest_scale + 1); u_Uy.resize(coarsest_scale + 1); vector<UMat> flow_uv(2); if (use_flow) { split(flow, flow_uv); u_initial_Ux.resize(coarsest_scale + 1); u_initial_Uy.resize(coarsest_scale + 1); } int fraction = 1; int cur_rows = 0, cur_cols = 0; for (int i = 0; i <= coarsest_scale; i++) { /* Avoid initializing the pyramid levels above the finest scale, as they won't be used anyway */ if (i == finest_scale) { cur_rows = I0.rows / fraction; cur_cols = I0.cols / fraction; u_I0s[i].create(cur_rows, cur_cols, CV_8UC1); resize(I0, u_I0s[i], u_I0s[i].size(), 0.0, 0.0, INTER_AREA); u_I1s[i].create(cur_rows, cur_cols, CV_8UC1); resize(I1, u_I1s[i], u_I1s[i].size(), 0.0, 0.0, INTER_AREA); /* These buffers are reused in each scale so we initialize them once on the finest scale: */ u_Sx.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_Sy.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0xx_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0yy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0xy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0x_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0y_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0xx_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0yy_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0xy_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0x_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0y_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_U.create(cur_rows, cur_cols, CV_32FC2); } else if (i > finest_scale) { cur_rows = u_I0s[i - 1].rows / 2; cur_cols = u_I0s[i - 1].cols / 2; u_I0s[i].create(cur_rows, cur_cols, CV_8UC1); resize(u_I0s[i - 1], u_I0s[i], u_I0s[i].size(), 0.0, 0.0, INTER_AREA); u_I1s[i].create(cur_rows, cur_cols, CV_8UC1); resize(u_I1s[i - 1], u_I1s[i], u_I1s[i].size(), 0.0, 0.0, INTER_AREA); } if (i >= finest_scale) { u_I1s_ext[i].create(cur_rows + 2 * border_size, cur_cols + 2 * border_size, CV_8UC1); copyMakeBorder(u_I1s[i], u_I1s_ext[i], border_size, border_size, border_size, border_size, BORDER_REPLICATE); u_I0xs[i].create(cur_rows, cur_cols, CV_16SC1); u_I0ys[i].create(cur_rows, cur_cols, CV_16SC1); spatialGradient(u_I0s[i], u_I0xs[i], u_I0ys[i]); u_Ux[i].create(cur_rows, cur_cols, CV_32FC1); u_Uy[i].create(cur_rows, cur_cols, CV_32FC1); variational_refinement_processors[i]->setAlpha(variational_refinement_alpha); variational_refinement_processors[i]->setDelta(variational_refinement_delta); variational_refinement_processors[i]->setGamma(variational_refinement_gamma); variational_refinement_processors[i]->setSorIterations(5); variational_refinement_processors[i]->setFixedPointIterations(variational_refinement_iter); if (use_flow) { resize(flow_uv[0], u_initial_Ux[i], Size(cur_cols, cur_rows)); divide(u_initial_Ux[i], static_cast<float>(fraction), u_initial_Ux[i]); resize(flow_uv[1], u_initial_Uy[i], Size(cur_cols, cur_rows)); divide(u_initial_Uy[i], static_cast<float>(fraction), u_initial_Uy[i]); } } fraction *= 2; } } bool DISOpticalFlowImpl::ocl_precomputeStructureTensor(UMat &dst_I0xx, UMat &dst_I0yy, UMat &dst_I0xy, UMat &dst_I0x, UMat &dst_I0y, UMat &I0x, UMat &I0y) { size_t globalSizeX[] = {(size_t)h}; size_t localSizeX[] = {16}; ocl::Kernel kernelX("dis_precomputeStructureTensor_hor", ocl::video::dis_flow_oclsrc); kernelX.args(ocl::KernelArg::PtrReadOnly(I0x), ocl::KernelArg::PtrReadOnly(I0y), (int)patch_size, (int)patch_stride, (int)w, (int)h, (int)ws, ocl::KernelArg::PtrWriteOnly(u_I0xx_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0yy_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0xy_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0x_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0y_buf_aux)); if (!kernelX.run(1, globalSizeX, localSizeX, false)) return false; size_t globalSizeY[] = {(size_t)ws}; size_t localSizeY[] = {16}; ocl::Kernel kernelY("dis_precomputeStructureTensor_ver", ocl::video::dis_flow_oclsrc); kernelY.args(ocl::KernelArg::PtrReadOnly(u_I0xx_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0yy_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0xy_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0x_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0y_buf_aux), (int)patch_size, (int)patch_stride, (int)w, (int)h, (int)ws, ocl::KernelArg::PtrWriteOnly(dst_I0xx), ocl::KernelArg::PtrWriteOnly(dst_I0yy), ocl::KernelArg::PtrWriteOnly(dst_I0xy), ocl::KernelArg::PtrWriteOnly(dst_I0x), ocl::KernelArg::PtrWriteOnly(dst_I0y)); return kernelY.run(1, globalSizeY, localSizeY, false); } bool DISOpticalFlowImpl::ocl_calc(InputArray I0, InputArray I1, InputOutputArray flow) { UMat I0Mat = I0.getUMat(); UMat I1Mat = I1.getUMat(); bool use_input_flow = false; if (flow.sameSize(I0) && flow.depth() == CV_32F && flow.channels() == 2) use_input_flow = true; else flow.create(I1Mat.size(), CV_32FC2); UMat &u_flowMat = flow.getUMatRef(); coarsest_scale = min((int)(log(max(I0Mat.cols, I0Mat.rows) / (4.0 * patch_size)) / log(2.0) + 0.5), /* Original code serach for maximal movement of width/4 */ (int)(log(min(I0Mat.cols, I0Mat.rows) / patch_size) / log(2.0))); /* Deepest pyramid level greater or equal than patch*/ ocl_prepareBuffers(I0Mat, I1Mat, u_flowMat, use_input_flow); u_Ux[coarsest_scale].setTo(0.0f); u_Uy[coarsest_scale].setTo(0.0f); for (int i = coarsest_scale; i >= finest_scale; i--) { w = u_I0s[i].cols; h = u_I0s[i].rows; ws = 1 + (w - patch_size) / patch_stride; hs = 1 + (h - patch_size) / patch_stride; if (!ocl_precomputeStructureTensor(u_I0xx_buf, u_I0yy_buf, u_I0xy_buf, u_I0x_buf, u_I0y_buf, u_I0xs[i], u_I0ys[i])) return false; if (!ocl_PatchInverseSearch(u_Ux[i], u_Uy[i], u_I0s[i], u_I1s_ext[i], u_I0xs[i], u_I0ys[i], 2, i)) return false; if (!ocl_Densification(u_Ux[i], u_Uy[i], u_Sx, u_Sy, u_I0s[i], u_I1s[i])) return false; if (variational_refinement_iter > 0) variational_refinement_processors[i]->calcUV(u_I0s[i], u_I1s[i], u_Ux[i].getMat(ACCESS_WRITE), u_Uy[i].getMat(ACCESS_WRITE)); if (i > finest_scale) { resize(u_Ux[i], u_Ux[i - 1], u_Ux[i - 1].size()); resize(u_Uy[i], u_Uy[i - 1], u_Uy[i - 1].size()); multiply(u_Ux[i - 1], 2, u_Ux[i - 1]); multiply(u_Uy[i - 1], 2, u_Uy[i - 1]); } } vector<UMat> uxy(2); uxy[0] = u_Ux[finest_scale]; uxy[1] = u_Uy[finest_scale]; merge(uxy, u_U); resize(u_U, u_flowMat, u_flowMat.size()); multiply(u_flowMat, 1 << finest_scale, u_flowMat); return true; } #endif void DISOpticalFlowImpl::calc(InputArray I0, InputArray I1, InputOutputArray flow) { CV_Assert(!I0.empty() && I0.depth() == CV_8U && I0.channels() == 1); CV_Assert(!I1.empty() && I1.depth() == CV_8U && I1.channels() == 1); CV_Assert(I0.sameSize(I1)); CV_Assert(I0.isContinuous()); CV_Assert(I1.isContinuous()); CV_OCL_RUN(flow.isUMat() && (patch_size == 8) && (use_spatial_propagation == true), ocl_calc(I0, I1, flow)); Mat I0Mat = I0.getMat(); Mat I1Mat = I1.getMat(); bool use_input_flow = false; if (flow.sameSize(I0) && flow.depth() == CV_32F && flow.channels() == 2) use_input_flow = true; else flow.create(I1Mat.size(), CV_32FC2); Mat flowMat = flow.getMat(); coarsest_scale = min((int)(log(max(I0Mat.cols, I0Mat.rows) / (4.0 * patch_size)) / log(2.0) + 0.5), /* Original code serach for maximal movement of width/4 */ (int)(log(min(I0Mat.cols, I0Mat.rows) / patch_size) / log(2.0))); /* Deepest pyramid level greater or equal than patch*/ int num_stripes = getNumThreads(); prepareBuffers(I0Mat, I1Mat, flowMat, use_input_flow); Ux[coarsest_scale].setTo(0.0f); Uy[coarsest_scale].setTo(0.0f); for (int i = coarsest_scale; i >= finest_scale; i--) { w = I0s[i].cols; h = I0s[i].rows; ws = 1 + (w - patch_size) / patch_stride; hs = 1 + (h - patch_size) / patch_stride; precomputeStructureTensor(I0xx_buf, I0yy_buf, I0xy_buf, I0x_buf, I0y_buf, I0xs[i], I0ys[i]); if (use_spatial_propagation) { /* Use a fixed number of stripes regardless the number of threads to make inverse search * with spatial propagation reproducible */ parallel_for_(Range(0, 8), PatchInverseSearch_ParBody(*this, 8, hs, Sx, Sy, Ux[i], Uy[i], I0s[i], I1s_ext[i], I0xs[i], I0ys[i], 2, i)); } else { parallel_for_(Range(0, num_stripes), PatchInverseSearch_ParBody(*this, num_stripes, hs, Sx, Sy, Ux[i], Uy[i], I0s[i], I1s_ext[i], I0xs[i], I0ys[i], 1, i)); } parallel_for_(Range(0, num_stripes), Densification_ParBody(*this, num_stripes, I0s[i].rows, Ux[i], Uy[i], Sx, Sy, I0s[i], I1s[i])); if (variational_refinement_iter > 0) variational_refinement_processors[i]->calcUV(I0s[i], I1s[i], Ux[i], Uy[i]); if (i > finest_scale) { resize(Ux[i], Ux[i - 1], Ux[i - 1].size()); resize(Uy[i], Uy[i - 1], Uy[i - 1].size()); Ux[i - 1] *= 2; Uy[i - 1] *= 2; } } Mat uxy[] = {Ux[finest_scale], Uy[finest_scale]}; merge(uxy, 2, U); resize(U, flowMat, flowMat.size()); flowMat *= 1 << finest_scale; } void DISOpticalFlowImpl::collectGarbage() { I0s.clear(); I1s.clear(); I1s_ext.clear(); I0xs.clear(); I0ys.clear(); Ux.clear(); Uy.clear(); U.release(); Sx.release(); Sy.release(); I0xx_buf.release(); I0yy_buf.release(); I0xy_buf.release(); I0xx_buf_aux.release(); I0yy_buf_aux.release(); I0xy_buf_aux.release(); #ifdef HAVE_OPENCL u_I0s.clear(); u_I1s.clear(); u_I1s_ext.clear(); u_I0xs.clear(); u_I0ys.clear(); u_Ux.clear(); u_Uy.clear(); u_U.release(); u_Sx.release(); u_Sy.release(); u_I0xx_buf.release(); u_I0yy_buf.release(); u_I0xy_buf.release(); u_I0xx_buf_aux.release(); u_I0yy_buf_aux.release(); u_I0xy_buf_aux.release(); #endif for (int i = finest_scale; i <= coarsest_scale; i++) variational_refinement_processors[i]->collectGarbage(); variational_refinement_processors.clear(); } Ptr<DISOpticalFlow> DISOpticalFlow::create(int preset) { Ptr<DISOpticalFlow> dis = makePtr<DISOpticalFlowImpl>(); dis->setPatchSize(8); if (preset == DISOpticalFlow::PRESET_ULTRAFAST) { dis->setFinestScale(2); dis->setPatchStride(4); dis->setGradientDescentIterations(12); dis->setVariationalRefinementIterations(0); } else if (preset == DISOpticalFlow::PRESET_FAST) { dis->setFinestScale(2); dis->setPatchStride(4); dis->setGradientDescentIterations(16); dis->setVariationalRefinementIterations(5); } else if (preset == DISOpticalFlow::PRESET_MEDIUM) { dis->setFinestScale(1); dis->setPatchStride(3); dis->setGradientDescentIterations(25); dis->setVariationalRefinementIterations(5); } return dis; } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_1309_0
crossvul-cpp_data_bad_1383_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1998-2010 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@zend.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-printf.h" #include "hphp/runtime/base/zend-math.h" #include "hphp/util/lock.h" #include "hphp/util/overflow.h" #include <cmath> #ifndef _MSC_VER #include <monetary.h> #endif #include "hphp/util/bstring.h" #include "hphp/runtime/base/exceptions.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/builtin-functions.h" #include <folly/portability/String.h> #define PHP_QPRINT_MAXL 75 namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // helpers void string_charmask(const char *sinput, int len, char *mask) { const unsigned char *input = (unsigned char *)sinput; const unsigned char *end; unsigned char c; memset(mask, 0, 256); for (end = input+len; input < end; input++) { c=*input; if ((input+3 < end) && input[1] == '.' && input[2] == '.' && input[3] >= c) { memset(mask+c, 1, input[3] - c + 1); input+=3; } else if ((input+1 < end) && input[0] == '.' && input[1] == '.') { /* Error, try to be as helpful as possible: (a range ending/starting with '.' won't be captured here) */ if (end-len >= input) { /* there was no 'left' char */ throw_invalid_argument ("charlist: Invalid '..'-range, missing left of '..'"); continue; } if (input+2 >= end) { /* there is no 'right' char */ throw_invalid_argument ("charlist: Invalid '..'-range, missing right of '..'"); continue; } if (input[-1] > input[2]) { /* wrong order */ throw_invalid_argument ("charlist: '..'-range needs to be incrementing"); continue; } /* FIXME: better error (a..b..c is the only left possibility?) */ throw_invalid_argument("charlist: Invalid '..'-range"); continue; } else { mask[c]=1; } } } int string_copy(char *dst, const char *src, int siz) { register char *d = dst; register const char *s = src; register size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0 && --n != 0) { do { if ((*d++ = *s++) == 0) break; } while (--n != 0); } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) *d = '\0'; /* NUL-terminate dst */ while (*s++) ; } return(s - src - 1); /* count does not include NUL */ } /////////////////////////////////////////////////////////////////////////////// // comparisons int string_ncmp(const char *s1, const char *s2, int len) { for (int i = 0; i < len; i++) { char c1 = s1[i]; char c2 = s2[i]; if (c1 > c2) return 1; if (c1 < c2) return -1; } return 0; } static int compare_right(char const **a, char const *aend, char const **b, char const *bend) { int bias = 0; /* The longest run of digits wins. That aside, the greatest value wins, but we can't know that it will until we've scanned both numbers to know that they have the same magnitude, so we remember it in BIAS. */ for(;; (*a)++, (*b)++) { if ((*a == aend || !isdigit((int)(unsigned char)**a)) && (*b == bend || !isdigit((int)(unsigned char)**b))) return bias; else if (*a == aend || !isdigit((int)(unsigned char)**a)) return -1; else if (*b == bend || !isdigit((int)(unsigned char)**b)) return +1; else if (**a < **b) { if (!bias) bias = -1; } else if (**a > **b) { if (!bias) bias = +1; } } return 0; } static int compare_left(char const **a, char const *aend, char const **b, char const *bend) { /* Compare two left-aligned numbers: the first to have a different value wins. */ for(;; (*a)++, (*b)++) { if ((*a == aend || !isdigit((int)(unsigned char)**a)) && (*b == bend || !isdigit((int)(unsigned char)**b))) return 0; else if (*a == aend || !isdigit((int)(unsigned char)**a)) return -1; else if (*b == bend || !isdigit((int)(unsigned char)**b)) return +1; else if (**a < **b) return -1; else if (**a > **b) return +1; } return 0; } int string_natural_cmp(char const *a, size_t a_len, char const *b, size_t b_len, int fold_case) { char ca, cb; char const *ap, *bp; char const *aend = a + a_len, *bend = b + b_len; int fractional, result; if (a_len == 0 || b_len == 0) return a_len - b_len; ap = a; bp = b; while (1) { ca = *ap; cb = *bp; /* skip over leading spaces or zeros */ while (isspace((int)(unsigned char)ca)) ca = *++ap; while (isspace((int)(unsigned char)cb)) cb = *++bp; /* process run of digits */ if (isdigit((int)(unsigned char)ca) && isdigit((int)(unsigned char)cb)) { fractional = (ca == '0' || cb == '0'); if (fractional) result = compare_left(&ap, aend, &bp, bend); else result = compare_right(&ap, aend, &bp, bend); if (result != 0) return result; else if (ap == aend && bp == bend) /* End of the strings. Let caller sort them out. */ return 0; else { /* Keep on comparing from the current point. */ ca = *ap; cb = *bp; } } if (fold_case) { ca = toupper((int)(unsigned char)ca); cb = toupper((int)(unsigned char)cb); } if (ca < cb) return -1; else if (ca > cb) return +1; ++ap; ++bp; if (ap >= aend && bp >= bend) /* The strings compare the same. Perhaps the caller will want to call strcmp to break the tie. */ return 0; else if (ap >= aend) return -1; else if (bp >= bend) return 1; } } /////////////////////////////////////////////////////////////////////////////// void string_to_case(String& s, int (*tocase)(int)) { assertx(!s.isNull()); assertx(tocase); auto data = s.mutableData(); auto len = s.size(); for (int i = 0; i < len; i++) { data[i] = tocase(data[i]); } } /////////////////////////////////////////////////////////////////////////////// #define STR_PAD_LEFT 0 #define STR_PAD_RIGHT 1 #define STR_PAD_BOTH 2 String string_pad(const char *input, int len, int pad_length, const char *pad_string, int pad_str_len, int pad_type) { assertx(input); int num_pad_chars = pad_length - len; /* If resulting string turns out to be shorter than input string, we simply copy the input and return. */ if (pad_length < 0 || num_pad_chars < 0) { return String(input, len, CopyString); } /* Setup the padding string values if specified. */ if (pad_str_len == 0) { throw_invalid_argument("pad_string: (empty)"); return String(); } String ret(pad_length, ReserveString); char *result = ret.mutableData(); /* We need to figure out the left/right padding lengths. */ int left_pad, right_pad; switch (pad_type) { case STR_PAD_RIGHT: left_pad = 0; right_pad = num_pad_chars; break; case STR_PAD_LEFT: left_pad = num_pad_chars; right_pad = 0; break; case STR_PAD_BOTH: left_pad = num_pad_chars / 2; right_pad = num_pad_chars - left_pad; break; default: throw_invalid_argument("pad_type: %d", pad_type); return String(); } /* First we pad on the left. */ int result_len = 0; for (int i = 0; i < left_pad; i++) { result[result_len++] = pad_string[i % pad_str_len]; } /* Then we copy the input string. */ memcpy(result + result_len, input, len); result_len += len; /* Finally, we pad on the right. */ for (int i = 0; i < right_pad; i++) { result[result_len++] = pad_string[i % pad_str_len]; } ret.setSize(result_len); return ret; } /////////////////////////////////////////////////////////////////////////////// int string_find(const char *input, int len, char ch, int pos, bool case_sensitive) { assertx(input); if (pos < 0 || pos > len) { return -1; } const void *ptr; if (case_sensitive) { ptr = memchr(input + pos, ch, len - pos); } else { ptr = bstrcasechr(input + pos, ch, len - pos); } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } int string_rfind(const char *input, int len, char ch, int pos, bool case_sensitive) { assertx(input); if (pos < -len || pos > len) { return -1; } const void *ptr; if (case_sensitive) { if (pos >= 0) { ptr = memrchr(input + pos, ch, len - pos); } else { ptr = memrchr(input, ch, len + pos + 1); } } else { if (pos >= 0) { ptr = bstrrcasechr(input + pos, ch, len - pos); } else { ptr = bstrrcasechr(input, ch, len + pos + 1); } } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } int string_find(const char *input, int len, const char *s, int s_len, int pos, bool case_sensitive) { assertx(input); assertx(s); if (!s_len || pos < 0 || pos > len) { return -1; } void *ptr; if (case_sensitive) { ptr = (void*)string_memnstr(input + pos, s, s_len, input + len); } else { ptr = bstrcasestr(input + pos, len - pos, s, s_len); } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } int string_rfind(const char *input, int len, const char *s, int s_len, int pos, bool case_sensitive) { assertx(input); assertx(s); if (!s_len || pos < -len || pos > len) { return -1; } void *ptr; if (case_sensitive) { if (pos >= 0) { ptr = bstrrstr(input + pos, len - pos, s, s_len); } else { ptr = bstrrstr(input, len + pos + s_len, s, s_len); } } else { if (pos >= 0) { ptr = bstrrcasestr(input + pos, len - pos, s, s_len); } else { ptr = bstrrcasestr(input, len + pos + s_len, s, s_len); } } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } const char *string_memnstr(const char *haystack, const char *needle, int needle_len, const char *end) { const char *p = haystack; char ne = needle[needle_len-1]; end -= needle_len; while (p <= end) { if ((p = (char *)memchr(p, *needle, (end-p+1))) && ne == p[needle_len-1]) { if (!memcmp(needle, p, needle_len-1)) { return p; } } if (p == nullptr) { return nullptr; } p++; } return nullptr; } String string_replace(const char *s, int len, int start, int length, const char *replacement, int len_repl) { assertx(s); assertx(replacement); assertx(len >= 0); // if "start" position is negative, count start position from the end // of the string if (start < 0) { start = len + start; if (start < 0) { start = 0; } } if (start > len) { start = len; } // if "length" position is negative, set it to the length // needed to stop that many chars from the end of the string if (length < 0) { length = (len - start) + length; if (length < 0) { length = 0; } } // check if length is too large if (length > len) { length = len; } // check if the length is too large adjusting for non-zero start // Write this way instead of start + length > len to avoid overflow if (length > len - start) { length = len - start; } String retString(len + len_repl - length, ReserveString); char *ret = retString.mutableData(); int ret_len = 0; if (start) { memcpy(ret, s, start); ret_len += start; } if (len_repl) { memcpy(ret + ret_len, replacement, len_repl); ret_len += len_repl; } len -= (start + length); if (len) { memcpy(ret + ret_len, s + start + length, len); ret_len += len; } retString.setSize(ret_len); return retString; } String string_replace(const char *input, int len, const char *search, int len_search, const char *replacement, int len_replace, int &count, bool case_sensitive) { assertx(input); assertx(search && len_search); assertx(len >= 0); assertx(len_search >= 0); assertx(len_replace >= 0); if (len == 0) { return String(); } req::vector<int> founds; founds.reserve(16); if (len_search == 1) { for (int pos = string_find(input, len, *search, 0, case_sensitive); pos >= 0; pos = string_find(input, len, *search, pos + len_search, case_sensitive)) { founds.push_back(pos); } } else { for (int pos = string_find(input, len, search, len_search, 0, case_sensitive); pos >= 0; pos = string_find(input, len, search, len_search, pos + len_search, case_sensitive)) { founds.push_back(pos); } } count = founds.size(); if (count == 0) { return String(); // not found } int reserve; // Make sure the new size of the string wouldn't overflow int32_t. Don't // bother if the replacement wouldn't make the string longer. if (len_replace > len_search) { auto raise = [&] { raise_error("String too large"); }; if (mul_overflow(len_replace - len_search, count)) { raise(); } int diff = (len_replace - len_search) * count; if (add_overflow(len, diff)) { raise(); } reserve = len + diff; } else { reserve = len + (len_replace - len_search) * count; } String retString(reserve, ReserveString); char *ret = retString.mutableData(); char *p = ret; int pos = 0; // last position in input that hasn't been copied over yet int n; for (unsigned int i = 0; i < founds.size(); i++) { n = founds[i]; if (n > pos) { n -= pos; memcpy(p, input, n); p += n; input += n; pos += n; } if (len_replace) { memcpy(p, replacement, len_replace); p += len_replace; } input += len_search; pos += len_search; } n = len; if (n > pos) { n -= pos; memcpy(p, input, n); p += n; } retString.setSize(p - ret); return retString; } /////////////////////////////////////////////////////////////////////////////// String string_chunk_split(const char *src, int srclen, const char *end, int endlen, int chunklen) { int chunks = srclen / chunklen; // complete chunks! int restlen = srclen - chunks * chunklen; /* srclen % chunklen */ String ret( safe_address( chunks + 1, endlen, srclen ), ReserveString ); char *dest = ret.mutableData(); const char *p; char *q; const char *pMax = src + srclen - chunklen + 1; for (p = src, q = dest; p < pMax; ) { memcpy(q, p, chunklen); q += chunklen; memcpy(q, end, endlen); q += endlen; p += chunklen; } if (restlen) { memcpy(q, p, restlen); q += restlen; memcpy(q, end, endlen); q += endlen; } ret.setSize(q - dest); return ret; } /////////////////////////////////////////////////////////////////////////////// #define PHP_TAG_BUF_SIZE 1023 /** * Check if tag is in a set of tags * * states: * * 0 start tag * 1 first non-whitespace char seen */ static int string_tag_find(const char *tag, int len, const char *set) { char c, *n; const char *t; int state=0, done=0; char *norm; if (len <= 0) { return 0; } norm = (char *)req::malloc_noptrs(len+1); SCOPE_EXIT { req::free(norm); }; n = norm; t = tag; c = tolower(*t); /* normalize the tag removing leading and trailing whitespace and turn any <a whatever...> into just <a> and any </tag> into <tag> */ while (!done) { switch (c) { case '<': *(n++) = c; break; case '>': done =1; break; default: if (!isspace((int)c)) { if (state == 0) { state=1; } if (c != '/') { *(n++) = c; } } else { if (state == 1) done=1; } break; } c = tolower(*(++t)); } *(n++) = '>'; *n = '\0'; if (strstr(set, norm)) { done=1; } else { done=0; } return done; } /** * A simple little state-machine to strip out html and php tags * * State 0 is the output state, State 1 means we are inside a * normal html tag and state 2 means we are inside a php tag. * * The state variable is passed in to allow a function like fgetss * to maintain state across calls to the function. * * lc holds the last significant character read and br is a bracket * counter. * * When an allow string is passed in we keep track of the string * in state 1 and when the tag is closed check it against the * allow string to see if we should allow it. * swm: Added ability to strip <?xml tags without assuming it PHP * code. */ String string_strip_tags(const char *s, const int len, const char *allow, const int allow_len, bool allow_tag_spaces) { const char *abuf, *p; char *rbuf, *tbuf, *tp, *rp, c, lc; int br, i=0, depth=0, in_q = 0; int state = 0, pos; assertx(s); assertx(allow); String retString(s, len, CopyString); rbuf = retString.mutableData(); String allowString; c = *s; lc = '\0'; p = s; rp = rbuf; br = 0; if (allow_len) { assertx(allow); allowString = String(allow_len, ReserveString); char *atmp = allowString.mutableData(); for (const char *tmp = allow; *tmp; tmp++, atmp++) { *atmp = tolower((int)*(const unsigned char *)tmp); } allowString.setSize(allow_len); abuf = allowString.data(); tbuf = (char *)req::malloc_noptrs(PHP_TAG_BUF_SIZE+1); tp = tbuf; } else { abuf = nullptr; tbuf = tp = nullptr; } auto move = [&pos, &tbuf, &tp]() { if (tp - tbuf >= PHP_TAG_BUF_SIZE) { pos = tp - tbuf; tbuf = (char*)req::realloc_noptrs(tbuf, (tp - tbuf) + PHP_TAG_BUF_SIZE + 1); tp = tbuf + pos; } }; while (i < len) { switch (c) { case '\0': break; case '<': if (isspace(*(p + 1)) && !allow_tag_spaces) { goto reg_char; } if (state == 0) { lc = '<'; state = 1; if (allow_len) { move(); *(tp++) = '<'; } } else if (state == 1) { depth++; } break; case '(': if (state == 2) { if (lc != '"' && lc != '\'') { lc = '('; br++; } } else if (allow_len && state == 1) { move(); *(tp++) = c; } else if (state == 0) { *(rp++) = c; } break; case ')': if (state == 2) { if (lc != '"' && lc != '\'') { lc = ')'; br--; } } else if (allow_len && state == 1) { move(); *(tp++) = c; } else if (state == 0) { *(rp++) = c; } break; case '>': if (depth) { depth--; break; } if (in_q) { break; } switch (state) { case 1: /* HTML/XML */ lc = '>'; in_q = state = 0; if (allow_len) { move(); *(tp++) = '>'; *tp='\0'; if (string_tag_find(tbuf, tp-tbuf, abuf)) { memcpy(rp, tbuf, tp-tbuf); rp += tp-tbuf; } tp = tbuf; } break; case 2: /* PHP */ if (!br && lc != '\"' && *(p-1) == '?') { in_q = state = 0; tp = tbuf; } break; case 3: in_q = state = 0; tp = tbuf; break; case 4: /* JavaScript/CSS/etc... */ if (p >= s + 2 && *(p-1) == '-' && *(p-2) == '-') { in_q = state = 0; tp = tbuf; } break; default: *(rp++) = c; break; } break; case '"': case '\'': if (state == 4) { /* Inside <!-- comment --> */ break; } else if (state == 2 && *(p-1) != '\\') { if (lc == c) { lc = '\0'; } else if (lc != '\\') { lc = c; } } else if (state == 0) { *(rp++) = c; } else if (allow_len && state == 1) { move(); *(tp++) = c; } if (state && p != s && *(p-1) != '\\' && (!in_q || *p == in_q)) { if (in_q) { in_q = 0; } else { in_q = *p; } } break; case '!': /* JavaScript & Other HTML scripting languages */ if (state == 1 && *(p-1) == '<') { state = 3; lc = c; } else { if (state == 0) { *(rp++) = c; } else if (allow_len && state == 1) { move(); *(tp++) = c; } } break; case '-': if (state == 3 && p >= s + 2 && *(p-1) == '-' && *(p-2) == '!') { state = 4; } else { goto reg_char; } break; case '?': if (state == 1 && *(p-1) == '<') { br=0; state=2; break; } case 'E': case 'e': /* !DOCTYPE exception */ if (state==3 && p > s+6 && tolower(*(p-1)) == 'p' && tolower(*(p-2)) == 'y' && tolower(*(p-3)) == 't' && tolower(*(p-4)) == 'c' && tolower(*(p-5)) == 'o' && tolower(*(p-6)) == 'd') { state = 1; break; } /* fall-through */ case 'l': /* swm: If we encounter '<?xml' then we shouldn't be in * state == 2 (PHP). Switch back to HTML. */ if (state == 2 && p > s+2 && *(p-1) == 'm' && *(p-2) == 'x') { state = 1; break; } /* fall-through */ default: reg_char: if (state == 0) { *(rp++) = c; } else if (allow_len && state == 1) { move(); *(tp++) = c; } break; } c = *(++p); i++; } if (rp < rbuf + len) { *rp = '\0'; } if (allow_len) { req::free(tbuf); } retString.setSize(rp - rbuf); return retString; } /////////////////////////////////////////////////////////////////////////////// static char string_hex2int(int c) { if (isdigit(c)) { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } return -1; } String string_quoted_printable_encode(const char *input, int len) { size_t length = len; const unsigned char *str = (unsigned char*)input; unsigned long lp = 0; unsigned char c; char *d, *buffer; char *hex = "0123456789ABCDEF"; String ret( safe_address( 3, length + ((safe_address(3, length, 0)/(PHP_QPRINT_MAXL-9)) + 1), 1), ReserveString ); d = buffer = ret.mutableData(); while (length--) { if (((c = *str++) == '\015') && (*str == '\012') && length > 0) { *d++ = '\015'; *d++ = *str++; length--; lp = 0; } else { if (iscntrl (c) || (c == 0x7f) || (c & 0x80) || (c == '=') || ((c == ' ') && (*str == '\015'))) { if ((((lp+= 3) > PHP_QPRINT_MAXL) && (c <= 0x7f)) || ((c > 0x7f) && (c <= 0xdf) && ((lp + 3) > PHP_QPRINT_MAXL)) || ((c > 0xdf) && (c <= 0xef) && ((lp + 6) > PHP_QPRINT_MAXL)) || ((c > 0xef) && (c <= 0xf4) && ((lp + 9) > PHP_QPRINT_MAXL))) { *d++ = '='; *d++ = '\015'; *d++ = '\012'; lp = 3; } *d++ = '='; *d++ = hex[c >> 4]; *d++ = hex[c & 0xf]; } else { if ((++lp) > PHP_QPRINT_MAXL) { *d++ = '='; *d++ = '\015'; *d++ = '\012'; lp = 1; } *d++ = c; } } } len = d - buffer; ret.setSize(len); return ret; } String string_quoted_printable_decode(const char *input, int len, bool is_q) { assertx(input); if (len == 0) { return String(); } int i = 0, j = 0, k; const char *str_in = input; String ret(len, ReserveString); char *str_out = ret.mutableData(); while (i < len && str_in[i]) { switch (str_in[i]) { case '=': if (i + 2 < len && str_in[i + 1] && str_in[i + 2] && isxdigit((int) str_in[i + 1]) && isxdigit((int) str_in[i + 2])) { str_out[j++] = (string_hex2int((int) str_in[i + 1]) << 4) + string_hex2int((int) str_in[i + 2]); i += 3; } else /* check for soft line break according to RFC 2045*/ { k = 1; while (str_in[i + k] && ((str_in[i + k] == 32) || (str_in[i + k] == 9))) { /* Possibly, skip spaces/tabs at the end of line */ k++; } if (!str_in[i + k]) { /* End of line reached */ i += k; } else if ((str_in[i + k] == 13) && (str_in[i + k + 1] == 10)) { /* CRLF */ i += k + 2; } else if ((str_in[i + k] == 13) || (str_in[i + k] == 10)) { /* CR or LF */ i += k + 1; } else { str_out[j++] = str_in[i++]; } } break; case '_': if (is_q) { str_out[j++] = ' '; i++; } else { str_out[j++] = str_in[i++]; } break; default: str_out[j++] = str_in[i++]; } } ret.setSize(j); return ret; } Variant string_base_to_numeric(const char *s, int len, int base) { int64_t num = 0; double fnum = 0; int mode = 0; int64_t cutoff; int cutlim; assertx(string_validate_base(base)); cutoff = LONG_MAX / base; cutlim = LONG_MAX % base; for (int i = len; i > 0; i--) { char c = *s++; /* might not work for EBCDIC */ if (c >= '0' && c <= '9') c -= '0'; else if (c >= 'A' && c <= 'Z') c -= 'A' - 10; else if (c >= 'a' && c <= 'z') c -= 'a' - 10; else continue; if (c >= base) continue; switch (mode) { case 0: /* Integer */ if (num < cutoff || (num == cutoff && c <= cutlim)) { num = num * base + c; break; } else { fnum = num; mode = 1; } /* fall-through */ case 1: /* Float */ fnum = fnum * base + c; } } if (mode == 1) { return fnum; } return num; } String string_long_to_base(unsigned long value, int base) { static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[(sizeof(unsigned long) << 3) + 1]; char *ptr, *end; assertx(string_validate_base(base)); end = ptr = buf + sizeof(buf) - 1; do { *--ptr = digits[value % base]; value /= base; } while (ptr > buf && value); return String(ptr, end - ptr, CopyString); } String string_numeric_to_base(const Variant& value, int base) { static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; assertx(string_validate_base(base)); if ((!value.isInteger() && !value.isDouble())) { return empty_string(); } if (value.isDouble()) { double fvalue = floor(value.toDouble()); /* floor it just in case */ char *ptr, *end; char buf[(sizeof(double) << 3) + 1]; /* Don't try to convert +/- infinity */ if (fvalue == HUGE_VAL || fvalue == -HUGE_VAL) { raise_warning("Number too large"); return empty_string(); } end = ptr = buf + sizeof(buf) - 1; do { *--ptr = digits[(int) fmod(fvalue, base)]; fvalue /= base; } while (ptr > buf && fabs(fvalue) >= 1); return String(ptr, end - ptr, CopyString); } return string_long_to_base(value.toInt64(), base); } /////////////////////////////////////////////////////////////////////////////// // uuencode #define PHP_UU_ENC(c) \ ((c) ? ((c) & 077) + ' ' : '`') #define PHP_UU_ENC_C2(c) \ PHP_UU_ENC(((*(c) * 16) & 060) | ((*((c) + 1) >> 4) & 017)) #define PHP_UU_ENC_C3(c) \ PHP_UU_ENC(((*(c + 1) * 4) & 074) | ((*((c) + 2) >> 6) & 03)) #define PHP_UU_DEC(c) \ (((c) - ' ') & 077) String string_uuencode(const char *src, int src_len) { assertx(src); assertx(src_len); int len = 45; char *p; const char *s, *e, *ee; char *dest; /* encoded length is ~ 38% greater than the original */ String ret((int)ceil(src_len * 1.38) + 45, ReserveString); p = dest = ret.mutableData(); s = src; e = src + src_len; while ((s + 3) < e) { ee = s + len; if (ee > e) { ee = e; len = ee - s; if (len % 3) { ee = s + (int) (floor(len / 3) * 3); } } *p++ = PHP_UU_ENC(len); while (s < ee) { *p++ = PHP_UU_ENC(*s >> 2); *p++ = PHP_UU_ENC_C2(s); *p++ = PHP_UU_ENC_C3(s); *p++ = PHP_UU_ENC(*(s + 2) & 077); s += 3; } if (len == 45) { *p++ = '\n'; } } if (s < e) { if (len == 45) { *p++ = PHP_UU_ENC(e - s); len = 0; } *p++ = PHP_UU_ENC(*s >> 2); *p++ = PHP_UU_ENC_C2(s); *p++ = ((e - s) > 1) ? PHP_UU_ENC_C3(s) : PHP_UU_ENC('\0'); *p++ = ((e - s) > 2) ? PHP_UU_ENC(*(s + 2) & 077) : PHP_UU_ENC('\0'); } if (len < 45) { *p++ = '\n'; } *p++ = PHP_UU_ENC('\0'); *p++ = '\n'; *p = '\0'; ret.setSize(p - dest); return ret; } String string_uudecode(const char *src, int src_len) { int total_len = 0; int len; const char *s, *e, *ee; char *p, *dest; String ret(ceil(src_len * 0.75), ReserveString); p = dest = ret.mutableData(); s = src; e = src + src_len; while (s < e) { if ((len = PHP_UU_DEC(*s++)) <= 0) { break; } /* sanity check */ if (len > src_len) { goto err; } total_len += len; ee = s + (len == 45 ? 60 : (int) floor(len * 1.33)); /* sanity check */ if (ee > e) { goto err; } while (s < ee) { if (s + 4 > e) goto err; *p++ = PHP_UU_DEC(*s) << 2 | PHP_UU_DEC(*(s + 1)) >> 4; *p++ = PHP_UU_DEC(*(s + 1)) << 4 | PHP_UU_DEC(*(s + 2)) >> 2; *p++ = PHP_UU_DEC(*(s + 2)) << 6 | PHP_UU_DEC(*(s + 3)); s += 4; } if (len < 45) { break; } /* skip \n */ s++; } if ((len = total_len > (p - dest))) { *p++ = PHP_UU_DEC(*s) << 2 | PHP_UU_DEC(*(s + 1)) >> 4; if (len > 1) { *p++ = PHP_UU_DEC(*(s + 1)) << 4 | PHP_UU_DEC(*(s + 2)) >> 2; if (len > 2) { *p++ = PHP_UU_DEC(*(s + 2)) << 6 | PHP_UU_DEC(*(s + 3)); } } } ret.setSize(total_len); return ret; err: return String(); } /////////////////////////////////////////////////////////////////////////////// // base64 namespace { const char base64_table[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '\0' }; const char base64_pad = '='; const short base64_reverse_table[256] = { -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2, -2, 0, 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, -2, -2, -2, -2, -2, -2, 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, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 }; folly::Optional<int> maxEncodedSize(int length) { if ((length + 2) < 0 || ((length + 2) / 3) >= (1 << (sizeof(int) * 8 - 2))) { return folly::none; } return ((length + 2) / 3) * 4; } // outstr must be at least maxEncodedSize(length) bytes size_t php_base64_encode(const unsigned char *str, int length, unsigned char* outstr) { const unsigned char *current = str; unsigned char *p = outstr; while (length > 2) { /* keep going until we have less than 24 bits */ *p++ = base64_table[current[0] >> 2]; *p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)]; *p++ = base64_table[((current[1] & 0x0f) << 2) + (current[2] >> 6)]; *p++ = base64_table[current[2] & 0x3f]; current += 3; length -= 3; /* we just handle 3 octets of data */ } /* now deal with the tail end of things */ if (length != 0) { *p++ = base64_table[current[0] >> 2]; if (length > 1) { *p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)]; *p++ = base64_table[(current[1] & 0x0f) << 2]; *p++ = base64_pad; } else { *p++ = base64_table[(current[0] & 0x03) << 4]; *p++ = base64_pad; *p++ = base64_pad; } } return p - outstr; } // outstr must be at least length bytes ssize_t php_base64_decode(const char *str, int length, bool strict, unsigned char* outstr) { const unsigned char *current = (unsigned char*)str; int ch, i = 0, j = 0, k; /* this sucks for threaded environments */ unsigned char* result = outstr; /* run through the whole string, converting as we go */ while ((ch = *current++) != '\0' && length-- > 0) { if (ch == base64_pad) { if (*current != '=' && ((i % 4) == 1 || (strict && length > 0))) { if ((i % 4) != 1) { while (isspace(*(++current))) { continue; } if (*current == '\0') { continue; } } return -1; } continue; } ch = base64_reverse_table[ch]; if ((!strict && ch < 0) || ch == -1) { /* a space or some other separator character, we simply skip over */ continue; } else if (ch == -2) { return -1; } switch(i % 4) { case 0: result[j] = ch << 2; break; case 1: result[j++] |= ch >> 4; result[j] = (ch & 0x0f) << 4; break; case 2: result[j++] |= ch >>2; result[j] = (ch & 0x03) << 6; break; case 3: result[j++] |= ch; break; } i++; } k = j; /* mop things up if we ended on a boundary */ if (ch == base64_pad) { switch(i % 4) { case 1: return -1; case 2: k++; case 3: result[k] = 0; } } return j; } } String string_base64_encode(const char* input, int len) { if (auto const wantedSize = maxEncodedSize(len)) { String ret(*wantedSize, ReserveString); auto actualSize = php_base64_encode((unsigned char*)input, len, (unsigned char*)ret.mutableData()); ret.setSize(actualSize); return ret; } return String(); } String string_base64_decode(const char* input, int len, bool strict) { String ret(len, ReserveString); auto actualSize = php_base64_decode(input, len, strict, (unsigned char*)ret.mutableData()); if (actualSize < 0) return String(); ret.setSize(actualSize); return ret; } std::string base64_encode(const char* input, int len) { if (auto const wantedSize = maxEncodedSize(len)) { std::string ret; ret.resize(*wantedSize); auto actualSize = php_base64_encode((unsigned char*)input, len, (unsigned char*)ret.data()); ret.resize(actualSize); return ret; } return std::string(); } std::string base64_decode(const char* input, int len, bool strict) { if (!len) return std::string(); std::string ret; ret.resize(len); auto actualSize = php_base64_decode(input, len, strict, (unsigned char*)ret.data()); if (!actualSize) return std::string(); ret.resize(actualSize); return ret; } /////////////////////////////////////////////////////////////////////////////// String string_escape_shell_arg(const char *str) { int x, y, l; char *cmd; y = 0; l = strlen(str); String ret(safe_address(l, 4, 3), ReserveString); /* worst case */ cmd = ret.mutableData(); #ifdef _MSC_VER cmd[y++] = '"'; #else cmd[y++] = '\''; #endif for (x = 0; x < l; x++) { switch (str[x]) { #ifdef _MSC_VER case '"': case '%': case '!': cmd[y++] = ' '; break; #else case '\'': cmd[y++] = '\''; cmd[y++] = '\\'; cmd[y++] = '\''; #endif /* fall-through */ default: cmd[y++] = str[x]; } } #ifdef _MSC_VER if (y > 0 && '\\' == cmd[y - 1]) { int k = 0, n = y - 1; for (; n >= 0 && '\\' == cmd[n]; n--, k++); if (k % 2) { cmd[y++] = '\\'; } } cmd[y++] = '"'; #else cmd[y++] = '\''; #endif ret.setSize(y); return ret; } String string_escape_shell_cmd(const char *str) { register int x, y, l; char *cmd; char *p = nullptr; l = strlen(str); String ret(safe_address(l, 2, 1), ReserveString); cmd = ret.mutableData(); for (x = 0, y = 0; x < l; x++) { switch (str[x]) { #ifndef _MSC_VER case '"': case '\'': if (!p && (p = (char *)memchr(str + x + 1, str[x], l - x - 1))) { /* noop */ } else if (p && *p == str[x]) { p = nullptr; } else { cmd[y++] = '\\'; } cmd[y++] = str[x]; break; #else /* % is Windows specific for environmental variables, ^%PATH% will output PATH while ^%PATH^% will not. escapeshellcmd->val will escape all % and !. */ case '%': case '!': case '"': case '\'': #endif case '#': /* This is character-set independent */ case '&': case ';': case '`': case '|': case '*': case '?': case '~': case '<': case '>': case '^': case '(': case ')': case '[': case ']': case '{': case '}': case '$': case '\\': case '\x0A': /* excluding these two */ case '\xFF': #ifdef _MSC_VER cmd[y++] = '^'; #else cmd[y++] = '\\'; #endif /* fall-through */ default: cmd[y++] = str[x]; } } ret.setSize(y); return ret; } /////////////////////////////////////////////////////////////////////////////// static void string_similar_str(const char *txt1, int len1, const char *txt2, int len2, int *pos1, int *pos2, int *max) { const char *p, *q; const char *end1 = txt1 + len1; const char *end2 = txt2 + len2; int l; *max = 0; for (p = txt1; p < end1; p++) { for (q = txt2; q < end2; q++) { for (l = 0; (p + l < end1) && (q + l < end2) && (p[l] == q[l]); l++); if (l > *max) { *max = l; *pos1 = p - txt1; *pos2 = q - txt2; } } } } static int string_similar_char(const char *txt1, int len1, const char *txt2, int len2) { int sum; int pos1 = 0, pos2 = 0, max; string_similar_str(txt1, len1, txt2, len2, &pos1, &pos2, &max); if ((sum = max)) { if (pos1 && pos2) { sum += string_similar_char(txt1, pos1, txt2, pos2); } if ((pos1 + max < len1) && (pos2 + max < len2)) { sum += string_similar_char(txt1 + pos1 + max, len1 - pos1 - max, txt2 + pos2 + max, len2 - pos2 - max); } } return sum; } int string_similar_text(const char *t1, int len1, const char *t2, int len2, float *percent) { if (len1 == 0 && len2 == 0) { if (percent) *percent = 0.0; return 0; } int sim = string_similar_char(t1, len1, t2, len2); if (percent) *percent = sim * 200.0 / (len1 + len2); return sim; } /////////////////////////////////////////////////////////////////////////////// #define LEVENSHTEIN_MAX_LENTH 255 // reference implementation, only optimized for memory usage, not speed int string_levenshtein(const char *s1, int l1, const char *s2, int l2, int cost_ins, int cost_rep, int cost_del ) { int *p1, *p2, *tmp; int i1, i2, c0, c1, c2; if (l1==0) return l2*cost_ins; if (l2==0) return l1*cost_del; if ((l1>LEVENSHTEIN_MAX_LENTH)||(l2>LEVENSHTEIN_MAX_LENTH)) { raise_warning("levenshtein(): Argument string(s) too long"); return -1; } p1 = (int*)req::malloc_noptrs((l2+1) * sizeof(int)); SCOPE_EXIT { req::free(p1); }; p2 = (int*)req::malloc_noptrs((l2+1) * sizeof(int)); SCOPE_EXIT { req::free(p2); }; for(i2=0;i2<=l2;i2++) { p1[i2] = i2*cost_ins; } for(i1=0;i1<l1;i1++) { p2[0]=p1[0]+cost_del; for(i2=0;i2<l2;i2++) { c0=p1[i2]+((s1[i1]==s2[i2])?0:cost_rep); c1=p1[i2+1]+cost_del; if (c1<c0) c0=c1; c2=p2[i2]+cost_ins; if (c2<c0) c0=c2; p2[i2+1]=c0; } tmp=p1; p1=p2; p2=tmp; } c0=p1[l2]; return c0; } /////////////////////////////////////////////////////////////////////////////// String string_money_format(const char *format, double value) { bool check = false; const char *p = format; while ((p = strchr(p, '%'))) { if (*(p + 1) == '%') { p += 2; } else if (!check) { check = true; p++; } else { throw_invalid_argument ("format: Only a single %%i or %%n token can be used"); return String(); } } int format_len = strlen(format); int str_len = safe_address(format_len, 1, 1024); String ret(str_len, ReserveString); char *str = ret.mutableData(); if ((str_len = strfmon(str, str_len, format, value)) < 0) { return String(); } ret.setSize(str_len); return ret; } /////////////////////////////////////////////////////////////////////////////// String string_number_format(double d, int dec, const String& dec_point, const String& thousand_sep) { char *tmpbuf = nullptr, *resbuf; char *s, *t; /* source, target */ char *dp; int integral; int tmplen, reslen=0; int count=0; int is_negative=0; if (d < 0) { is_negative = 1; d = -d; } if (dec < 0) dec = 0; d = php_math_round(d, dec); // departure from PHP: we got rid of dependencies on spprintf() here. String tmpstr(63, ReserveString); tmpbuf = tmpstr.mutableData(); tmplen = snprintf(tmpbuf, 64, "%.*F", dec, d); if (tmplen < 0) return empty_string(); if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) { tmpstr.setSize(tmplen); return tmpstr; } if (tmplen >= 64) { // Uncommon, asked for more than 64 chars worth of precision tmpstr = String(tmplen, ReserveString); tmpbuf = tmpstr.mutableData(); tmplen = snprintf(tmpbuf, tmplen + 1, "%.*F", dec, d); if (tmplen < 0) return empty_string(); if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) { tmpstr.setSize(tmplen); return tmpstr; } } /* find decimal point, if expected */ if (dec) { dp = strpbrk(tmpbuf, ".,"); } else { dp = nullptr; } /* calculate the length of the return buffer */ if (dp) { integral = dp - tmpbuf; } else { /* no decimal point was found */ integral = tmplen; } /* allow for thousand separators */ if (!thousand_sep.empty()) { if (integral + thousand_sep.size() * ((integral-1) / 3) < integral) { /* overflow */ raise_error("String overflow"); } integral += ((integral-1) / 3) * thousand_sep.size(); } reslen = integral; if (dec) { reslen += dec; if (!dec_point.empty()) { if (reslen + dec_point.size() < dec_point.size()) { /* overflow */ raise_error("String overflow"); } reslen += dec_point.size(); } } /* add a byte for minus sign */ if (is_negative) { reslen++; } String resstr(reslen, ReserveString); resbuf = resstr.mutableData(); s = tmpbuf+tmplen-1; t = resbuf+reslen-1; /* copy the decimal places. * Take care, as the sprintf implementation may return less places than * we requested due to internal buffer limitations */ if (dec) { int declen = dp ? s - dp : 0; int topad = dec > declen ? dec - declen : 0; /* pad with '0's */ while (topad--) { *t-- = '0'; } if (dp) { s -= declen + 1; /* +1 to skip the point */ t -= declen; /* now copy the chars after the point */ memcpy(t + 1, dp + 1, declen); } /* add decimal point */ if (!dec_point.empty()) { memcpy(t + (1 - dec_point.size()), dec_point.data(), dec_point.size()); t -= dec_point.size(); } } /* copy the numbers before the decimal point, adding thousand * separator every three digits */ while(s >= tmpbuf) { *t-- = *s--; if (thousand_sep && (++count%3)==0 && s>=tmpbuf) { memcpy(t + (1 - thousand_sep.size()), thousand_sep.data(), thousand_sep.size()); t -= thousand_sep.size(); } } /* and a minus sign, if needed */ if (is_negative) { *t-- = '-'; } resstr.setSize(reslen); return resstr; } /////////////////////////////////////////////////////////////////////////////// // soundex /* Simple soundex algorithm as described by Knuth in TAOCP, vol 3 */ String string_soundex(const String& str) { assertx(!str.empty()); int _small, code, last; String retString(4, ReserveString); char* soundex = retString.mutableData(); static char soundex_table[26] = { 0, /* A */ '1', /* B */ '2', /* C */ '3', /* D */ 0, /* E */ '1', /* F */ '2', /* G */ 0, /* H */ 0, /* I */ '2', /* J */ '2', /* K */ '4', /* L */ '5', /* M */ '5', /* N */ 0, /* O */ '1', /* P */ '2', /* Q */ '6', /* R */ '2', /* S */ '3', /* T */ 0, /* U */ '1', /* V */ 0, /* W */ '2', /* X */ 0, /* Y */ '2' /* Z */ }; /* build soundex string */ last = -1; auto p = str.slice().data(); for (_small = 0; *p && _small < 4; p++) { /* convert chars to upper case and strip non-letter chars */ /* BUG: should also map here accented letters used in non */ /* English words or names (also found in English text!): */ /* esstsett, thorn, n-tilde, c-cedilla, s-caron, ... */ code = toupper((int)(unsigned char)(*p)); if (code >= 'A' && code <= 'Z') { if (_small == 0) { /* remember first valid char */ soundex[_small++] = code; last = soundex_table[code - 'A']; } else { /* ignore sequences of consonants with same soundex */ /* code in trail, and vowels unless they separate */ /* consonant letters */ code = soundex_table[code - 'A']; if (code != last) { if (code != 0) { soundex[_small++] = code; } last = code; } } } } /* pad with '0' and terminate with 0 ;-) */ while (_small < 4) { soundex[_small++] = '0'; } retString.setSize(4); return retString; } /////////////////////////////////////////////////////////////////////////////// // metaphone /** * this is now the original code by Michael G Schwern: * i've changed it just a slightly bit (use emalloc, * get rid of includes etc) * - thies - 13.09.1999 */ /*----------------------------- */ /* this used to be "metaphone.h" */ /*----------------------------- */ /* Special encodings */ #define SH 'X' #define TH '0' /*----------------------------- */ /* end of "metaphone.h" */ /*----------------------------- */ /*----------------------------- */ /* this used to be "metachar.h" */ /*----------------------------- */ /* Metachar.h ... little bits about characters for metaphone */ /*-- Character encoding array & accessing macros --*/ /* Stolen directly out of the book... */ char _codes[26] = { 1,16,4,16,9,2,4,16,9,2,0,2,2,2,1,4,0,2,4,4,1,0,0,0,8,0}; #define ENCODE(c) (isalpha(c) ? _codes[((toupper(c)) - 'A')] : 0) #define isvowel(c) (ENCODE(c) & 1) /* AEIOU */ /* These letters are passed through unchanged */ #define NOCHANGE(c) (ENCODE(c) & 2) /* FJMNR */ /* These form dipthongs when preceding H */ #define AFFECTH(c) (ENCODE(c) & 4) /* CGPST */ /* These make C and G soft */ #define MAKESOFT(c) (ENCODE(c) & 8) /* EIY */ /* These prevent GH from becoming F */ #define NOGHTOF(c) (ENCODE(c) & 16) /* BDH */ /*----------------------------- */ /* end of "metachar.h" */ /*----------------------------- */ /* I suppose I could have been using a character pointer instead of * accesssing the array directly... */ /* Look at the next letter in the word */ #define Next_Letter ((char)toupper(word[w_idx+1])) /* Look at the current letter in the word */ #define Curr_Letter ((char)toupper(word[w_idx])) /* Go N letters back. */ #define Look_Back_Letter(n) (w_idx >= n ? (char)toupper(word[w_idx-n]) : '\0') /* Previous letter. I dunno, should this return null on failure? */ #define Prev_Letter (Look_Back_Letter(1)) /* Look two letters down. It makes sure you don't walk off the string. */ #define After_Next_Letter (Next_Letter != '\0' ? (char)toupper(word[w_idx+2]) \ : '\0') #define Look_Ahead_Letter(n) ((char)toupper(Lookahead(word+w_idx, n))) /* Allows us to safely look ahead an arbitrary # of letters */ /* I probably could have just used strlen... */ static char Lookahead(unsigned char *word, int how_far) { char letter_ahead = '\0'; /* null by default */ int idx; for (idx = 0; word[idx] != '\0' && idx < how_far; idx++); /* Edge forward in the string... */ letter_ahead = (char)word[idx]; /* idx will be either == to how_far or * at the end of the string */ return letter_ahead; } /* phonize one letter * We don't know the buffers size in advance. On way to solve this is to just * re-allocate the buffer size. We're using an extra of 2 characters (this * could be one though; or more too). */ #define Phonize(c) { buffer.append(c); } /* How long is the phoned word? */ #define Phone_Len (buffer.size()) /* Note is a letter is a 'break' in the word */ #define Isbreak(c) (!isalpha(c)) String string_metaphone(const char *input, int word_len, long max_phonemes, int traditional) { unsigned char *word = (unsigned char *)input; int w_idx = 0; /* point in the phonization we're at. */ int max_buffer_len = 0; /* maximum length of the destination buffer */ /*-- Parameter checks --*/ /* Negative phoneme length is meaningless */ if (max_phonemes < 0) return String(); /* Empty/null string is meaningless */ /* Overly paranoid */ /* always_assert(word != NULL && word[0] != '\0'); */ if (word == nullptr) return String(); /*-- Allocate memory for our phoned_phrase --*/ if (max_phonemes == 0) { /* Assume largest possible */ max_buffer_len = word_len; } else { max_buffer_len = max_phonemes; } StringBuffer buffer(max_buffer_len); /*-- The first phoneme has to be processed specially. --*/ /* Find our first letter */ for (; !isalpha(Curr_Letter); w_idx++) { /* On the off chance we were given nothing but crap... */ if (Curr_Letter == '\0') { return buffer.detach(); /* For testing */ } } switch (Curr_Letter) { /* AE becomes E */ case 'A': if (Next_Letter == 'E') { Phonize('E'); w_idx += 2; } /* Remember, preserve vowels at the beginning */ else { Phonize('A'); w_idx++; } break; /* [GKP]N becomes N */ case 'G': case 'K': case 'P': if (Next_Letter == 'N') { Phonize('N'); w_idx += 2; } break; /* WH becomes H, WR becomes R W if followed by a vowel */ case 'W': if (Next_Letter == 'H' || Next_Letter == 'R') { Phonize(Next_Letter); w_idx += 2; } else if (isvowel(Next_Letter)) { Phonize('W'); w_idx += 2; } /* else ignore */ break; /* X becomes S */ case 'X': Phonize('S'); w_idx++; break; /* Vowels are kept */ /* We did A already case 'A': case 'a': */ case 'E': case 'I': case 'O': case 'U': Phonize(Curr_Letter); w_idx++; break; default: /* do nothing */ break; } /* On to the metaphoning */ for (; Curr_Letter != '\0' && (max_phonemes == 0 || Phone_Len < max_phonemes); w_idx++) { /* How many letters to skip because an eariler encoding handled * multiple letters */ unsigned short int skip_letter = 0; /* THOUGHT: It would be nice if, rather than having things like... * well, SCI. For SCI you encode the S, then have to remember * to skip the C. So the phonome SCI invades both S and C. It would * be better, IMHO, to skip the C from the S part of the encoding. * Hell, I'm trying it. */ /* Ignore non-alphas */ if (!isalpha(Curr_Letter)) continue; /* Drop duplicates, except CC */ if (Curr_Letter == Prev_Letter && Curr_Letter != 'C') continue; switch (Curr_Letter) { /* B -> B unless in MB */ case 'B': if (Prev_Letter != 'M') Phonize('B'); break; /* 'sh' if -CIA- or -CH, but not SCH, except SCHW. * (SCHW is handled in S) * S if -CI-, -CE- or -CY- * dropped if -SCI-, SCE-, -SCY- (handed in S) * else K */ case 'C': if (MAKESOFT(Next_Letter)) { /* C[IEY] */ if (After_Next_Letter == 'A' && Next_Letter == 'I') { /* CIA */ Phonize(SH); } /* SC[IEY] */ else if (Prev_Letter == 'S') { /* Dropped */ } else { Phonize('S'); } } else if (Next_Letter == 'H') { if ((!traditional) && (After_Next_Letter == 'R' || Prev_Letter == 'S')) { /* Christ, School */ Phonize('K'); } else { Phonize(SH); } skip_letter++; } else { Phonize('K'); } break; /* J if in -DGE-, -DGI- or -DGY- * else T */ case 'D': if (Next_Letter == 'G' && MAKESOFT(After_Next_Letter)) { Phonize('J'); skip_letter++; } else Phonize('T'); break; /* F if in -GH and not B--GH, D--GH, -H--GH, -H---GH * else dropped if -GNED, -GN, * else dropped if -DGE-, -DGI- or -DGY- (handled in D) * else J if in -GE-, -GI, -GY and not GG * else K */ case 'G': if (Next_Letter == 'H') { if (!(NOGHTOF(Look_Back_Letter(3)) || Look_Back_Letter(4) == 'H')) { Phonize('F'); skip_letter++; } else { /* silent */ } } else if (Next_Letter == 'N') { if (Isbreak(After_Next_Letter) || (After_Next_Letter == 'E' && Look_Ahead_Letter(3) == 'D')) { /* dropped */ } else Phonize('K'); } else if (MAKESOFT(Next_Letter) && Prev_Letter != 'G') { Phonize('J'); } else { Phonize('K'); } break; /* H if before a vowel and not after C,G,P,S,T */ case 'H': if (isvowel(Next_Letter) && !AFFECTH(Prev_Letter)) Phonize('H'); break; /* dropped if after C * else K */ case 'K': if (Prev_Letter != 'C') Phonize('K'); break; /* F if before H * else P */ case 'P': if (Next_Letter == 'H') { Phonize('F'); } else { Phonize('P'); } break; /* K */ case 'Q': Phonize('K'); break; /* 'sh' in -SH-, -SIO- or -SIA- or -SCHW- * else S */ case 'S': if (Next_Letter == 'I' && (After_Next_Letter == 'O' || After_Next_Letter == 'A')) { Phonize(SH); } else if (Next_Letter == 'H') { Phonize(SH); skip_letter++; } else if ((!traditional) && (Next_Letter == 'C' && Look_Ahead_Letter(2) == 'H' && Look_Ahead_Letter(3) == 'W')) { Phonize(SH); skip_letter += 2; } else { Phonize('S'); } break; /* 'sh' in -TIA- or -TIO- * else 'th' before H * else T */ case 'T': if (Next_Letter == 'I' && (After_Next_Letter == 'O' || After_Next_Letter == 'A')) { Phonize(SH); } else if (Next_Letter == 'H') { Phonize(TH); skip_letter++; } else { Phonize('T'); } break; /* F */ case 'V': Phonize('F'); break; /* W before a vowel, else dropped */ case 'W': if (isvowel(Next_Letter)) Phonize('W'); break; /* KS */ case 'X': Phonize('K'); Phonize('S'); break; /* Y if followed by a vowel */ case 'Y': if (isvowel(Next_Letter)) Phonize('Y'); break; /* S */ case 'Z': Phonize('S'); break; /* No transformation */ case 'F': case 'J': case 'L': case 'M': case 'N': case 'R': Phonize(Curr_Letter); break; default: /* nothing */ break; } /* END SWITCH */ w_idx += skip_letter; } /* END FOR */ return buffer.detach(); } /////////////////////////////////////////////////////////////////////////////// // Cyrillic /** * This is codetables for different Cyrillic charsets (relative to koi8-r). * Each table contains data for 128-255 symbols from ASCII table. * First 256 symbols are for conversion from koi8-r to corresponding charset, * second 256 symbols are for reverse conversion, from charset to koi8-r. * * Here we have the following tables: * _cyr_win1251 - for windows-1251 charset * _cyr_iso88595 - for iso8859-5 charset * _cyr_cp866 - for x-cp866 charset * _cyr_mac - for x-mac-cyrillic charset */ typedef unsigned char _cyr_charset_table[512]; static const _cyr_charset_table _cyr_win1251 = { 0,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, 46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46, 46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46, 154,174,190,46,159,189,46,46,179,191,180,157,46,46,156,183, 46,46,182,166,173,46,46,158,163,152,164,155,46,46,46,167, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209, 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,184,186,32,179,191,32,32,32,32,32,180,162,32, 32,32,32,168,170,32,178,175,32,32,32,32,32,165,161,169, 254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238, 239,255,240,241,242,243,230,226,252,251,231,248,253,249,247,250, 222,192,193,214,196,197,212,195,213,200,201,202,203,204,205,206, 207,223,208,209,210,211,198,194,220,219,199,216,221,217,215,218, }; static const _cyr_charset_table _cyr_cp866 = { 0,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, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 35,35,35,124,124,124,124,43,43,124,124,43,43,43,43,43, 43,45,45,124,45,43,124,124,43,43,45,45,124,45,43,45, 45,45,45,43,43,43,43,43,43,43,43,35,35,124,124,35, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209, 179,163,180,164,183,167,190,174,32,149,158,32,152,159,148,154, 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 205,186,213,241,243,201,32,245,187,212,211,200,190,32,247,198, 199,204,181,240,242,185,32,244,203,207,208,202,216,32,246,32, 238,160,161,230,164,165,228,163,229,168,169,170,171,172,173,174, 175,239,224,225,226,227,166,162,236,235,167,232,237,233,231,234, 158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142, 143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154, }; static const _cyr_charset_table _cyr_iso88595 = { 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,179,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209, 32,163,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,241,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,161,32,32,32,32,32,32,32,32,32,32,32,32, 238,208,209,230,212,213,228,211,229,216,217,218,219,220,221,222, 223,239,224,225,226,227,214,210,236,235,215,232,237,233,231,234, 206,176,177,198,180,181,196,179,197,184,185,186,187,188,189,190, 191,207,192,193,194,195,182,178,204,203,183,200,205,201,199,202, }; static const _cyr_charset_table _cyr_mac = { 0,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, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 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, 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,179,163,209, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,255, 0,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, 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, 160,161,162,222,164,165,166,167,168,169,170,171,172,173,174,175, 176,177,178,221,180,181,182,183,184,185,186,187,188,189,190,191, 254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238, 239,223,240,241,242,243,230,226,252,251,231,248,253,249,247,250, 158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142, 143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154, }; /** * This is the function that performs real in-place conversion of the string * between charsets. * Parameters: * str - string to be converted * from,to - one-symbol label of source and destination charset * The following symbols are used as labels: * k - koi8-r * w - windows-1251 * i - iso8859-5 * a - x-cp866 * d - x-cp866 * m - x-mac-cyrillic */ String string_convert_cyrillic_string(const String& input, char from, char to) { const unsigned char *from_table, *to_table; unsigned char tmp; auto uinput = (unsigned char*)input.slice().data(); String retString(input.size(), ReserveString); unsigned char *str = (unsigned char *)retString.mutableData(); from_table = nullptr; to_table = nullptr; switch (toupper((int)(unsigned char)from)) { case 'W': from_table = _cyr_win1251; break; case 'A': case 'D': from_table = _cyr_cp866; break; case 'I': from_table = _cyr_iso88595; break; case 'M': from_table = _cyr_mac; break; case 'K': break; default: throw_invalid_argument("Unknown source charset: %c", from); break; } switch (toupper((int)(unsigned char)to)) { case 'W': to_table = _cyr_win1251; break; case 'A': case 'D': to_table = _cyr_cp866; break; case 'I': to_table = _cyr_iso88595; break; case 'M': to_table = _cyr_mac; break; case 'K': break; default: throw_invalid_argument("Unknown destination charset: %c", to); break; } for (int i = 0; i < input.size(); i++) { tmp = from_table == nullptr ? uinput[i] : from_table[uinput[i]]; str[i] = to_table == nullptr ? tmp : to_table[tmp + 256]; } retString.setSize(input.size()); return retString; } /////////////////////////////////////////////////////////////////////////////// // Hebrew #define HEB_BLOCK_TYPE_ENG 1 #define HEB_BLOCK_TYPE_HEB 2 #define isheb(c) \ (((((unsigned char) c) >= 224) && (((unsigned char) c) <= 250)) ? 1 : 0) #define _isblank(c) \ (((((unsigned char) c) == ' ' || ((unsigned char) c) == '\t')) ? 1 : 0) #define _isnewline(c) \ (((((unsigned char) c) == '\n' || ((unsigned char) c) == '\r')) ? 1 : 0) /** * Converts Logical Hebrew text (Hebrew Windows style) to Visual text * Cheers/complaints/flames - Zeev Suraski <zeev@php.net> */ String string_convert_hebrew_string(const String& inStr, int /*max_chars_per_line*/, int convert_newlines) { assertx(!inStr.empty()); auto str = inStr.data(); auto str_len = inStr.size(); const char *tmp; char *heb_str, *broken_str; char *target; int block_start, block_end, block_type, block_length, i; long max_chars=0; int begin, end, char_count, orig_begin; tmp = str; block_start=block_end=0; heb_str = (char *) req::malloc_noptrs(str_len + 1); SCOPE_EXIT { req::free(heb_str); }; target = heb_str+str_len; *target = 0; target--; block_length=0; if (isheb(*tmp)) { block_type = HEB_BLOCK_TYPE_HEB; } else { block_type = HEB_BLOCK_TYPE_ENG; } do { if (block_type == HEB_BLOCK_TYPE_HEB) { while ((isheb((int)*(tmp+1)) || _isblank((int)*(tmp+1)) || ispunct((int)*(tmp+1)) || (int)*(tmp+1)=='\n' ) && block_end<str_len-1) { tmp++; block_end++; block_length++; } for (i = block_start; i<= block_end; i++) { *target = str[i]; switch (*target) { case '(': *target = ')'; break; case ')': *target = '('; break; case '[': *target = ']'; break; case ']': *target = '['; break; case '{': *target = '}'; break; case '}': *target = '{'; break; case '<': *target = '>'; break; case '>': *target = '<'; break; case '\\': *target = '/'; break; case '/': *target = '\\'; break; default: break; } target--; } block_type = HEB_BLOCK_TYPE_ENG; } else { while (!isheb(*(tmp+1)) && (int)*(tmp+1)!='\n' && block_end < str_len-1) { tmp++; block_end++; block_length++; } while ((_isblank((int)*tmp) || ispunct((int)*tmp)) && *tmp!='/' && *tmp!='-' && block_end > block_start) { tmp--; block_end--; } for (i = block_end; i >= block_start; i--) { *target = str[i]; target--; } block_type = HEB_BLOCK_TYPE_HEB; } block_start=block_end+1; } while (block_end < str_len-1); String brokenStr(str_len, ReserveString); broken_str = brokenStr.mutableData(); begin=end=str_len-1; target = broken_str; while (1) { char_count=0; while ((!max_chars || char_count < max_chars) && begin > 0) { char_count++; begin--; if (begin <= 0 || _isnewline(heb_str[begin])) { while (begin > 0 && _isnewline(heb_str[begin-1])) { begin--; char_count++; } break; } } if (char_count == max_chars) { /* try to avoid breaking words */ int new_char_count=char_count, new_begin=begin; while (new_char_count > 0) { if (_isblank(heb_str[new_begin]) || _isnewline(heb_str[new_begin])) { break; } new_begin++; new_char_count--; } if (new_char_count > 0) { char_count=new_char_count; begin=new_begin; } } orig_begin=begin; if (_isblank(heb_str[begin])) { heb_str[begin]='\n'; } while (begin <= end && _isnewline(heb_str[begin])) { /* skip leading newlines */ begin++; } for (i = begin; i <= end; i++) { /* copy content */ *target = heb_str[i]; target++; } for (i = orig_begin; i <= end && _isnewline(heb_str[i]); i++) { *target = heb_str[i]; target++; } begin=orig_begin; if (begin <= 0) { *target = 0; break; } begin--; end=begin; } if (convert_newlines) { int count; auto ret = string_replace(broken_str, str_len, "\n", strlen("\n"), "<br />\n", strlen("<br />\n"), count, true); if (!ret.isNull()) { return ret; } } brokenStr.setSize(str_len); return brokenStr; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_1383_0
crossvul-cpp_data_bad_2813_0
/***************************************************************** | | AP4 - avcC Atoms | | Copyright 2002-2008 Axiomatic Systems, LLC | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4AvccAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Utils.h" #include "Ap4Types.h" /*---------------------------------------------------------------------- | dynamic cast support +---------------------------------------------------------------------*/ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvccAtom) /*---------------------------------------------------------------------- | AP4_AvccAtom::GetProfileName +---------------------------------------------------------------------*/ const char* AP4_AvccAtom::GetProfileName(AP4_UI08 profile) { switch (profile) { case AP4_AVC_PROFILE_BASELINE: return "Baseline"; case AP4_AVC_PROFILE_MAIN: return "Main"; case AP4_AVC_PROFILE_EXTENDED: return "Extended"; case AP4_AVC_PROFILE_HIGH: return "High"; case AP4_AVC_PROFILE_HIGH_10: return "High 10"; case AP4_AVC_PROFILE_HIGH_422: return "High 4:2:2"; case AP4_AVC_PROFILE_HIGH_444: return "High 4:4:4"; } return NULL; } /*---------------------------------------------------------------------- | AP4_AvccAtom::Create +---------------------------------------------------------------------*/ AP4_AvccAtom* AP4_AvccAtom::Create(AP4_Size size, AP4_ByteStream& stream) { // read the raw bytes in a buffer unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE; AP4_DataBuffer payload_data(payload_size); AP4_Result result = stream.Read(payload_data.UseData(), payload_size); if (AP4_FAILED(result)) return NULL; // check the version const AP4_UI08* payload = payload_data.GetData(); if (payload[0] != 1) { return NULL; } // check the size if (payload_size < 6) return NULL; unsigned int num_seq_params = payload[5]&31; unsigned int cursor = 6; for (unsigned int i=0; i<num_seq_params; i++) { if (cursor+2 > payload_size) return NULL; cursor += 2+AP4_BytesToInt16BE(&payload[cursor]); if (cursor > payload_size) return NULL; } unsigned int num_pic_params = payload[cursor++]; if (cursor > payload_size) return NULL; for (unsigned int i=0; i<num_pic_params; i++) { if (cursor+2 > payload_size) return NULL; cursor += 2+AP4_BytesToInt16BE(&payload[cursor]); if (cursor > payload_size) return NULL; } return new AP4_AvccAtom(size, payload); } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom() : AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE), m_ConfigurationVersion(1), m_Profile(0), m_Level(0), m_ProfileCompatibility(0), m_NaluLengthSize(0) { UpdateRawBytes(); m_Size32 += m_RawBytes.GetDataSize(); } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom(const AP4_AvccAtom& other) : AP4_Atom(AP4_ATOM_TYPE_AVCC, other.m_Size32), m_ConfigurationVersion(other.m_ConfigurationVersion), m_Profile(other.m_Profile), m_Level(other.m_Level), m_ProfileCompatibility(other.m_ProfileCompatibility), m_NaluLengthSize(other.m_NaluLengthSize), m_RawBytes(other.m_RawBytes) { // deep copy of the parameters unsigned int i = 0; for (i=0; i<other.m_SequenceParameters.ItemCount(); i++) { m_SequenceParameters.Append(other.m_SequenceParameters[i]); } for (i=0; i<other.m_PictureParameters.ItemCount(); i++) { m_PictureParameters.Append(other.m_PictureParameters[i]); } } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) : AP4_Atom(AP4_ATOM_TYPE_AVCC, size) { // make a copy of our configuration bytes unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE; m_RawBytes.SetData(payload, payload_size); // parse the payload m_ConfigurationVersion = payload[0]; m_Profile = payload[1]; m_ProfileCompatibility = payload[2]; m_Level = payload[3]; m_NaluLengthSize = 1+(payload[4]&3); AP4_UI08 num_seq_params = payload[5]&31; m_SequenceParameters.EnsureCapacity(num_seq_params); unsigned int cursor = 6; for (unsigned int i=0; i<num_seq_params; i++) { m_SequenceParameters.Append(AP4_DataBuffer()); AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]); m_SequenceParameters[i].SetData(&payload[cursor]+2, param_length); cursor += 2+param_length; } AP4_UI08 num_pic_params = payload[cursor++]; m_PictureParameters.EnsureCapacity(num_pic_params); for (unsigned int i=0; i<num_pic_params; i++) { m_PictureParameters.Append(AP4_DataBuffer()); AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]); m_PictureParameters[i].SetData(&payload[cursor]+2, param_length); cursor += 2+param_length; } } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile, AP4_UI08 level, AP4_UI08 profile_compatibility, AP4_UI08 length_size, const AP4_Array<AP4_DataBuffer>& sequence_parameters, const AP4_Array<AP4_DataBuffer>& picture_parameters) : AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE), m_ConfigurationVersion(1), m_Profile(profile), m_Level(level), m_ProfileCompatibility(profile_compatibility), m_NaluLengthSize(length_size) { // deep copy of the parameters unsigned int i = 0; for (i=0; i<sequence_parameters.ItemCount(); i++) { m_SequenceParameters.Append(sequence_parameters[i]); } for (i=0; i<picture_parameters.ItemCount(); i++) { m_PictureParameters.Append(picture_parameters[i]); } // compute the raw bytes UpdateRawBytes(); // update the size m_Size32 += m_RawBytes.GetDataSize(); } /*---------------------------------------------------------------------- | AP4_AvccAtom::UpdateRawBytes +---------------------------------------------------------------------*/ void AP4_AvccAtom::UpdateRawBytes() { // compute the payload size unsigned int payload_size = 6; for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { payload_size += 2+m_SequenceParameters[i].GetDataSize(); } ++payload_size; for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) { payload_size += 2+m_PictureParameters[i].GetDataSize(); } m_RawBytes.SetDataSize(payload_size); AP4_UI08* payload = m_RawBytes.UseData(); payload[0] = m_ConfigurationVersion; payload[1] = m_Profile; payload[2] = m_ProfileCompatibility; payload[3] = m_Level; payload[4] = 0xFC | (m_NaluLengthSize-1); payload[5] = 0xE0 | (AP4_UI08)m_SequenceParameters.ItemCount(); unsigned int cursor = 6; for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { AP4_UI16 param_length = (AP4_UI16)m_SequenceParameters[i].GetDataSize(); AP4_BytesFromUInt16BE(&payload[cursor], param_length); cursor += 2; AP4_CopyMemory(&payload[cursor], m_SequenceParameters[i].GetData(), param_length); cursor += param_length; } payload[cursor++] = (AP4_UI08)m_PictureParameters.ItemCount(); for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) { AP4_UI16 param_length = (AP4_UI16)m_PictureParameters[i].GetDataSize(); AP4_BytesFromUInt16BE(&payload[cursor], param_length); cursor += 2; AP4_CopyMemory(&payload[cursor], m_PictureParameters[i].GetData(), param_length); cursor += param_length; } } /*---------------------------------------------------------------------- | AP4_AvccAtom::WriteFields +---------------------------------------------------------------------*/ AP4_Result AP4_AvccAtom::WriteFields(AP4_ByteStream& stream) { return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize()); } /*---------------------------------------------------------------------- | AP4_AvccAtom::InspectFields +---------------------------------------------------------------------*/ AP4_Result AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector) { inspector.AddField("Configuration Version", m_ConfigurationVersion); const char* profile_name = GetProfileName(m_Profile); if (profile_name) { inspector.AddField("Profile", profile_name); } else { inspector.AddField("Profile", m_Profile); } inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX); inspector.AddField("Level", m_Level); inspector.AddField("NALU Length Size", m_NaluLengthSize); for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize()); } for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) { inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize()); } return AP4_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_2813_0
crossvul-cpp_data_good_3218_0
/* Audio File Library Copyright (C) 2010-2013, Michael Pruett <michael@68k.org> Copyright (C) 2001, Silicon Graphics, Inc. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /* This module implements IMA ADPCM compression. */ #include "config.h" #include "IMA.h" #include <assert.h> #include <audiofile.h> #include "BlockCodec.h" #include "Compiler.h" #include "File.h" #include "Track.h" #include "afinternal.h" #include "byteorder.h" #include "util.h" #include "../pcm.h" struct adpcmState { int previousValue; // previous output value int index; // index into step table adpcmState() { previousValue = 0; index = 0; } }; class IMA : public BlockCodec { public: static IMA *createDecompress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames); static IMA *createCompress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames); virtual ~IMA(); virtual const char *name() const OVERRIDE { return mode() == Compress ? "ima_adpcm_compress" : "ima_adpcm_decompress"; } virtual void describe() OVERRIDE; private: int m_imaType; adpcmState *m_adpcmState; IMA(Mode, Track *, File *fh, bool canSeek); int decodeBlock(const uint8_t *encoded, int16_t *decoded) OVERRIDE; int decodeBlockWAVE(const uint8_t *encoded, int16_t *decoded); int decodeBlockQT(const uint8_t *encoded, int16_t *decoded); int encodeBlock(const int16_t *input, uint8_t *output) OVERRIDE; int encodeBlockWAVE(const int16_t *input, uint8_t *output); int encodeBlockQT(const int16_t *input, uint8_t *output); }; IMA::IMA(Mode mode, Track *track, File *fh, bool canSeek) : BlockCodec(mode, track, fh, canSeek), m_imaType(0) { AUpvlist pv = (AUpvlist) track->f.compressionParams; m_framesPerPacket = track->f.framesPerPacket; m_bytesPerPacket = track->f.bytesPerPacket; long l; if (_af_pv_getlong(pv, _AF_IMA_ADPCM_TYPE, &l)) m_imaType = l; m_adpcmState = new adpcmState[track->f.channelCount]; } IMA::~IMA() { delete [] m_adpcmState; } int IMA::decodeBlock(const uint8_t *encoded, int16_t *decoded) { if (m_imaType == _AF_IMA_ADPCM_TYPE_WAVE) return decodeBlockWAVE(encoded, decoded); else if (m_imaType == _AF_IMA_ADPCM_TYPE_QT) return decodeBlockQT(encoded, decoded); return 0; } static const int8_t indexTable[16] = { -1, -1, -1, -1, 2, 4, 6, 8, -1, -1, -1, -1, 2, 4, 6, 8, }; static const int16_t stepTable[89] = { 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767 }; static inline int clamp(int x, int low, int high) { if (x < low) return low; if (x > high) return high; return x; } static inline int16_t decodeSample(adpcmState &state, uint8_t code) { int step = stepTable[state.index]; int diff = step >> 3; if (code & 4) diff += step; if (code & 2) diff += step>>1; if (code & 1) diff += step>>2; int predictor = state.previousValue; if (code & 8) predictor -= diff; else predictor += diff; state.previousValue = clamp(predictor, MIN_INT16, MAX_INT16); state.index = clamp(state.index + indexTable[code], 0, 88); return state.previousValue; } int IMA::decodeBlockWAVE(const uint8_t *encoded, int16_t *decoded) { int channelCount = m_track->f.channelCount; for (int c=0; c<channelCount; c++) { m_adpcmState[c].previousValue = (encoded[1]<<8) | encoded[0]; if (encoded[1] & 0x80) m_adpcmState[c].previousValue -= 0x10000; m_adpcmState[c].index = clamp(encoded[2], 0, 88); *decoded++ = m_adpcmState[c].previousValue; encoded += 4; } for (int n=0; n<m_framesPerPacket - 1; n += 8) { for (int c=0; c<channelCount; c++) { int16_t *output = decoded + c; for (int s=0; s<4; s++) { *output = decodeSample(m_adpcmState[c], *encoded & 0xf); output += channelCount; *output = decodeSample(m_adpcmState[c], *encoded >> 4); output += channelCount; encoded++; } } decoded += channelCount * 8; } return m_framesPerPacket * channelCount * sizeof (int16_t); } int IMA::decodeBlockQT(const uint8_t *encoded, int16_t *decoded) { int channelCount = m_track->f.channelCount; for (int c=0; c<channelCount; c++) { adpcmState state; int predictor = (encoded[0] << 8) | (encoded[1] & 0x80); if (predictor & 0x8000) predictor -= 0x10000; state.previousValue = clamp(predictor, MIN_INT16, MAX_INT16); state.index = clamp(encoded[1] & 0x7f, 0, 88); encoded += 2; for (int n=0; n<m_framesPerPacket; n+=2) { uint8_t e = *encoded; decoded[n*channelCount + c] = decodeSample(state, e & 0xf); decoded[(n+1)*channelCount + c] = decodeSample(state, e >> 4); encoded++; } } return m_framesPerPacket * channelCount * sizeof (int16_t); } int IMA::encodeBlock(const int16_t *input, uint8_t *output) { if (m_imaType == _AF_IMA_ADPCM_TYPE_WAVE) return encodeBlockWAVE(input, output); else if (m_imaType == _AF_IMA_ADPCM_TYPE_QT) return encodeBlockQT(input, output); return 0; } static inline uint8_t encodeSample(adpcmState &state, int16_t sample) { int step = stepTable[state.index]; int diff = sample - state.previousValue; int vpdiff = step >> 3; uint8_t code = 0; if (diff < 0) { code = 8; diff = -diff; } if (diff >= step) { code |= 4; diff -= step; vpdiff += step; } step >>= 1; if (diff >= step) { code |= 2; diff -= step; vpdiff += step; } step >>= 1; if (diff >= step) { code |= 1; vpdiff += step; } if (code & 8) vpdiff = -vpdiff; state.previousValue = clamp(state.previousValue + vpdiff, MIN_INT16, MAX_INT16); state.index = clamp(state.index + indexTable[code], 0, 88); return code & 0xf; } int IMA::encodeBlockWAVE(const int16_t *input, uint8_t *output) { int channelCount = m_track->f.channelCount; for (int c=0; c<channelCount; c++) { output[0] = m_adpcmState[c].previousValue & 0xff; output[1] = m_adpcmState[c].previousValue >> 8; output[2] = m_adpcmState[c].index; output[3] = 0; output += 4; } for (int n=0; n<m_framesPerPacket - 1; n += 8) { for (int c=0; c<channelCount; c++) { const int16_t *currentInput = input + c; for (int s=0; s<4; s++) { uint8_t encodedValue = encodeSample(m_adpcmState[c], *currentInput); currentInput += channelCount; encodedValue |= encodeSample(m_adpcmState[c], *currentInput) << 4; currentInput += channelCount; *output++ = encodedValue; } } input += channelCount * 8; } return m_bytesPerPacket; } int IMA::encodeBlockQT(const int16_t *input, uint8_t *output) { int channelCount = m_track->f.channelCount; for (int c=0; c<channelCount; c++) { adpcmState state = m_adpcmState[c]; state.previousValue &= ~0x7f; output[0] = (state.previousValue >> 8) & 0xff; output[1] = (state.previousValue & 0x80) | (state.index & 0x7f); output += 2; for (int n=0; n<m_framesPerPacket; n+=2) { uint8_t encoded = encodeSample(state, input[n*channelCount + c]); encoded |= encodeSample(state, input[(n+1)*channelCount + c]) << 4; *output++ = encoded; } m_adpcmState[c] = state; } return m_bytesPerPacket; } bool _af_ima_adpcm_format_ok (AudioFormat *f) { if (f->channelCount != 1 && f->channelCount != 2) { _af_error(AF_BAD_COMPRESSION, "IMA ADPCM compression requires 1 or 2 channels"); return false; } if (f->sampleFormat != AF_SAMPFMT_TWOSCOMP || f->sampleWidth != 16) { _af_error(AF_BAD_COMPRESSION, "IMA ADPCM compression requires 16-bit signed integer format"); return false; } if (f->byteOrder != _AF_BYTEORDER_NATIVE) { _af_error(AF_BAD_COMPRESSION, "IMA ADPCM compression requires native byte order"); return false; } return true; } void IMA::describe() { m_outChunk->f.byteOrder = _AF_BYTEORDER_NATIVE; m_outChunk->f.compressionType = AF_COMPRESSION_NONE; m_outChunk->f.compressionParams = AU_NULL_PVLIST; } IMA *IMA::createDecompress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { assert(fh->tell() == track->fpos_first_frame); IMA *ima = new IMA(Decompress, track, fh, canSeek); if (!ima->m_imaType) { _af_error(AF_BAD_CODEC_CONFIG, "IMA type not set"); delete ima; return NULL; } *chunkFrames = ima->m_framesPerPacket; return ima; } IMA *IMA::createCompress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { assert(fh->tell() == track->fpos_first_frame); IMA *ima = new IMA(Compress, track, fh, canSeek); if (!ima->m_imaType) { _af_error(AF_BAD_CODEC_CONFIG, "IMA type not set"); delete ima; return NULL; } *chunkFrames = ima->m_framesPerPacket; return ima; } FileModule *_af_ima_adpcm_init_decompress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { return IMA::createDecompress(track, fh, canSeek, headerless, chunkFrames); } FileModule *_af_ima_adpcm_init_compress(Track *track, File *fh, bool canSeek, bool headerless, AFframecount *chunkFrames) { return IMA::createCompress(track, fh, canSeek, headerless, chunkFrames); }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_3218_0
crossvul-cpp_data_good_94_2
/* -*- C++ -*- * File: libraw_cxx.cpp * Copyright 2008-2018 LibRaw LLC (info@libraw.org) * Created: Sat Mar 8 , 2008 * * LibRaw C++ interface (implementation) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). */ #include <math.h> #include <errno.h> #include <float.h> #include <new> #include <exception> #include <sys/types.h> #include <sys/stat.h> #if !defined(_WIN32) && !defined(__MINGW32__) #include <netinet/in.h> #else #include <winsock2.h> #endif #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #ifdef USE_ZLIB #include <zlib.h> #endif #ifdef USE_RAWSPEED #include "../RawSpeed/rawspeed_xmldata.cpp" #include <RawSpeed/StdAfx.h> #include <RawSpeed/FileMap.h> #include <RawSpeed/RawParser.h> #include <RawSpeed/RawDecoder.h> #include <RawSpeed/CameraMetaData.h> #include <RawSpeed/ColorFilterArray.h> #endif #ifdef USE_DNGSDK #include "dng_host.h" #include "dng_negative.h" #include "dng_simple_image.h" #include "dng_info.h" #endif #include "libraw_fuji_compressed.cpp" #ifdef __cplusplus extern "C" { #endif void default_memory_callback(void *, const char *file, const char *where) { fprintf(stderr, "%s: Out of memory in %s\n", file ? file : "unknown file", where); } void default_data_callback(void *, const char *file, const int offset) { if (offset < 0) fprintf(stderr, "%s: Unexpected end of file\n", file ? file : "unknown file"); else fprintf(stderr, "%s: data corrupted at %d\n", file ? file : "unknown file", offset); } const char *libraw_strerror(int e) { enum LibRaw_errors errorcode = (LibRaw_errors)e; switch (errorcode) { case LIBRAW_SUCCESS: return "No error"; case LIBRAW_UNSPECIFIED_ERROR: return "Unspecified error"; case LIBRAW_FILE_UNSUPPORTED: return "Unsupported file format or not RAW file"; case LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE: return "Request for nonexisting image number"; case LIBRAW_OUT_OF_ORDER_CALL: return "Out of order call of libraw function"; case LIBRAW_NO_THUMBNAIL: return "No thumbnail in file"; case LIBRAW_UNSUPPORTED_THUMBNAIL: return "Unsupported thumbnail format"; case LIBRAW_INPUT_CLOSED: return "No input stream, or input stream closed"; case LIBRAW_UNSUFFICIENT_MEMORY: return "Unsufficient memory"; case LIBRAW_DATA_ERROR: return "Corrupted data or unexpected EOF"; case LIBRAW_IO_ERROR: return "Input/output error"; case LIBRAW_CANCELLED_BY_CALLBACK: return "Cancelled by user callback"; case LIBRAW_BAD_CROP: return "Bad crop box"; default: return "Unknown error code"; } } #ifdef __cplusplus } #endif #define Sigma_X3F 22 const double LibRaw_constants::xyz_rgb[3][3] = { {0.4124564, 0.3575761, 0.1804375}, {0.2126729, 0.7151522, 0.0721750}, {0.0193339, 0.1191920, 0.9503041}}; const float LibRaw_constants::d65_white[3] = {0.95047f, 1.0f, 1.08883f}; #define P1 imgdata.idata #define S imgdata.sizes #define O imgdata.params #define C imgdata.color #define T imgdata.thumbnail #define IO libraw_internal_data.internal_output_params #define ID libraw_internal_data.internal_data #define EXCEPTION_HANDLER(e) \ do \ { \ /* fprintf(stderr,"Exception %d caught\n",e);*/ \ switch (e) \ { \ case LIBRAW_EXCEPTION_ALLOC: \ recycle(); \ return LIBRAW_UNSUFFICIENT_MEMORY; \ case LIBRAW_EXCEPTION_DECODE_RAW: \ case LIBRAW_EXCEPTION_DECODE_JPEG: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_DECODE_JPEG2000: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_IO_EOF: \ case LIBRAW_EXCEPTION_IO_CORRUPT: \ recycle(); \ return LIBRAW_IO_ERROR; \ case LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK: \ recycle(); \ return LIBRAW_CANCELLED_BY_CALLBACK; \ case LIBRAW_EXCEPTION_BAD_CROP: \ recycle(); \ return LIBRAW_BAD_CROP; \ default: \ return LIBRAW_UNSPECIFIED_ERROR; \ } \ } while (0) const char *LibRaw::version() { return LIBRAW_VERSION_STR; } int LibRaw::versionNumber() { return LIBRAW_VERSION; } const char *LibRaw::strerror(int p) { return libraw_strerror(p); } unsigned LibRaw::capabilities() { unsigned ret = 0; #ifdef USE_RAWSPEED ret |= LIBRAW_CAPS_RAWSPEED; #endif #ifdef USE_DNGSDK ret |= LIBRAW_CAPS_DNGSDK; #endif return ret; } unsigned LibRaw::parse_custom_cameras(unsigned limit, libraw_custom_camera_t table[], char **list) { if (!list) return 0; unsigned index = 0; for (int i = 0; i < limit; i++) { if (!list[i]) break; if (strlen(list[i]) < 10) continue; char *string = (char *)malloc(strlen(list[i]) + 1); strcpy(string, list[i]); char *start = string; memset(&table[index], 0, sizeof(table[0])); for (int j = 0; start && j < 14; j++) { char *end = strchr(start, ','); if (end) { *end = 0; end++; } // move to next char while (isspace(*start) && *start) start++; // skip leading spaces? unsigned val = strtol(start, 0, 10); switch (j) { case 0: table[index].fsize = val; break; case 1: table[index].rw = val; break; case 2: table[index].rh = val; break; case 3: table[index].lm = val; break; case 4: table[index].tm = val; break; case 5: table[index].rm = val; break; case 6: table[index].bm = val; break; case 7: table[index].lf = val; break; case 8: table[index].cf = val; break; case 9: table[index].max = val; break; case 10: table[index].flags = val; break; case 11: strncpy(table[index].t_make, start, sizeof(table[index].t_make) - 1); break; case 12: strncpy(table[index].t_model, start, sizeof(table[index].t_model) - 1); break; case 13: table[index].offset = val; break; default: break; } start = end; } free(string); if (table[index].t_make[0]) index++; } return index; } void LibRaw::derror() { if (!libraw_internal_data.unpacker_data.data_error && libraw_internal_data.internal_data.input) { if (libraw_internal_data.internal_data.input->eof()) { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), -1); throw LIBRAW_EXCEPTION_IO_EOF; } else { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), libraw_internal_data.internal_data.input->tell()); // throw LIBRAW_EXCEPTION_IO_CORRUPT; } } libraw_internal_data.unpacker_data.data_error++; } void LibRaw::dcraw_clear_mem(libraw_processed_image_t *p) { if (p) ::free(p); } int LibRaw::is_sraw() { return load_raw == &LibRaw::canon_sraw_load_raw || load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::is_coolscan_nef() { return load_raw == &LibRaw::nikon_coolscan_load_raw; } int LibRaw::is_jpeg_thumb() { return thumb_load_raw == 0 && write_thumb == &LibRaw::jpeg_thumb; } int LibRaw::is_nikon_sraw() { return load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::sraw_midpoint() { if (load_raw == &LibRaw::canon_sraw_load_raw) return 8192; else if (load_raw == &LibRaw::nikon_load_sraw) return 2048; else return 0; } #ifdef USE_RAWSPEED using namespace RawSpeed; class CameraMetaDataLR : public CameraMetaData { public: CameraMetaDataLR() : CameraMetaData() {} CameraMetaDataLR(char *filename) : CameraMetaData(filename) {} CameraMetaDataLR(char *data, int sz); }; CameraMetaDataLR::CameraMetaDataLR(char *data, int sz) : CameraMetaData() { ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { ThrowCME("CameraMetaData:Could not initialize context."); } xmlResetLastError(); doc = xmlCtxtReadMemory(ctxt, data, sz, "", NULL, XML_PARSE_DTDVALID); if (doc == NULL) { ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s", ctxt->lastError.message); } if (ctxt->valid == 0) { if (ctxt->lastError.code == 0x5e) { // printf("CameraMetaData: Unable to locate DTD, attempting to ignore."); } else { ThrowCME("CameraMetaData: XML file does not validate. DTD Error was: %s", ctxt->lastError.message); } } xmlNodePtr cur; cur = xmlDocGetRootElement(doc); if (xmlStrcmp(cur->name, (const xmlChar *)"Cameras")) { ThrowCME("CameraMetaData: XML document of the wrong type, root node is not cameras."); return; } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"Camera"))) { Camera *camera = new Camera(doc, cur); addCamera(camera); // Create cameras for aliases. for (unsigned int i = 0; i < camera->aliases.size(); i++) { addCamera(new Camera(camera, i)); } } cur = cur->next; } if (doc) xmlFreeDoc(doc); doc = 0; if (ctxt) xmlFreeParserCtxt(ctxt); ctxt = 0; } #define RAWSPEED_DATA_COUNT (sizeof(_rawspeed_data_xml) / sizeof(_rawspeed_data_xml[0])) static CameraMetaDataLR *make_camera_metadata() { int len = 0, i; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { len += strlen(_rawspeed_data_xml[i]); } char *rawspeed_xml = (char *)calloc(len + 1, sizeof(_rawspeed_data_xml[0][0])); if (!rawspeed_xml) return NULL; int offt = 0; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { int ll = strlen(_rawspeed_data_xml[i]); if (offt + ll > len) break; memmove(rawspeed_xml + offt, _rawspeed_data_xml[i], ll); offt += ll; } rawspeed_xml[offt] = 0; CameraMetaDataLR *ret = NULL; try { ret = new CameraMetaDataLR(rawspeed_xml, offt); } catch (...) { // Mask all exceptions } free(rawspeed_xml); return ret; } #endif #define ZERO(a) memset(&a, 0, sizeof(a)) static void cleargps(libraw_gps_info_t *q) { for (int i = 0; i < 3; i++) q->latitude[i] = q->longtitude[i] = q->gpstimestamp[i] = 0.f; q->altitude = 0.f; q->altref = q->latref = q->longref = q->gpsstatus = q->gpsparsed = 0; } LibRaw::LibRaw(unsigned int flags) : memmgr(1024) { double aber[4] = {1, 1, 1, 1}; double gamm[6] = {0.45, 4.5, 0, 0, 0, 0}; unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX}; unsigned cropbox[4] = {0, 0, UINT_MAX, UINT_MAX}; #ifdef DCRAW_VERBOSE verbose = 1; #else verbose = 0; #endif ZERO(imgdata); cleargps(&imgdata.other.parsed_gps); ZERO(libraw_internal_data); ZERO(callbacks); _rawspeed_camerameta = _rawspeed_decoder = NULL; dnghost = NULL; _x3f_data = NULL; #ifdef USE_RAWSPEED CameraMetaDataLR *camerameta = make_camera_metadata(); // May be NULL in case of exception in make_camera_metadata() _rawspeed_camerameta = static_cast<void *>(camerameta); #endif callbacks.mem_cb = (flags & LIBRAW_OPIONS_NO_MEMERR_CALLBACK) ? NULL : &default_memory_callback; callbacks.data_cb = (flags & LIBRAW_OPIONS_NO_DATAERR_CALLBACK) ? NULL : &default_data_callback; callbacks.exif_cb = NULL; // no default callback callbacks.pre_identify_cb = NULL; callbacks.post_identify_cb = NULL; callbacks.pre_subtractblack_cb = callbacks.pre_scalecolors_cb = callbacks.pre_preinterpolate_cb = callbacks.pre_interpolate_cb = callbacks.interpolate_bayer_cb = callbacks.interpolate_xtrans_cb = callbacks.post_interpolate_cb = callbacks.pre_converttorgb_cb = callbacks.post_converttorgb_cb = NULL; memmove(&imgdata.params.aber, &aber, sizeof(aber)); memmove(&imgdata.params.gamm, &gamm, sizeof(gamm)); memmove(&imgdata.params.greybox, &greybox, sizeof(greybox)); memmove(&imgdata.params.cropbox, &cropbox, sizeof(cropbox)); imgdata.params.bright = 1; imgdata.params.use_camera_matrix = 1; imgdata.params.user_flip = -1; imgdata.params.user_black = -1; imgdata.params.user_cblack[0] = imgdata.params.user_cblack[1] = imgdata.params.user_cblack[2] = imgdata.params.user_cblack[3] = -1000001; imgdata.params.user_sat = -1; imgdata.params.user_qual = -1; imgdata.params.output_color = 1; imgdata.params.output_bps = 8; imgdata.params.use_fuji_rotate = 1; imgdata.params.exp_shift = 1.0; imgdata.params.auto_bright_thr = LIBRAW_DEFAULT_AUTO_BRIGHTNESS_THRESHOLD; imgdata.params.adjust_maximum_thr = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; imgdata.params.use_rawspeed = 1; imgdata.params.use_dngsdk = LIBRAW_DNG_DEFAULT; imgdata.params.no_auto_scale = 0; imgdata.params.no_interpolation = 0; imgdata.params.raw_processing_options = LIBRAW_PROCESSING_DP2Q_INTERPOLATERG | LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF | LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT; imgdata.params.sony_arw2_posterization_thr = 0; imgdata.params.green_matching = 0; imgdata.params.custom_camera_strings = 0; imgdata.params.coolscan_nef_gamma = 1.0f; imgdata.parent_class = this; imgdata.progress_flags = 0; imgdata.color.baseline_exposure = -999.f; _exitflag = 0; tls = new LibRaw_TLS; tls->init(); } int LibRaw::set_rawspeed_camerafile(char *filename) { #ifdef USE_RAWSPEED try { CameraMetaDataLR *camerameta = new CameraMetaDataLR(filename); if (_rawspeed_camerameta) { CameraMetaDataLR *d = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete d; } _rawspeed_camerameta = static_cast<void *>(camerameta); } catch (...) { // just return error code return -1; } #endif return 0; } LibRaw::~LibRaw() { recycle(); delete tls; #ifdef USE_RAWSPEED if (_rawspeed_camerameta) { CameraMetaDataLR *cmeta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete cmeta; _rawspeed_camerameta = NULL; } #endif } void *LibRaw::malloc(size_t t) { void *p = memmgr.malloc(t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::realloc(void *q, size_t t) { void *p = memmgr.realloc(q, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::calloc(size_t n, size_t t) { void *p = memmgr.calloc(n, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void LibRaw::free(void *p) { memmgr.free(p); } void LibRaw::recycle_datastream() { if (libraw_internal_data.internal_data.input && libraw_internal_data.internal_data.input_internal) { delete libraw_internal_data.internal_data.input; libraw_internal_data.internal_data.input = NULL; } libraw_internal_data.internal_data.input_internal = 0; } void x3f_clear(void *); void LibRaw::recycle() { recycle_datastream(); #define FREE(a) \ do \ { \ if (a) \ { \ free(a); \ a = NULL; \ } \ } while (0) FREE(imgdata.image); FREE(imgdata.thumbnail.thumb); FREE(libraw_internal_data.internal_data.meta_data); FREE(libraw_internal_data.output_data.histogram); FREE(libraw_internal_data.output_data.oprof); FREE(imgdata.color.profile); FREE(imgdata.rawdata.ph1_cblack); FREE(imgdata.rawdata.ph1_rblack); FREE(imgdata.rawdata.raw_alloc); FREE(imgdata.idata.xmpdata); #undef FREE ZERO(imgdata.sizes); imgdata.sizes.raw_crop.cleft = 0xffff; imgdata.sizes.raw_crop.ctop = 0xffff; ZERO(imgdata.idata); ZERO(imgdata.makernotes); ZERO(imgdata.color); ZERO(imgdata.other); ZERO(imgdata.thumbnail); ZERO(imgdata.rawdata); imgdata.makernotes.olympus.OlympusCropID = -1; imgdata.makernotes.sony.raw_crop.cleft = 0xffff; imgdata.makernotes.sony.raw_crop.ctop = 0xffff; cleargps(&imgdata.other.parsed_gps); imgdata.color.baseline_exposure = -999.f; imgdata.makernotes.fuji.FujiExpoMidPointShift = -999.f; imgdata.makernotes.fuji.FujiDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiFilmMode = 0xffff; imgdata.makernotes.fuji.FujiDynamicRangeSetting = 0xffff; imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiAutoDynamicRange = 0xffff; imgdata.makernotes.fuji.FocusMode = 0xffff; imgdata.makernotes.fuji.AFMode = 0xffff; imgdata.makernotes.fuji.FocusPixel[0] = imgdata.makernotes.fuji.FocusPixel[1] = 0xffff; imgdata.makernotes.fuji.ImageStabilization[0] = imgdata.makernotes.fuji.ImageStabilization[1] = imgdata.makernotes.fuji.ImageStabilization[2] = 0xffff; imgdata.makernotes.sony.SonyCameraType = 0xffff; imgdata.makernotes.sony.real_iso_offset = 0xffff; imgdata.makernotes.sony.ImageCount3_offset = 0xffff; imgdata.makernotes.sony.ElectronicFrontCurtainShutter = 0xffff; imgdata.makernotes.kodak.BlackLevelTop = 0xffff; imgdata.makernotes.kodak.BlackLevelBottom = 0xffff; imgdata.color.dng_color[0].illuminant = imgdata.color.dng_color[1].illuminant = 0xffff; for (int i = 0; i < 4; i++) imgdata.color.dng_levels.analogbalance[i] = 1.0f; ZERO(libraw_internal_data); ZERO(imgdata.lens); imgdata.lens.makernotes.CanonFocalUnits = 1; imgdata.lens.makernotes.LensID = 0xffffffffffffffffULL; ZERO(imgdata.shootinginfo); imgdata.shootinginfo.DriveMode = -1; imgdata.shootinginfo.FocusMode = -1; imgdata.shootinginfo.MeteringMode = -1; imgdata.shootinginfo.AFPoint = -1; imgdata.shootinginfo.ExposureMode = -1; imgdata.shootinginfo.ImageStabilization = -1; _exitflag = 0; #ifdef USE_RAWSPEED if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); delete d; } _rawspeed_decoder = 0; #endif if (_x3f_data) { x3f_clear(_x3f_data); _x3f_data = 0; } memmgr.cleanup(); imgdata.thumbnail.tformat = LIBRAW_THUMBNAIL_UNKNOWN; imgdata.progress_flags = 0; load_raw = thumb_load_raw = 0; tls->init(); } const char *LibRaw::unpack_function_name() { libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); return decoder_info.decoder_name; } int LibRaw::get_decoder_info(libraw_decoder_info_t *d_info) { if (!d_info) return LIBRAW_UNSPECIFIED_ERROR; d_info->decoder_name = 0; d_info->decoder_flags = 0; if (!load_raw) return LIBRAW_OUT_OF_ORDER_CALL; int rawdata = (imgdata.idata.filters || P1.colors == 1); // dcraw.c names order if (load_raw == &LibRaw::android_tight_load_raw) { d_info->decoder_name = "android_tight_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::android_loose_load_raw) { d_info->decoder_name = "android_loose_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_600_load_raw) { d_info->decoder_name = "canon_600_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::fuji_compressed_load_raw) { d_info->decoder_name = "fuji_compressed_load_raw()"; } else if (load_raw == &LibRaw::fuji_14bit_load_raw) { d_info->decoder_name = "fuji_14bit_load_raw()"; } else if (load_raw == &LibRaw::canon_load_raw) { d_info->decoder_name = "canon_load_raw()"; } else if (load_raw == &LibRaw::lossless_jpeg_load_raw) { d_info->decoder_name = "lossless_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::canon_sraw_load_raw) { d_info->decoder_name = "canon_sraw_load_raw()"; // d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::lossless_dng_load_raw) { d_info->decoder_name = "lossless_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::packed_dng_load_raw) { d_info->decoder_name = "packed_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::pentax_load_raw) { d_info->decoder_name = "pentax_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_load_raw) { d_info->decoder_name = "nikon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_coolscan_load_raw) { d_info->decoder_name = "nikon_coolscan_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_load_sraw) { d_info->decoder_name = "nikon_load_sraw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_yuv_load_raw) { d_info->decoder_name = "nikon_load_yuv_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::rollei_load_raw) { // UNTESTED d_info->decoder_name = "rollei_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::phase_one_load_raw) { d_info->decoder_name = "phase_one_load_raw()"; } else if (load_raw == &LibRaw::phase_one_load_raw_c) { d_info->decoder_name = "phase_one_load_raw_c()"; } else if (load_raw == &LibRaw::hasselblad_load_raw) { d_info->decoder_name = "hasselblad_load_raw()"; } else if (load_raw == &LibRaw::leaf_hdr_load_raw) { d_info->decoder_name = "leaf_hdr_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw) { d_info->decoder_name = "unpacked_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw_reversed) { d_info->decoder_name = "unpacked_load_raw_reversed()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sinar_4shot_load_raw) { // UNTESTED d_info->decoder_name = "sinar_4shot_load_raw()"; } else if (load_raw == &LibRaw::imacon_full_load_raw) { d_info->decoder_name = "imacon_full_load_raw()"; } else if (load_raw == &LibRaw::hasselblad_full_load_raw) { d_info->decoder_name = "hasselblad_full_load_raw()"; } else if (load_raw == &LibRaw::packed_load_raw) { d_info->decoder_name = "packed_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::broadcom_load_raw) { // UNTESTED d_info->decoder_name = "broadcom_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nokia_load_raw) { // UNTESTED d_info->decoder_name = "nokia_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_rmf_load_raw) { // UNTESTED d_info->decoder_name = "canon_rmf_load_raw()"; } else if (load_raw == &LibRaw::panasonic_load_raw) { d_info->decoder_name = "panasonic_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::olympus_load_raw) { d_info->decoder_name = "olympus_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::minolta_rd175_load_raw) { // UNTESTED d_info->decoder_name = "minolta_rd175_load_raw()"; } else if (load_raw == &LibRaw::quicktake_100_load_raw) { // UNTESTED d_info->decoder_name = "quicktake_100_load_raw()"; } else if (load_raw == &LibRaw::kodak_radc_load_raw) { d_info->decoder_name = "kodak_radc_load_raw()"; } else if (load_raw == &LibRaw::kodak_jpeg_load_raw) { // UNTESTED + RBAYER d_info->decoder_name = "kodak_jpeg_load_raw()"; } else if (load_raw == &LibRaw::lossy_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossy_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_dc120_load_raw) { d_info->decoder_name = "kodak_dc120_load_raw()"; } else if (load_raw == &LibRaw::eight_bit_load_raw) { d_info->decoder_name = "eight_bit_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c330_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c603_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_262_load_raw) { d_info->decoder_name = "kodak_262_load_raw()"; // UNTESTED! d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_65000_load_raw) { d_info->decoder_name = "kodak_65000_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { // UNTESTED d_info->decoder_name = "kodak_ycbcr_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_rgb_load_raw) { // UNTESTED d_info->decoder_name = "kodak_rgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sony_load_raw) { d_info->decoder_name = "sony_load_raw()"; } else if (load_raw == &LibRaw::sony_arw_load_raw) { d_info->decoder_name = "sony_arw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::sony_arw2_load_raw) { d_info->decoder_name = "sony_arw2_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_SONYARW2; } else if (load_raw == &LibRaw::sony_arq_load_raw) { d_info->decoder_name = "sony_arq_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::samsung_load_raw) { d_info->decoder_name = "samsung_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::samsung2_load_raw) { d_info->decoder_name = "samsung2_load_raw()"; } else if (load_raw == &LibRaw::samsung3_load_raw) { d_info->decoder_name = "samsung3_load_raw()"; } else if (load_raw == &LibRaw::smal_v6_load_raw) { // UNTESTED d_info->decoder_name = "smal_v6_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::smal_v9_load_raw) { // UNTESTED d_info->decoder_name = "smal_v9_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::redcine_load_raw) { d_info->decoder_name = "redcine_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::x3f_load_raw) { d_info->decoder_name = "x3f_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC | LIBRAW_DECODER_FIXEDMAXC | LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::pentax_4shot_load_raw) { d_info->decoder_name = "pentax_4shot_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::deflate_dng_load_raw) { d_info->decoder_name = "deflate_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::nikon_load_striped_packed_raw) { d_info->decoder_name = "nikon_load_striped_packed_raw()"; } else { d_info->decoder_name = "Unknown unpack function"; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; } return LIBRAW_SUCCESS; } int LibRaw::adjust_maximum() { ushort real_max; float auto_threshold; if (O.adjust_maximum_thr < 0.00001) return LIBRAW_SUCCESS; else if (O.adjust_maximum_thr > 0.99999) auto_threshold = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; else auto_threshold = O.adjust_maximum_thr; real_max = C.data_maximum; if (real_max > 0 && real_max < C.maximum && real_max > C.maximum * auto_threshold) { C.maximum = real_max; } return LIBRAW_SUCCESS; } void LibRaw::merror(void *ptr, const char *where) { if (ptr) return; if (callbacks.mem_cb) (*callbacks.mem_cb)( callbacks.memcb_data, libraw_internal_data.internal_data.input ? libraw_internal_data.internal_data.input->fname() : NULL, where); throw LIBRAW_EXCEPTION_ALLOC; } int LibRaw::open_file(const char *fname, INT64 max_buf_size) { #ifndef WIN32 struct stat st; if (stat(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #else struct _stati64 st; if (_stati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #endif LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) int LibRaw::open_file(const wchar_t *fname, INT64 max_buf_size) { struct _stati64 st; if (_wstati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #endif int LibRaw::open_buffer(void *buffer, size_t size) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, size); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } int LibRaw::open_bayer(unsigned char *buffer, unsigned datalen, ushort _raw_width, ushort _raw_height, ushort _left_margin, ushort _top_margin, ushort _right_margin, ushort _bottom_margin, unsigned char procflags, unsigned char bayer_pattern, unsigned unused_bits, unsigned otherflags, unsigned black_level) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, datalen); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); // From identify initdata(); strcpy(imgdata.idata.make, "BayerDump"); snprintf(imgdata.idata.model, sizeof(imgdata.idata.model) - 1, "%u x %u pixels", _raw_width, _raw_height); S.flip = procflags >> 2; libraw_internal_data.internal_output_params.zero_is_bad = procflags & 2; libraw_internal_data.unpacker_data.data_offset = 0; S.raw_width = _raw_width; S.raw_height = _raw_height; S.left_margin = _left_margin; S.top_margin = _top_margin; S.width = S.raw_width - S.left_margin - _right_margin; S.height = S.raw_height - S.top_margin - _bottom_margin; imgdata.idata.filters = 0x1010101 * bayer_pattern; imgdata.idata.colors = 4 - !((imgdata.idata.filters & imgdata.idata.filters >> 1) & 0x5555); libraw_internal_data.unpacker_data.load_flags = otherflags; switch (libraw_internal_data.unpacker_data.tiff_bps = (datalen)*8 / (S.raw_width * S.raw_height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((datalen) / S.raw_height * 3 >= S.raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (libraw_internal_data.unpacker_data.load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: libraw_internal_data.unpacker_data.load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: libraw_internal_data.unpacker_data.order = 0x4949 | 0x404 * (libraw_internal_data.unpacker_data.load_flags & 1); libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags >> 4; libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags = libraw_internal_data.unpacker_data.load_flags >> 1 & 7; load_raw = &CLASS unpacked_load_raw; } C.maximum = (1 << libraw_internal_data.unpacker_data.tiff_bps) - (1 << unused_bits); C.black = black_level; S.iwidth = S.width; S.iheight = S.height; imgdata.idata.colors = 3; imgdata.idata.filters |= ((imgdata.idata.filters >> 2 & 0x22222222) | (imgdata.idata.filters << 2 & 0x88888888)) & imgdata.idata.filters << 1; imgdata.idata.raw_count = 1; for (int i = 0; i < 4; i++) imgdata.color.pre_mul[i] = 1.0; strcpy(imgdata.idata.cdesc, "RGBG"); ID.input_internal = 1; SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); return LIBRAW_SUCCESS; } #ifdef USE_ZLIB inline unsigned int __DNG_HalfToFloat(ushort halfValue) { int sign = (halfValue >> 15) & 0x00000001; int exponent = (halfValue >> 10) & 0x0000001f; int mantissa = halfValue & 0x000003ff; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00000400)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00000400; } } else if (exponent == 31) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x1eL + 127 - 15) << 23) | (0x3ffL << 13)); } else { return 0; } } exponent += (127 - 15); mantissa <<= 13; return (unsigned int)((sign << 31) | (exponent << 23) | mantissa); } inline unsigned int __DNG_FP24ToFloat(const unsigned char *input) { int sign = (input[0] >> 7) & 0x01; int exponent = (input[0]) & 0x7F; int mantissa = (((int)input[1]) << 8) | input[2]; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00010000)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00010000; } } else if (exponent == 127) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x7eL + 128 - 64) << 23) | (0xffffL << 7)); } else { // Nan -- Just set to zero. return 0; } } exponent += (128 - 64); mantissa <<= 7; return (uint32_t)((sign << 31) | (exponent << 23) | mantissa); } inline void DecodeDeltaBytes(unsigned char *bytePtr, int cols, int channels) { if (channels == 1) { unsigned char b0 = bytePtr[0]; bytePtr += 1; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; bytePtr[0] = b0; bytePtr += 1; } } else if (channels == 3) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; bytePtr += 3; for (int col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr += 3; } } else if (channels == 4) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; unsigned char b3 = bytePtr[3]; bytePtr += 4; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; b3 += bytePtr[3]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr[3] = b3; bytePtr += 4; } } else { for (int col = 1; col < cols; ++col) { for (int chan = 0; chan < channels; ++chan) { bytePtr[chan + channels] += bytePtr[chan]; } bytePtr += channels; } } } static void DecodeFPDelta(unsigned char *input, unsigned char *output, int cols, int channels, int bytesPerSample) { DecodeDeltaBytes(input, cols * bytesPerSample, channels); int32_t rowIncrement = cols * channels; if (bytesPerSample == 2) { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; #else const unsigned char *input1 = input; const unsigned char *input0 = input + rowIncrement; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output += 2; } } else if (bytesPerSample == 3) { const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output += 3; } } else { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; const unsigned char *input3 = input + rowIncrement * 3; #else const unsigned char *input3 = input; const unsigned char *input2 = input + rowIncrement; const unsigned char *input1 = input + rowIncrement * 2; const unsigned char *input0 = input + rowIncrement * 3; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output[3] = input3[col]; output += 4; } } } static float expandFloats(unsigned char *dst, int tileWidth, int bytesps) { float max = 0.f; if (bytesps == 2) { uint16_t *dst16 = (ushort *)dst; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index) { dst32[index] = __DNG_HalfToFloat(dst16[index]); max = MAX(max, f32[index]); } } else if (bytesps == 3) { uint8_t *dst8 = ((unsigned char *)dst) + (tileWidth - 1) * 3; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index, dst8 -= 3) { dst32[index] = __DNG_FP24ToFloat(dst8); max = MAX(max, f32[index]); } } else if (bytesps == 4) { float *f32 = (float *)dst; for (int index = 0; index < tileWidth; index++) max = MAX(max, f32[index]); } return max; } void LibRaw::deflate_dng_load_raw() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) { throw LIBRAW_EXCEPTION_DECODE_RAW; } float *float_raw_image = 0; float max = 0.f; if (ifd->samples != 1 && ifd->samples != 3 && ifd->samples != 4) throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported if (libraw_internal_data.unpacker_data.tiff_samples != ifd->samples) throw LIBRAW_EXCEPTION_DECODE_RAW; // Wrong IFD size_t tilesH = (imgdata.sizes.raw_width + libraw_internal_data.unpacker_data.tile_width - 1) / libraw_internal_data.unpacker_data.tile_width; size_t tilesV = (imgdata.sizes.raw_height + libraw_internal_data.unpacker_data.tile_length - 1) / libraw_internal_data.unpacker_data.tile_length; size_t tileCnt = tilesH * tilesV; if (ifd->sample_format == 3) { // Floating point data float_raw_image = (float *)calloc(tileCnt * libraw_internal_data.unpacker_data.tile_length * libraw_internal_data.unpacker_data.tile_width * ifd->samples, sizeof(float)); // imgdata.color.maximum = 65535; // imgdata.color.black = 0; // memset(imgdata.color.cblack,0,sizeof(imgdata.color.cblack)); } else throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported int xFactor; switch (ifd->predictor) { case 3: default: xFactor = 1; break; case 34894: xFactor = 2; break; case 34895: xFactor = 4; break; } if (libraw_internal_data.unpacker_data.tile_length < INT_MAX) { if (tileCnt < 1 || tileCnt > 1000000) throw LIBRAW_EXCEPTION_DECODE_RAW; size_t *tOffsets = (size_t *)malloc(tileCnt * sizeof(size_t)); for (int t = 0; t < tileCnt; ++t) tOffsets[t] = get4(); size_t *tBytes = (size_t *)malloc(tileCnt * sizeof(size_t)); unsigned long maxBytesInTile = 0; if (tileCnt == 1) tBytes[0] = maxBytesInTile = ifd->bytes; else { libraw_internal_data.internal_data.input->seek(ifd->bytes, SEEK_SET); for (size_t t = 0; t < tileCnt; ++t) { tBytes[t] = get4(); maxBytesInTile = MAX(maxBytesInTile, tBytes[t]); } } unsigned tilePixels = libraw_internal_data.unpacker_data.tile_width * libraw_internal_data.unpacker_data.tile_length; unsigned pixelSize = sizeof(float) * ifd->samples; unsigned tileBytes = tilePixels * pixelSize; unsigned tileRowBytes = libraw_internal_data.unpacker_data.tile_width * pixelSize; unsigned char *cBuffer = (unsigned char *)malloc(maxBytesInTile); unsigned char *uBuffer = (unsigned char *)malloc(tileBytes + tileRowBytes); // extra row for decoding for (size_t y = 0, t = 0; y < imgdata.sizes.raw_height; y += libraw_internal_data.unpacker_data.tile_length) { for (size_t x = 0; x < imgdata.sizes.raw_width; x += libraw_internal_data.unpacker_data.tile_width, ++t) { libraw_internal_data.internal_data.input->seek(tOffsets[t], SEEK_SET); libraw_internal_data.internal_data.input->read(cBuffer, 1, tBytes[t]); unsigned long dstLen = tileBytes; int err = uncompress(uBuffer + tileRowBytes, &dstLen, cBuffer, tBytes[t]); if (err != Z_OK) { free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); throw LIBRAW_EXCEPTION_DECODE_RAW; return; } else { int bytesps = ifd->bps >> 3; size_t rowsInTile = y + libraw_internal_data.unpacker_data.tile_length > imgdata.sizes.raw_height ? imgdata.sizes.raw_height - y : libraw_internal_data.unpacker_data.tile_length; size_t colsInTile = x + libraw_internal_data.unpacker_data.tile_width > imgdata.sizes.raw_width ? imgdata.sizes.raw_width - x : libraw_internal_data.unpacker_data.tile_width; for (size_t row = 0; row < rowsInTile; ++row) // do not process full tile if not needed { unsigned char *dst = uBuffer + row * libraw_internal_data.unpacker_data.tile_width * bytesps * ifd->samples; unsigned char *src = dst + tileRowBytes; DecodeFPDelta(src, dst, libraw_internal_data.unpacker_data.tile_width / xFactor, ifd->samples * xFactor, bytesps); float lmax = expandFloats(dst, libraw_internal_data.unpacker_data.tile_width * ifd->samples, bytesps); max = MAX(max, lmax); unsigned char *dst2 = (unsigned char *)&float_raw_image[((y + row) * imgdata.sizes.raw_width + x) * ifd->samples]; memmove(dst2, dst, colsInTile * ifd->samples * sizeof(float)); } } } } free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); } imgdata.color.fmaximum = max; // Set fields according to data format imgdata.rawdata.raw_alloc = float_raw_image; if (ifd->samples == 1) { imgdata.rawdata.float_image = float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 4; } else if (ifd->samples == 3) { imgdata.rawdata.float3_image = (float(*)[3])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 12; } else if (ifd->samples == 4) { imgdata.rawdata.float4_image = (float(*)[4])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 16; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT) convertFloatToInt(); // with default settings } #else void LibRaw::deflate_dng_load_raw() { throw LIBRAW_EXCEPTION_DECODE_RAW; } #endif int LibRaw::is_floating_point() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) return 0; return ifd->sample_format == 3; } int LibRaw::have_fpdata() { return imgdata.rawdata.float_image || imgdata.rawdata.float3_image || imgdata.rawdata.float4_image; } void LibRaw::convertFloatToInt(float dmin /* =4096.f */, float dmax /* =32767.f */, float dtarget /*= 16383.f */) { int samples = 0; float *data = 0; if (imgdata.rawdata.float_image) { samples = 1; data = imgdata.rawdata.float_image; } else if (imgdata.rawdata.float3_image) { samples = 3; data = (float *)imgdata.rawdata.float3_image; } else if (imgdata.rawdata.float4_image) { samples = 4; data = (float *)imgdata.rawdata.float4_image; } else return; ushort *raw_alloc = (ushort *)malloc(imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples * sizeof(ushort)); float tmax = MAX(imgdata.color.maximum, 1); float datamax = imgdata.color.fmaximum; tmax = MAX(tmax, datamax); tmax = MAX(tmax, 1.f); float multip = 1.f; if (tmax < dmin || tmax > dmax) { imgdata.rawdata.color.fnorm = imgdata.color.fnorm = multip = dtarget / tmax; imgdata.rawdata.color.maximum = imgdata.color.maximum = dtarget; imgdata.rawdata.color.black = imgdata.color.black = (float)imgdata.color.black * multip; for (int i = 0; i < sizeof(imgdata.color.cblack) / sizeof(imgdata.color.cblack[0]); i++) if (i != 4 && i != 5) imgdata.rawdata.color.cblack[i] = imgdata.color.cblack[i] = (float)imgdata.color.cblack[i] * multip; } else imgdata.rawdata.color.fnorm = imgdata.color.fnorm = 0.f; for (size_t i = 0; i < imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples; ++i) { float val = MAX(data[i], 0.f); raw_alloc[i] = (ushort)(val * multip); } if (samples == 1) { imgdata.rawdata.raw_alloc = imgdata.rawdata.raw_image = raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 2; } else if (samples == 3) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color3_image = (ushort(*)[3])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; } else if (samples == 4) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = (ushort(*)[4])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; } free(data); // remove old allocation imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; imgdata.rawdata.float4_image = 0; } void LibRaw::sony_arq_load_raw() { int row, col; read_shorts(imgdata.rawdata.raw_image, imgdata.sizes.raw_width * imgdata.sizes.raw_height * 4); for (row = 0; row < imgdata.sizes.raw_height; row++) { unsigned short(*rowp)[4] = (unsigned short(*)[4]) & imgdata.rawdata.raw_image[row * imgdata.sizes.raw_width * 4]; for (col = 0; col < imgdata.sizes.raw_width; col++) { unsigned short g2 = rowp[col][2]; rowp[col][2] = rowp[col][3]; rowp[col][3] = g2; if (((unsigned)(row - imgdata.sizes.top_margin) < imgdata.sizes.height) && ((unsigned)(col - imgdata.sizes.left_margin) < imgdata.sizes.width) && (MAX(MAX(rowp[col][0], rowp[col][1]), MAX(rowp[col][2], rowp[col][3])) > imgdata.color.maximum)) derror(); } } } void LibRaw::pentax_4shot_load_raw() { ushort *plane = (ushort *)malloc(imgdata.sizes.raw_width * imgdata.sizes.raw_height * sizeof(ushort)); int alloc_sz = imgdata.sizes.raw_width * (imgdata.sizes.raw_height + 16) * 4 * sizeof(ushort); ushort(*result)[4] = (ushort(*)[4])malloc(alloc_sz); struct movement_t { int row, col; } _move[4] = { {1, 1}, {0, 1}, {0, 0}, {1, 0}, }; int tidx = 0; for (int i = 0; i < 4; i++) { int move_row, move_col; if (imgdata.params.p4shot_order[i] >= '0' && imgdata.params.p4shot_order[i] <= '3') { move_row = (imgdata.params.p4shot_order[i] - '0' & 2) ? 1 : 0; move_col = (imgdata.params.p4shot_order[i] - '0' & 1) ? 1 : 0; } else { move_row = _move[i].row; move_col = _move[i].col; } for (; tidx < 16; tidx++) if (tiff_ifd[tidx].t_width == imgdata.sizes.raw_width && tiff_ifd[tidx].t_height == imgdata.sizes.raw_height && tiff_ifd[tidx].bps > 8 && tiff_ifd[tidx].samples == 1) break; if (tidx >= 16) break; imgdata.rawdata.raw_image = plane; ID.input->seek(tiff_ifd[tidx].offset, SEEK_SET); imgdata.idata.filters = 0xb4b4b4b4; libraw_internal_data.unpacker_data.data_offset = tiff_ifd[tidx].offset; (this->*pentax_component_load_raw)(); for (int row = 0; row < imgdata.sizes.raw_height - move_row; row++) { int colors[2]; for (int c = 0; c < 2; c++) colors[c] = COLOR(row, c); ushort *srcrow = &plane[imgdata.sizes.raw_width * row]; ushort(*dstrow)[4] = &result[(imgdata.sizes.raw_width) * (row + move_row) + move_col]; for (int col = 0; col < imgdata.sizes.raw_width - move_col; col++) dstrow[col][colors[col % 2]] = srcrow[col]; } tidx++; } // assign things back: imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; imgdata.idata.filters = 0; imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = result; free(plane); imgdata.rawdata.raw_image = 0; } void LibRaw::hasselblad_full_load_raw() { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) { read_shorts(&imgdata.image[row * S.width + col][2], 1); // B read_shorts(&imgdata.image[row * S.width + col][1], 1); // G read_shorts(&imgdata.image[row * S.width + col][0], 1); // R } } static inline void unpack7bytesto4x16(unsigned char *src, unsigned short *dest) { dest[0] = (src[0] << 6) | (src[1] >> 2); dest[1] = ((src[1] & 0x3) << 12) | (src[2] << 4) | (src[3] >> 4); dest[2] = (src[3] & 0xf) << 10 | (src[4] << 2) | (src[5] >> 6); dest[3] = ((src[5] & 0x3f) << 8) | src[6]; } static inline void unpack28bytesto16x16ns(unsigned char *src, unsigned short *dest) { dest[0] = (src[3] << 6) | (src[2] >> 2); dest[1] = ((src[2] & 0x3) << 12) | (src[1] << 4) | (src[0] >> 4); dest[2] = (src[0] & 0xf) << 10 | (src[7] << 2) | (src[6] >> 6); dest[3] = ((src[6] & 0x3f) << 8) | src[5]; dest[4] = (src[4] << 6) | (src[11] >> 2); dest[5] = ((src[11] & 0x3) << 12) | (src[10] << 4) | (src[9] >> 4); dest[6] = (src[9] & 0xf) << 10 | (src[8] << 2) | (src[15] >> 6); dest[7] = ((src[15] & 0x3f) << 8) | src[14]; dest[8] = (src[13] << 6) | (src[12] >> 2); dest[9] = ((src[12] & 0x3) << 12) | (src[19] << 4) | (src[18] >> 4); dest[10] = (src[18] & 0xf) << 10 | (src[17] << 2) | (src[16] >> 6); dest[11] = ((src[16] & 0x3f) << 8) | src[23]; dest[12] = (src[22] << 6) | (src[21] >> 2); dest[13] = ((src[21] & 0x3) << 12) | (src[20] << 4) | (src[27] >> 4); dest[14] = (src[27] & 0xf) << 10 | (src[26] << 2) | (src[25] >> 6); dest[15] = ((src[25] & 0x3f) << 8) | src[24]; } #define swab32(x) \ ((unsigned int)((((unsigned int)(x) & (unsigned int)0x000000ffUL) << 24) | \ (((unsigned int)(x) & (unsigned int)0x0000ff00UL) << 8) | \ (((unsigned int)(x) & (unsigned int)0x00ff0000UL) >> 8) | \ (((unsigned int)(x) & (unsigned int)0xff000000UL) >> 24))) static inline void swab32arr(unsigned *arr, unsigned len) { for (unsigned i = 0; i < len; i++) arr[i] = swab32(arr[i]); } #undef swab32 void LibRaw::fuji_14bit_load_raw() { const unsigned linelen = S.raw_width * 7 / 4; const unsigned pitch = S.raw_pitch ? S.raw_pitch / 2 : S.raw_width; unsigned char *buf = (unsigned char *)malloc(linelen); merror(buf, "fuji_14bit_load_raw()"); for (int row = 0; row < S.raw_height; row++) { unsigned bytesread = libraw_internal_data.internal_data.input->read(buf, 1, linelen); unsigned short *dest = &imgdata.rawdata.raw_image[pitch * row]; if (bytesread % 28) { swab32arr((unsigned *)buf, bytesread / 4); for (int sp = 0, dp = 0; dp < pitch - 3 && sp < linelen - 6 && sp < bytesread - 6; sp += 7, dp += 4) unpack7bytesto4x16(buf + sp, dest + dp); } else for (int sp = 0, dp = 0; dp < pitch - 15 && sp < linelen - 27 && sp < bytesread - 27; sp += 28, dp += 16) unpack28bytesto16x16ns(buf + sp, dest + dp); } free(buf); } void LibRaw::nikon_load_striped_packed_raw() { int vbits = 0, bwide, rbits, bite, row, col, val, i; UINT64 bitbuf = 0; unsigned load_flags = 24; // libraw_internal_data.unpacker_data.load_flags; unsigned tiff_bps = libraw_internal_data.unpacker_data.tiff_bps; int tiff_compress = libraw_internal_data.unpacker_data.tiff_compress; struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) throw LIBRAW_EXCEPTION_DECODE_RAW; if (!ifd->rows_per_strip || !ifd->strip_offsets_count) return; // not unpacked int stripcnt = 0; bwide = S.raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - S.raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); for (row = 0; row < S.raw_height; row++) { checkCancel(); if (!(row % ifd->rows_per_strip)) { if (stripcnt >= ifd->strip_offsets_count) return; // run out of data libraw_internal_data.internal_data.input->seek(ifd->strip_offsets[stripcnt], SEEK_SET); stripcnt++; } for (col = 0; col < S.raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(libraw_internal_data.internal_data.input->get_char() << i); } imgdata.rawdata.raw_image[(row)*S.raw_width + (col)] = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); } vbits -= rbits; } } struct foveon_data_t { const char *make; const char *model; const int raw_width, raw_height; const int white; const int left_margin, top_margin; const int width, height; } foveon_data[] = { {"Sigma", "SD9", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD9", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD10", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD10", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD14", 2688, 1792, 14000, 18, 12, 2651, 1767}, {"Sigma", "SD14", 2688, 896, 14000, 18, 6, 2651, 883}, // 2/3 {"Sigma", "SD14", 1344, 896, 14000, 9, 6, 1326, 883}, // 1/2 {"Sigma", "SD15", 2688, 1792, 2900, 18, 12, 2651, 1767}, {"Sigma", "SD15", 2688, 896, 2900, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "SD15", 1344, 896, 2900, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1", 2688, 1792, 2100, 18, 12, 2651, 1767}, {"Sigma", "DP1", 2688, 896, 2100, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "DP1", 1344, 896, 2100, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1S", 2688, 1792, 2200, 18, 12, 2651, 1767}, {"Sigma", "DP1S", 2688, 896, 2200, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1S", 1344, 896, 2200, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP1X", 2688, 1792, 3560, 18, 12, 2651, 1767}, {"Sigma", "DP1X", 2688, 896, 3560, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1X", 1344, 896, 3560, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2", 2688, 1792, 2326, 13, 16, 2651, 1767}, {"Sigma", "DP2", 2688, 896, 2326, 13, 8, 2651, 883}, // 2/3 ?? {"Sigma", "DP2", 1344, 896, 2326, 7, 8, 1325, 883}, // 1/2 ?? {"Sigma", "DP2S", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2S", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2S", 1344, 896, 2300, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2X", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2X", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2X", 1344, 896, 2300, 9, 6, 1325, 883}, // 1/2 {"Sigma", "SD1", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "SD1 Merrill", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1 Merrill", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1 Merrill", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP1 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP2 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP2 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP2 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP3 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP3 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP3 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Polaroid", "x530", 1440, 1088, 2700, 10, 13, 1419, 1059}, // dp2 Q {"Sigma", "dp3 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp3 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp2 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp2 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp1 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp1 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp0 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp0 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size // Sigma sd Quattro {"Sigma", "sd Quattro", 5888, 3776, 16383, 204, 76, 5446, 3624}, // full size {"Sigma", "sd Quattro", 2944, 1888, 16383, 102, 38, 2723, 1812}, // half size // Sd Quattro H {"Sigma", "sd Quattro H", 6656, 4480, 16383, 224, 160, 6208, 4160}, // full size {"Sigma", "sd Quattro H", 3328, 2240, 16383, 112, 80, 3104, 2080}, // half size {"Sigma", "sd Quattro H", 5504, 3680, 16383, 0, 4, 5496, 3668}, // full size {"Sigma", "sd Quattro H", 2752, 1840, 16383, 0, 2, 2748, 1834}, // half size }; const int foveon_count = sizeof(foveon_data) / sizeof(foveon_data[0]); int LibRaw::open_datastream(LibRaw_abstract_datastream *stream) { if (!stream) return ENOENT; if (!stream->valid()) return LIBRAW_IO_ERROR; recycle(); if(callbacks.pre_identify_cb) { int r = (callbacks.pre_identify_cb)(this); if(r == 1) goto final; } try { ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); identify(); if(callbacks.post_identify_cb) (callbacks.post_identify_cb)(this); #if 0 if(!strcasecmp(imgdata.idata.make, "Sony") && imgdata.color.maximum > 0 && imgdata.color.linear_max[0] > imgdata.color.maximum*3 && imgdata.color.linear_max[0] <= imgdata.color.maximum*4) for(int c = 0; c<4; c++) imgdata.color.linear_max[c] /= 4; #endif if (!strcasecmp(imgdata.idata.make, "Canon") && (load_raw == &LibRaw::canon_sraw_load_raw) && imgdata.sizes.raw_width > 0) { float ratio = float(imgdata.sizes.raw_height) / float(imgdata.sizes.raw_width); if ((ratio < 0.57 || ratio > 0.75) && imgdata.makernotes.canon.SensorHeight > 1 && imgdata.makernotes.canon.SensorWidth > 1) { imgdata.sizes.raw_width = imgdata.makernotes.canon.SensorWidth; imgdata.sizes.left_margin = imgdata.makernotes.canon.SensorLeftBorder; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.makernotes.canon.SensorRightBorder - imgdata.makernotes.canon.SensorLeftBorder + 1; imgdata.sizes.raw_height = imgdata.makernotes.canon.SensorHeight; imgdata.sizes.top_margin = imgdata.makernotes.canon.SensorTopBorder; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.makernotes.canon.SensorBottomBorder - imgdata.makernotes.canon.SensorTopBorder + 1; libraw_internal_data.unpacker_data.load_flags |= 256; // reset width/height in canon_sraw_load_raw() imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } else if (imgdata.sizes.raw_width == 4032 && imgdata.sizes.raw_height == 3402 && !strcasecmp(imgdata.idata.model, "EOS 80D")) // 80D hardcoded { imgdata.sizes.raw_width = 4536; imgdata.sizes.left_margin = 28; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.sizes.raw_width - imgdata.sizes.left_margin; imgdata.sizes.raw_height = 3024; imgdata.sizes.top_margin = 8; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.sizes.raw_height - imgdata.sizes.top_margin; libraw_internal_data.unpacker_data.load_flags |= 256; imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } } // XTrans Compressed? if (!imgdata.idata.dng_version && !strcasecmp(imgdata.idata.make, "Fujifilm") && (load_raw == &LibRaw::unpacked_load_raw)) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 2 != libraw_internal_data.unpacker_data.data_size) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 7 / 4 == libraw_internal_data.unpacker_data.data_size) load_raw = &LibRaw::fuji_14bit_load_raw; else parse_fuji_compressed_header(); } if (imgdata.idata.filters == 9) { // Adjust top/left margins for X-Trans int newtm = imgdata.sizes.top_margin % 6 ? (imgdata.sizes.top_margin / 6 + 1) * 6 : imgdata.sizes.top_margin; int newlm = imgdata.sizes.left_margin % 6 ? (imgdata.sizes.left_margin / 6 + 1) * 6 : imgdata.sizes.left_margin; if (newtm != imgdata.sizes.top_margin || newlm != imgdata.sizes.left_margin) { imgdata.sizes.height -= (newtm - imgdata.sizes.top_margin); imgdata.sizes.top_margin = newtm; imgdata.sizes.width -= (newlm - imgdata.sizes.left_margin); imgdata.sizes.left_margin = newlm; for (int c1 = 0; c1 < 6; c1++) for (int c2 = 0; c2 < 6; c2++) imgdata.idata.xtrans[c1][c2] = imgdata.idata.xtrans_abs[c1][c2]; } } } // Fix DNG white balance if needed if (imgdata.idata.dng_version && (imgdata.idata.filters == 0) && imgdata.idata.colors > 1 && imgdata.idata.colors < 5) { float delta[4] = {0.f, 0.f, 0.f, 0.f}; int black[4]; for (int c = 0; c < 4; c++) black[c] = imgdata.color.dng_levels.dng_black + imgdata.color.dng_levels.dng_cblack[c]; for (int c = 0; c < imgdata.idata.colors; c++) delta[c] = imgdata.color.dng_levels.dng_whitelevel[c] - black[c]; float mindelta = delta[0], maxdelta = delta[0]; for (int c = 1; c < imgdata.idata.colors; c++) { if (mindelta > delta[c]) mindelta = delta[c]; if (maxdelta < delta[c]) maxdelta = delta[c]; } if (mindelta > 1 && maxdelta < (mindelta * 20)) // safety { for (int c = 0; c < imgdata.idata.colors; c++) { imgdata.color.cam_mul[c] /= (delta[c] / maxdelta); imgdata.color.pre_mul[c] /= (delta[c] / maxdelta); } imgdata.color.maximum = imgdata.color.cblack[0] + maxdelta; } } if (imgdata.idata.dng_version && ((!strcasecmp(imgdata.idata.make, "Leica") && !strcasecmp(imgdata.idata.model, "D-LUX (Typ 109)")) || (!strcasecmp(imgdata.idata.make, "Panasonic") && !strcasecmp(imgdata.idata.model, "LX100")))) imgdata.sizes.width = 4288; if (!strncasecmp(imgdata.idata.make, "Sony", 4) && imgdata.idata.dng_version && !(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)) { if (S.raw_width == 3984) S.width = 3925; else if (S.raw_width == 4288) S.width = S.raw_width - 32; else if (S.raw_width == 4928 && S.height < 3280) S.width = S.raw_width - 8; else if (S.raw_width == 5504) S.width = S.raw_width - (S.height > 3664 ? 8 : 32); } if (!strcasecmp(imgdata.idata.make, "Pentax") && /*!strcasecmp(imgdata.idata.model,"K-3 II") &&*/ imgdata.idata.raw_count == 4 && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_PENTAX_PS_ALLFRAMES)) { imgdata.idata.raw_count = 1; imgdata.idata.filters = 0; imgdata.idata.colors = 4; IO.mix_green = 1; pentax_component_load_raw = load_raw; load_raw = &LibRaw::pentax_4shot_load_raw; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Leaf") && !strcmp(imgdata.idata.model, "Credo 50")) { imgdata.color.pre_mul[0] = 1.f / 0.3984f; imgdata.color.pre_mul[2] = 1.f / 0.7666f; imgdata.color.pre_mul[1] = imgdata.color.pre_mul[3] = 1.0; } // S3Pro DNG patch if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S3Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S5Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && (!strncmp(imgdata.idata.model, "S20Pro", 6) || !strncmp(imgdata.idata.model, "F700", 4))) { imgdata.sizes.raw_width /= 2; load_raw = &LibRaw::unpacked_load_raw_fuji_f700s20; } if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Nikon") && !libraw_internal_data.unpacker_data.load_flags && (!strncasecmp(imgdata.idata.model, "D810", 4) || !strcasecmp(imgdata.idata.model, "D4S")) && libraw_internal_data.unpacker_data.data_size * 2 == imgdata.sizes.raw_height * imgdata.sizes.raw_width * 3) { libraw_internal_data.unpacker_data.load_flags = 80; } // Adjust BL for Sony A900/A850 if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Sony")) // 12 bit sony, but metadata may be for 14-bit range { if (C.maximum > 4095) C.maximum = 4095; if (C.black > 256 || C.cblack[0] > 256) { C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } } if (load_raw == &LibRaw::nikon_yuv_load_raw) // Is it Nikon sRAW? { load_raw = &LibRaw::nikon_load_sraw; C.black = 0; memset(C.cblack, 0, sizeof(C.cblack)); imgdata.idata.filters = 0; libraw_internal_data.unpacker_data.tiff_samples = 3; imgdata.idata.colors = 3; double beta_1 = -5.79342238397656E-02; double beta_2 = 3.28163551282665; double beta_3 = -8.43136004842678; double beta_4 = 1.03533181861023E+01; for (int i = 0; i <= 3072; i++) { double x = (double)i / 3072.; double y = (1. - exp(-beta_1 * x - beta_2 * x * x - beta_3 * x * x * x - beta_4 * x * x * x * x)); if (y < 0.) y = 0.; imgdata.color.curve[i] = (y * 16383.); } for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) imgdata.color.rgb_cam[i][j] = float(i == j); } // Adjust BL for Nikon 12bit if ((load_raw == &LibRaw::nikon_load_raw || load_raw == &LibRaw::packed_load_raw) && !strcasecmp(imgdata.idata.make, "Nikon") && strncmp(imgdata.idata.model, "COOLPIX", 7) // && strncmp(imgdata.idata.model,"1 ",2) && libraw_internal_data.unpacker_data.tiff_bps == 12) { C.maximum = 4095; C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } // Adjust Highlight Linearity limit if (C.linear_max[0] < 0) { if (imgdata.idata.dng_version) { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c + 6]; } else { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c]; } } if (!strcasecmp(imgdata.idata.make, "Nikon") && (!C.linear_max[0]) && (C.maximum > 1024) && (load_raw != &LibRaw::nikon_load_sraw)) { C.linear_max[0] = C.linear_max[1] = C.linear_max[2] = C.linear_max[3] = (long)((float)(C.maximum) / 1.07f); } // Correct WB for Samsung GX20 if (!strcasecmp(imgdata.idata.make, "Samsung") && !strcasecmp(imgdata.idata.model, "GX20")) { C.WB_Coeffs[LIBRAW_WBI_Daylight][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Daylight][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Shade][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Shade][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Cloudy][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Tungsten][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_D][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_D][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_N][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_N][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_W][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_W][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Flash][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Flash][2]) * 2.56f); for (int c = 0; c < 64; c++) { if (imgdata.color.WBCT_Coeffs[c][0] > 0.0f) { imgdata.color.WBCT_Coeffs[c][3] *= 2.56f; } } } // Adjust BL for Panasonic if (load_raw == &LibRaw::panasonic_load_raw && (!strcasecmp(imgdata.idata.make, "Panasonic") || !strcasecmp(imgdata.idata.make, "Leica") || !strcasecmp(imgdata.idata.make, "YUNEEC")) && ID.pana_black[0] && ID.pana_black[1] && ID.pana_black[2]) { if(libraw_internal_data.unpacker_data.pana_encoding == 5) P1.raw_count = 0; // Disable for new decoder C.black = 0; int add = libraw_internal_data.unpacker_data.pana_encoding == 4?15:0; C.cblack[0] = ID.pana_black[0]+add; C.cblack[1] = C.cblack[3] = ID.pana_black[1]+add; C.cblack[2] = ID.pana_black[2]+add; int i = C.cblack[3]; for (int c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (int c = 0; c < 4; c++) C.cblack[c] -= i; C.black = i; } // Adjust sizes for X3F processing if (load_raw == &LibRaw::x3f_load_raw) { for (int i = 0; i < foveon_count; i++) if (!strcasecmp(imgdata.idata.make, foveon_data[i].make) && !strcasecmp(imgdata.idata.model, foveon_data[i].model) && imgdata.sizes.raw_width == foveon_data[i].raw_width && imgdata.sizes.raw_height == foveon_data[i].raw_height) { imgdata.sizes.top_margin = foveon_data[i].top_margin; imgdata.sizes.left_margin = foveon_data[i].left_margin; imgdata.sizes.width = imgdata.sizes.iwidth = foveon_data[i].width; imgdata.sizes.height = imgdata.sizes.iheight = foveon_data[i].height; C.maximum = foveon_data[i].white; break; } } #if 0 size_t bytes = ID.input->size()-libraw_internal_data.unpacker_data.data_offset; float bpp = float(bytes)/float(S.raw_width)/float(S.raw_height); float bpp2 = float(bytes)/float(S.width)/float(S.height); printf("RawSize: %dx%d data offset: %d data size:%d bpp: %g bpp2: %g\n",S.raw_width,S.raw_height,libraw_internal_data.unpacker_data.data_offset,bytes,bpp,bpp2); if(!strcasecmp(imgdata.idata.make,"Hasselblad") && bpp == 6.0f) { load_raw = &LibRaw::hasselblad_full_load_raw; S.width = S.raw_width; S.height = S.raw_height; P1.filters = 0; P1.colors=3; P1.raw_count=1; C.maximum=0xffff; printf("3 channel hassy found\n"); } #endif if (C.profile_length) { if (C.profile) free(C.profile); C.profile = malloc(C.profile_length); merror(C.profile, "LibRaw::open_file()"); ID.input->seek(ID.profile_offset, SEEK_SET); ID.input->read(C.profile, C.profile_length, 1); } SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } final:; if (P1.raw_count < 1) return LIBRAW_FILE_UNSUPPORTED; write_fun = &LibRaw::write_ppm_tiff; if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); if (IO.shrink && P1.filters >= 1000) { S.width &= 65534; S.height &= 65534; } S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_SIZE_ADJUST); return LIBRAW_SUCCESS; } #ifdef USE_RAWSPEED void LibRaw::fix_after_rawspeed(int bl) { if (load_raw == &LibRaw::lossy_dng_load_raw) C.maximum = 0xffff; else if (load_raw == &LibRaw::sony_load_raw) C.maximum = 0x3ff0; } #else void LibRaw::fix_after_rawspeed(int) {} #endif void LibRaw::clearCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 0); #else __sync_fetch_and_and(&_exitflag, 0); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->resumeProcessing(); } #endif } void LibRaw::setCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 1); #else __sync_fetch_and_add(&_exitflag, 1); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->cancelProcessing(); } #endif } void LibRaw::checkCancel() { #ifdef WIN32 if (InterlockedExchange(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #else if (__sync_fetch_and_and(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } int LibRaw::try_rawspeed() { #ifdef USE_RAWSPEED int ret = LIBRAW_SUCCESS; int rawspeed_ignore_errors = 0; if (imgdata.idata.dng_version && imgdata.idata.colors == 3 && !strcasecmp(imgdata.idata.software, "Adobe Photoshop Lightroom 6.1.1 (Windows)")) rawspeed_ignore_errors = 1; // RawSpeed Supported, INT64 spos = ID.input->tell(); void *_rawspeed_buffer = 0; try { // printf("Using rawspeed\n"); ID.input->seek(0, SEEK_SET); INT64 _rawspeed_buffer_sz = ID.input->size() + 32; _rawspeed_buffer = malloc(_rawspeed_buffer_sz); if (!_rawspeed_buffer) throw LIBRAW_EXCEPTION_ALLOC; ID.input->read(_rawspeed_buffer, _rawspeed_buffer_sz, 1); FileMap map((uchar8 *)_rawspeed_buffer, _rawspeed_buffer_sz); RawParser t(&map); RawDecoder *d = 0; CameraMetaDataLR *meta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); d = t.getDecoder(); if (!d) throw "Unable to find decoder"; try { d->checkSupport(meta); } catch (const RawDecoderException &e) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_UNSUPPORTED; throw e; } d->interpolateBadPixels = FALSE; d->applyStage1DngOpcodes = FALSE; _rawspeed_decoder = static_cast<void *>(d); d->decodeRaw(); d->decodeMetaData(meta); RawImage r = d->mRaw; if (r->errors.size() > 0 && !rawspeed_ignore_errors) { delete d; _rawspeed_decoder = 0; throw 1; } if (r->isCFA) { imgdata.rawdata.raw_image = (ushort *)r->getDataUncropped(0, 0); } else if (r->getCpp() == 4) { imgdata.rawdata.color4_image = (ushort(*)[4])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else if (r->getCpp() == 3) { imgdata.rawdata.color3_image = (ushort(*)[3])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else { delete d; _rawspeed_decoder = 0; ret = LIBRAW_UNSPECIFIED_ERROR; } if (_rawspeed_decoder) { // set sizes iPoint2D rsdim = r->getUncroppedDim(); S.raw_pitch = r->pitch; S.raw_width = rsdim.x; S.raw_height = rsdim.y; // C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } free(_rawspeed_buffer); _rawspeed_buffer = 0; imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROCESSED; } catch (const RawDecoderException &RDE) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } const char *p = RDE.what(); if (!strncmp(RDE.what(), "Decoder canceled", strlen("Decoder canceled"))) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; ret = LIBRAW_UNSPECIFIED_ERROR; } catch (...) { // We may get here due to cancellation flag imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } ret = LIBRAW_UNSPECIFIED_ERROR; } ID.input->seek(spos, SEEK_SET); return ret; #else return LIBRAW_NOT_IMPLEMENTED; #endif } int LibRaw::valid_for_dngsdk() { #ifndef USE_DNGSDK return 0; #else if (!imgdata.idata.dng_version) return 0; if (!imgdata.params.use_dngsdk) return 0; if (load_raw == &LibRaw::lossy_dng_load_raw) return 0; if (is_floating_point() && (imgdata.params.use_dngsdk & LIBRAW_DNG_FLOAT)) return 1; if (!imgdata.idata.filters && (imgdata.params.use_dngsdk & LIBRAW_DNG_LINEAR)) return 1; if (libraw_internal_data.unpacker_data.tiff_bps == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_8BIT)) return 1; if (libraw_internal_data.unpacker_data.tiff_compress == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_DEFLATE)) return 1; if (libraw_internal_data.unpacker_data.tiff_samples == 2) return 0; // Always deny 2-samples (old fuji superccd) if (imgdata.idata.filters == 9 && (imgdata.params.use_dngsdk & LIBRAW_DNG_XTRANS)) return 1; if (is_fuji_rotated()) return 0; // refuse if (imgdata.params.use_dngsdk & LIBRAW_DNG_OTHER) return 1; return 0; #endif } int LibRaw::is_curve_linear() { for (int i = 0; i < 0x10000; i++) if (imgdata.color.curve[i] != i) return 0; return 1; } int LibRaw::try_dngsdk() { #ifdef USE_DNGSDK if (!dnghost) return LIBRAW_UNSPECIFIED_ERROR; dng_host *host = static_cast<dng_host *>(dnghost); try { libraw_dng_stream stream(libraw_internal_data.internal_data.input); AutoPtr<dng_negative> negative; negative.Reset(host->Make_dng_negative()); dng_info info; info.Parse(*host, stream); info.PostParse(*host); if (!info.IsValidDNG()) { return LIBRAW_DATA_ERROR; } negative->Parse(*host, stream, info); negative->PostParse(*host, stream, info); negative->ReadStage1Image(*host, stream, info); dng_simple_image *stage2 = (dng_simple_image *)negative->Stage1Image(); if (stage2->Bounds().W() != S.raw_width || stage2->Bounds().H() != S.raw_height) { return LIBRAW_DATA_ERROR; } int pplanes = stage2->Planes(); int ptype = stage2->PixelType(); dng_pixel_buffer buffer; stage2->GetPixelBuffer(buffer); int pixels = stage2->Bounds().H() * stage2->Bounds().W() * pplanes; if (ptype == ttByte) imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ttShort)); else imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ptype)); if (ptype == ttShort && !is_curve_linear()) { ushort *src = (ushort *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } else if (ptype == ttByte) { unsigned char *src = (unsigned char *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; if (is_curve_linear()) { for (int i = 0; i < pixels; i++) dst[i] = src[i]; } else { for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; } S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ttShort); } else { memmove(imgdata.rawdata.raw_alloc, buffer.fData, pixels * TagTypeSize(ptype)); S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } switch (ptype) { case ttFloat: if (pplanes == 1) imgdata.rawdata.float_image = (float *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.float3_image = (float(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.float4_image = (float(*)[4])imgdata.rawdata.raw_alloc; break; case ttByte: case ttShort: if (pplanes == 1) imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; break; default: /* do nothing */ break; } } catch (...) { return LIBRAW_UNSPECIFIED_ERROR; } return imgdata.rawdata.raw_alloc ? LIBRAW_SUCCESS : LIBRAW_UNSPECIFIED_ERROR; #else return LIBRAW_UNSPECIFIED_ERROR; #endif } void LibRaw::set_dng_host(void *p) { #ifdef USE_DNGSDK dnghost = p; #endif } int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 0, 2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if (!load_raw) return LIBRAW_UNSPECIFIED_ERROR; // already allocated ? if (imgdata.image) { free(imgdata.image); imgdata.image = 0; } if (imgdata.rawdata.raw_alloc) { free(imgdata.rawdata.raw_alloc); imgdata.rawdata.raw_alloc = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *)malloc(libraw_internal_data.unpacker_data.meta_length); merror(libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if (!IO.fuji_width) { // adjust non-Fuji allocation if (rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if (rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } if (rwidth > 65535 || rheight > 65535) // No way to make image larger than 64k pix throw LIBRAW_EXCEPTION_IO_CORRUPT; imgdata.rawdata.raw_image = 0; imgdata.rawdata.color4_image = 0; imgdata.rawdata.color3_image = 0; imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; #ifdef USE_DNGSDK if (imgdata.idata.dng_version && dnghost && imgdata.idata.raw_count == 1 && valid_for_dngsdk() && load_raw != &LibRaw::pentax_4shot_load_raw) { int rr = try_dngsdk(); } #endif #ifdef USE_RAWSPEED if (!raw_was_read()) { int rawspeed_enabled = 1; if (imgdata.idata.dng_version && libraw_internal_data.unpacker_data.tiff_samples == 2) rawspeed_enabled = 0; if (imgdata.idata.raw_count > 1) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.software, "Magic", 5)) rawspeed_enabled = 0; // Disable rawspeed for double-sized Oly files if (!strncasecmp(imgdata.idata.make, "Olympus", 7) && ((imgdata.sizes.raw_width > 6000) || !strncasecmp(imgdata.idata.model, "SH-2", 4) || !strncasecmp(imgdata.idata.model, "SH-3", 4) || !strncasecmp(imgdata.idata.model, "TG-4", 4) || !strncasecmp(imgdata.idata.model, "TG-5", 4))) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.make, "Canon", 5) && !strcasecmp(imgdata.idata.model, "EOS 6D Mark II")) rawspeed_enabled = 0; if (imgdata.idata.dng_version && imgdata.idata.filters == 0 && libraw_internal_data.unpacker_data.tiff_bps == 8) // Disable for 8 bit rawspeed_enabled = 0; if (load_raw == &LibRaw::packed_load_raw && !strncasecmp(imgdata.idata.make, "Nikon", 5) && (!strncasecmp(imgdata.idata.model, "E", 1) || !strncasecmp(imgdata.idata.model, "COOLPIX B", 9))) rawspeed_enabled = 0; // RawSpeed Supported, if (O.use_rawspeed && rawspeed_enabled && !(is_sraw() && (O.raw_processing_options & (LIBRAW_PROCESSING_SRAW_NO_RGB | LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE))) && (decoder_info.decoder_flags & LIBRAW_DECODER_TRYRAWSPEED) && _rawspeed_camerameta) { int rr = try_rawspeed(); } } #endif if (!raw_was_read()) // RawSpeed failed or not run { // Not allocated on RawSpeed call, try call LibRaow int zero_rawimage = 0; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder and DNG float // Do nothing! Decoder will allocate data internally } if (decoder_info.decoder_flags & LIBRAW_DECODER_3CHANNEL) { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3 > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3); imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 6; } else if (imgdata.idata.filters || P1.colors == 1) // Bayer image or single color -> decode to raw_image { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 2; // Bayer case, not set before } else // NO LEGACY FLAG if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) { S.raw_pitch = S.raw_width * 8; } else { S.iwidth = S.width; S.iheight = S.height; IO.shrink = 0; if (!S.raw_pitch) S.raw_pitch = (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS) ? S.raw_width * 8 : S.width * 8; } // sRAW and old Foveon decoders only, so extra buffer size is just 1/4 // allocate image as temporary buffer, size if (INT64(MAX(S.width, S.raw_width)) * INT64(MAX(S.height, S.raw_height)) * sizeof(*imgdata.image) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = 0; imgdata.image = (ushort(*)[4])calloc( unsigned(MAX(S.width, S.raw_width)) * unsigned(MAX(S.height, S.raw_height)), sizeof(*imgdata.image)); if (!(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL)) { imgdata.rawdata.raw_image = (ushort *)imgdata.image; zero_rawimage = 1; } } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); unsigned m_save = C.maximum; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = 65535; (this->*load_raw)(); if (zero_rawimage) imgdata.rawdata.raw_image = 0; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = m_save; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder only: do nothing } else if (!(imgdata.idata.filters || P1.colors == 1)) // legacy decoder, ownalloc handled above { // successfully decoded legacy image, attach image to raw_alloc imgdata.rawdata.raw_alloc = imgdata.image; imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; imgdata.image = 0; // Restore saved values. Note: Foveon have masked frame // Other 4-color legacy data: no borders if (!(libraw_internal_data.unpacker_data.load_flags & 256) && !(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) && !(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS)) { S.raw_width = S.width; S.left_margin = 0; S.raw_height = S.height; S.top_margin = 0; } } } if (imgdata.rawdata.raw_image) crop_masked_pixels(); // calculate black levels // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 1, 2); return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } void LibRaw::unpacked_load_raw_fuji_f700s20() { int base_offset = 0; int row_size = imgdata.sizes.raw_width * 2; // in bytes if (imgdata.idata.raw_count == 2 && imgdata.params.shot_select) { libraw_internal_data.internal_data.input->seek(-row_size, SEEK_CUR); base_offset = row_size; // in bytes } unsigned char *buffer = (unsigned char *)malloc(row_size * 2); for (int row = 0; row < imgdata.sizes.raw_height; row++) { read_shorts((ushort *)buffer, imgdata.sizes.raw_width * 2); memmove(&imgdata.rawdata.raw_image[row * imgdata.sizes.raw_pitch / 2], buffer + base_offset, row_size); } free(buffer); } void LibRaw::nikon_load_sraw() { // We're already seeked to data! unsigned char *rd = (unsigned char *)malloc(3 * (imgdata.sizes.raw_width + 2)); if (!rd) throw LIBRAW_EXCEPTION_ALLOC; try { int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); libraw_internal_data.internal_data.input->read(rd, 3, imgdata.sizes.raw_width); for (col = 0; col < imgdata.sizes.raw_width - 1; col += 2) { int bi = col * 3; ushort bits1 = (rd[bi + 1] & 0xf) << 8 | rd[bi]; // 3,0,1 ushort bits2 = rd[bi + 2] << 4 | ((rd[bi + 1] >> 4) & 0xf); // 452 ushort bits3 = ((rd[bi + 4] & 0xf) << 8) | rd[bi + 3]; // 967 ushort bits4 = rd[bi + 5] << 4 | ((rd[bi + 4] >> 4) & 0xf); // ab8 imgdata.image[row * imgdata.sizes.raw_width + col][0] = bits1; imgdata.image[row * imgdata.sizes.raw_width + col][1] = bits3; imgdata.image[row * imgdata.sizes.raw_width + col][2] = bits4; imgdata.image[row * imgdata.sizes.raw_width + col + 1][0] = bits2; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = 2048; imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = 2048; } } } catch (...) { free(rd); throw; } free(rd); C.maximum = 0xfff; // 12 bit? if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { return; // no CbCr interpolation } // Interpolate CC channels int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col += 2) { int col2 = col < imgdata.sizes.raw_width - 2 ? col + 2 : col; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][1] + imgdata.image[row * imgdata.sizes.raw_width + col2][1]) / 2); imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][2] + imgdata.image[row * imgdata.sizes.raw_width + col2][2]) / 2); } } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) return; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col++) { float Y = float(imgdata.image[row * imgdata.sizes.raw_width + col][0]) / 2549.f; float Ch2 = float(imgdata.image[row * imgdata.sizes.raw_width + col][1] - 1280) / 1536.f; float Ch3 = float(imgdata.image[row * imgdata.sizes.raw_width + col][2] - 1280) / 1536.f; if (Y > 1.f) Y = 1.f; if (Y > 0.803f) Ch2 = Ch3 = 0.5f; float r = Y + 1.40200f * (Ch3 - 0.5f); if (r < 0.f) r = 0.f; if (r > 1.f) r = 1.f; float g = Y - 0.34414f * (Ch2 - 0.5f) - 0.71414 * (Ch3 - 0.5f); if (g > 1.f) g = 1.f; if (g < 0.f) g = 0.f; float b = Y + 1.77200 * (Ch2 - 0.5f); if (b > 1.f) b = 1.f; if (b < 0.f) b = 0.f; imgdata.image[row * imgdata.sizes.raw_width + col][0] = imgdata.color.curve[int(r * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][1] = imgdata.color.curve[int(g * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][2] = imgdata.color.curve[int(b * 3072.f)]; } } C.maximum = 16383; } void LibRaw::free_image(void) { if (imgdata.image) { free(imgdata.image); imgdata.image = 0; imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; } } void LibRaw::raw2image_start() { // restore color,sizes and internal data into raw_image fields memmove(&imgdata.color, &imgdata.rawdata.color, sizeof(imgdata.color)); memmove(&imgdata.sizes, &imgdata.rawdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.idata, &imgdata.rawdata.iparams, sizeof(imgdata.idata)); memmove(&libraw_internal_data.internal_output_params, &imgdata.rawdata.ioparams, sizeof(libraw_internal_data.internal_output_params)); if (O.user_flip >= 0) S.flip = O.user_flip; switch ((S.flip + 3600) % 360) { case 270: S.flip = 5; break; case 180: S.flip = 3; break; case 90: S.flip = 6; break; } // adjust for half mode! IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; } int LibRaw::is_phaseone_compressed() { return (load_raw == &LibRaw::phase_one_load_raw_c || load_raw == &LibRaw::phase_one_load_raw); } int LibRaw::is_canon_600() { return load_raw == &LibRaw::canon_600_load_raw; } int LibRaw::raw2image(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // free and re-allocate image bitmap if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, S.iheight * S.iwidth * sizeof(*imgdata.image)); memset(imgdata.image, 0, S.iheight * S.iwidth * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { unsigned r, c; int row, col; for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][FC(r, c)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } } else { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][fcol(row, col)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.width * 8 == S.raw_pitch) memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); else { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } // hack - clear later flags! if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } void LibRaw::phase_one_allocate_tempbuffer() { // Allocate temp raw_image buffer imgdata.rawdata.raw_image = (ushort *)malloc(S.raw_pitch * S.raw_height); merror(imgdata.rawdata.raw_image, "phase_one_prepare_to_correct()"); } void LibRaw::phase_one_free_tempbuffer() { free(imgdata.rawdata.raw_image); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; } int LibRaw::phase_one_subtract_black(ushort *src, ushort *dest) { try { if (O.user_black < 0 && O.user_cblack[0] <= -1000000 && O.user_cblack[1] <= -1000000 && O.user_cblack[2] <= -1000000 && O.user_cblack[3] <= -1000000) { if (!imgdata.rawdata.ph1_cblack || !imgdata.rawdata.ph1_rblack) { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl; dest[idx] = val > 0 ? val : 0; } } } else { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl + imgdata.rawdata.ph1_cblack[row][col >= imgdata.rawdata.color.phase_one_data.split_col] + imgdata.rawdata.ph1_rblack[col][row >= imgdata.rawdata.color.phase_one_data.split_row]; dest[idx] = val > 0 ? val : 0; } } } } else // black set by user interaction { // Black level in cblack! for (int row = 0; row < S.raw_height; row++) { checkCancel(); unsigned short cblk[16]; for (int cc = 0; cc < 16; cc++) cblk[cc] = C.cblack[fcol(row, cc)]; for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; ushort val = src[idx]; ushort bl = cblk[col & 0xf]; dest[idx] = val > bl ? val - bl : 0; } } } return 0; } catch (LibRaw_exceptions err) { return LIBRAW_CANCELLED_BY_CALLBACK; } } void LibRaw::copy_fuji_uncropped(unsigned short cblack[4], unsigned short *dmaxp) { int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { unsigned r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FC(r, c); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][cc] = val; } } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } void LibRaw::copy_bayer(unsigned short cblack[4], unsigned short *dmaxp) { // Both cropped and uncropped int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.height; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < S.width; col++) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = fcol(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][cc] = val; } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } int LibRaw::raw2image_ex(int do_subtract_black) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); // Compressed P1 files with bl data! if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // process cropping int do_crop = 0; unsigned save_width = S.width; if (~O.cropbox[2] && ~O.cropbox[3]) { int crop[4], c, filt; for (int c = 0; c < 4; c++) { crop[c] = O.cropbox[c]; if (crop[c] < 0) crop[c] = 0; } if (IO.fuji_width && imgdata.idata.filters >= 1000) { crop[0] = (crop[0] / 4) * 4; crop[1] = (crop[1] / 4) * 4; if (!libraw_internal_data.unpacker_data.fuji_layout) { crop[2] *= sqrt(2.0); crop[3] /= sqrt(2.0); } crop[2] = (crop[2] / 4 + 1) * 4; crop[3] = (crop[3] / 4 + 1) * 4; } else if (imgdata.idata.filters == 1) { crop[0] = (crop[0] / 16) * 16; crop[1] = (crop[1] / 16) * 16; } else if (imgdata.idata.filters == LIBRAW_XTRANS) { crop[0] = (crop[0] / 6) * 6; crop[1] = (crop[1] / 6) * 6; } do_crop = 1; crop[2] = MIN(crop[2], (signed)S.width - crop[0]); crop[3] = MIN(crop[3], (signed)S.height - crop[1]); if (crop[2] <= 0 || crop[3] <= 0) throw LIBRAW_EXCEPTION_BAD_CROP; // adjust sizes! S.left_margin += crop[0]; S.top_margin += crop[1]; S.width = crop[2]; S.height = crop[3]; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if (!IO.fuji_width && imgdata.idata.filters && imgdata.idata.filters >= 1000) { for (filt = c = 0; c < 16; c++) filt |= FC((c >> 1) + (crop[1]), (c & 1) + (crop[0])) << c * 2; imgdata.idata.filters = filt; } } int alloc_width = S.iwidth; int alloc_height = S.iheight; if (IO.fuji_width && do_crop) { int IO_fw = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int t_alloc_width = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO_fw; int t_alloc_height = t_alloc_width - 1; alloc_height = (t_alloc_height + IO.shrink) >> IO.shrink; alloc_width = (t_alloc_width + IO.shrink) >> IO.shrink; } int alloc_sz = alloc_width * alloc_height; if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, alloc_sz * sizeof(*imgdata.image)); memset(imgdata.image, 0, alloc_sz * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(alloc_sz, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image_ex()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Adjust black levels unsigned short cblack[4] = {0, 0, 0, 0}; unsigned short dmax = 0; if (do_subtract_black) { adjust_bl(); for (int i = 0; i < 4; i++) cblack[i] = (unsigned short)C.cblack[i]; } // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { if (do_crop) { IO.fuji_width = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int IO_fwidth = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO.fuji_width; int IO_fheight = IO_fwidth - 1; int row, col; for (row = 0; row < S.height; row++) { for (col = 0; col < S.width; col++) { int r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FCF(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (dmax < val) dmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * alloc_width + ((c) >> IO.shrink)][cc] = val; } } S.height = IO_fheight; S.width = IO_fwidth; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; S.raw_height -= 2 * S.top_margin; } else { copy_fuji_uncropped(cblack, &dmax); } } // end Fuji else { copy_bayer(cblack, &dmax); } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.raw_pitch != S.width * 8) { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } else { // legacy is always 4channel and not shrinked! memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } if (do_subtract_black) { C.data_maximum = (int)dmax; C.maximum -= C.black; // ZERO(C.cblack); C.cblack[0] = C.cblack[1] = C.cblack[2] = C.cblack[3] = 0; C.black = 0; } // hack - clear later flags! imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #if 1 libraw_processed_image_t *LibRaw::dcraw_make_mem_thumb(int *errcode) { if (!T.thumb) { if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { if (errcode) *errcode = LIBRAW_NO_THUMBNAIL; } else { if (errcode) *errcode = LIBRAW_OUT_OF_ORDER_CALL; } return NULL; } if (T.tformat == LIBRAW_THUMBNAIL_BITMAP) { libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + T.tlength); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_BITMAP; ret->height = T.theight; ret->width = T.twidth; ret->colors = 3; ret->bits = 8; ret->data_size = T.tlength; memmove(ret->data, T.thumb, T.tlength); if (errcode) *errcode = 0; return ret; } else if (T.tformat == LIBRAW_THUMBNAIL_JPEG) { ushort exif[5]; int mk_exif = 0; if (strcmp(T.thumb + 6, "Exif")) mk_exif = 1; int dsize = T.tlength + mk_exif * (sizeof(exif) + sizeof(tiff_hdr)); libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + dsize); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_JPEG; ret->data_size = dsize; ret->data[0] = 0xff; ret->data[1] = 0xd8; if (mk_exif) { struct tiff_hdr th; memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); memmove(ret->data + 2, exif, sizeof(exif)); tiff_head(&th, 0); memmove(ret->data + (2 + sizeof(exif)), &th, sizeof(th)); memmove(ret->data + (2 + sizeof(exif) + sizeof(th)), T.thumb + 2, T.tlength - 2); } else { memmove(ret->data + 2, T.thumb + 2, T.tlength - 2); } if (errcode) *errcode = 0; return ret; } else { if (errcode) *errcode = LIBRAW_UNSUPPORTED_THUMBNAIL; return NULL; } } // jlb // macros for copying pixels to either BGR or RGB formats #define FORBGR for (c = P1.colors - 1; c >= 0; c--) #define FORRGB for (c = 0; c < P1.colors; c++) void LibRaw::get_mem_image_format(int *width, int *height, int *colors, int *bps) const { if (S.flip & 4) { *width = S.height; *height = S.width; } else { *width = S.width; *height = S.height; } *colors = P1.colors; *bps = O.output_bps; } int LibRaw::copy_mem_image(void *scan0, int stride, int bgr) { // the image memory pointed to by scan0 is assumed to be in the format returned by get_mem_image_format if ((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) < LIBRAW_PROGRESS_PRE_INTERPOLATE) return LIBRAW_OUT_OF_ORDER_CALL; if (libraw_internal_data.output_data.histogram) { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * O.auto_bright_thr; if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } int s_iheight = S.iheight; int s_iwidth = S.iwidth; int s_width = S.width; int s_hwight = S.height; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, S.width); for (row = 0; row < S.height; row++, soff += rstep) { uchar *bufp = ((uchar *)scan0) + row * stride; ppm2 = (ushort *)(ppm = bufp); // keep trivial decisions in the outer loop for speed if (bgr) { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } else { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } // bufp += stride; // go to the next line } S.iheight = s_iheight; S.iwidth = s_iwidth; S.width = s_width; S.height = s_hwight; return 0; } #undef FORBGR #undef FORRGB libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode) { int width, height, colors, bps; get_mem_image_format(&width, &height, &colors, &bps); int stride = width * (bps / 8) * colors; unsigned ds = height * stride; libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + ds); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); // metadata init ret->type = LIBRAW_IMAGE_BITMAP; ret->height = height; ret->width = width; ret->colors = colors; ret->bits = bps; ret->data_size = ds; copy_mem_image(ret->data, stride, 0); return ret; } #undef FORC #undef FORCC #undef SWAP #endif int LibRaw::dcraw_ppm_tiff_writer(const char *filename) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); if (!imgdata.image) return LIBRAW_OUT_OF_ORDER_CALL; if (!filename) return ENOENT; FILE *f = fopen(filename, "wb"); if (!f) return errno; try { if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_ppm_tiff_writer()"); } libraw_internal_data.internal_data.output = f; write_ppm_tiff(); SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); libraw_internal_data.internal_data.output = NULL; fclose(f); return 0; } catch (LibRaw_exceptions err) { fclose(f); EXCEPTION_HANDLER(err); } } #define THUMB_READ_BEYOND 16384 void LibRaw::kodak_thumb_loader() { INT64 est_datasize = T.theight * T.twidth / 3; // is 0.3 bytes per pixel good estimate? if (ID.toffset < 0) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (ID.toffset + est_datasize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; // some kodak cameras ushort s_height = S.height, s_width = S.width, s_iwidth = S.iwidth, s_iheight = S.iheight; ushort s_flags = libraw_internal_data.unpacker_data.load_flags; libraw_internal_data.unpacker_data.load_flags = 12; int s_colors = P1.colors; unsigned s_filters = P1.filters; ushort(*s_image)[4] = imgdata.image; S.height = T.theight; S.width = T.twidth; P1.filters = 0; if (thumb_load_raw == &CLASS kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "LibRaw::kodak_thumb_loader()"); ID.input->seek(ID.toffset, SEEK_SET); // read kodak thumbnail into T.image[] try { (this->*thumb_load_raw)(); } catch (...) { free(imgdata.image); imgdata.image = s_image; T.twidth = 0; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = 0; S.height = s_height; T.tcolors = 0; P1.colors = s_colors; P1.filters = s_filters; T.tlength = 0; libraw_internal_data.unpacker_data.load_flags = s_flags; return; } // copy-n-paste from image pipe #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #ifndef CLIP #define CLIP(x) LIM(x, 0, 65535) #endif #define SWAP(a, b) \ { \ a ^= b; \ a ^= (b ^= a); \ } // from scale_colors { double dmax; float scale_mul[4]; int c, val; for (dmax = DBL_MAX, c = 0; c < 3; c++) if (dmax > C.pre_mul[c]) dmax = C.pre_mul[c]; for (c = 0; c < 3; c++) scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum; scale_mul[3] = scale_mul[1]; size_t size = S.height * S.width; for (unsigned i = 0; i < size * 4; i++) { val = imgdata.image[0][i]; if (!val) continue; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } // from convert_to_rgb ushort *img; int row, col; int(*t_hist)[LIBRAW_HISTOGRAM_SIZE] = (int(*)[LIBRAW_HISTOGRAM_SIZE])calloc(sizeof(*t_hist), 4); merror(t_hist, "LibRaw::kodak_thumb_loader()"); float out[3], out_cam[3][4] = {{2.81761312, -1.98369181, 0.166078627, 0}, {-0.111855984, 1.73688626, -0.625030339, 0}, {-0.0379119813, -0.891268849, 1.92918086, 0}}; for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { out[0] = out[1] = out[2] = 0; int c; for (c = 0; c < 3; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); for (c = 0; c < P1.colors; c++) t_hist[c][img[c] >> 3]++; } // from gamma_lut int(*save_hist)[LIBRAW_HISTOGRAM_SIZE] = libraw_internal_data.output_data.histogram; libraw_internal_data.output_data.histogram = t_hist; // make curve output curve! ushort(*t_curve) = (ushort *)calloc(sizeof(C.curve), 1); merror(t_curve, "LibRaw::kodak_thumb_loader()"); memmove(t_curve, C.curve, sizeof(C.curve)); memset(C.curve, 0, sizeof(C.curve)); { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } libraw_internal_data.output_data.histogram = save_hist; free(t_hist); // from write_ppm_tiff - copy pixels into bitmap int s_flip = imgdata.sizes.flip; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = 0; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); if (T.thumb) free(T.thumb); T.thumb = (char *)calloc(S.width * S.height, P1.colors); merror(T.thumb, "LibRaw::kodak_thumb_loader()"); T.tlength = S.width * S.height * P1.colors; // from write_tiff_ppm { int soff = flip_index(0, 0); int cstep = flip_index(0, 1) - soff; int rstep = flip_index(1, 0) - flip_index(0, S.width); for (int row = 0; row < S.height; row++, soff += rstep) { char *ppm = T.thumb + row * S.width * P1.colors; for (int col = 0; col < S.width; col++, soff += cstep) for (int c = 0; c < P1.colors; c++) ppm[col * P1.colors + c] = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } } memmove(C.curve, t_curve, sizeof(C.curve)); free(t_curve); // restore variables free(imgdata.image); imgdata.image = s_image; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = s_flip; T.twidth = S.width; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = S.height; S.height = s_height; T.tcolors = P1.colors; P1.colors = s_colors; P1.filters = s_filters; libraw_internal_data.unpacker_data.load_flags = s_flags; } #undef MIN #undef MAX #undef LIM #undef CLIP #undef SWAP // ������� thumbnail �� �����, ������ thumb_format � ������������ � �������� int LibRaw::thumbOK(INT64 maxsz) { if (!ID.input) return 0; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) return 0; INT64 fsize = ID.input->size(); if (fsize > 0x7fffffffU) return 0; // No thumb for raw > 2Gb int tsize = 0; int tcol = (T.tcolors > 0 && T.tcolors < 4) ? T.tcolors : 3; if (write_thumb == &LibRaw::jpeg_thumb) tsize = T.tlength; else if (write_thumb == &LibRaw::ppm_thumb) tsize = tcol * T.twidth * T.theight; else if (write_thumb == &LibRaw::ppm16_thumb) tsize = tcol * T.twidth * T.theight * ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1); else if (write_thumb == &LibRaw::x3f_thumb_loader) { tsize = x3f_thumb_size(); } else // Kodak => no check tsize = 1; if (tsize < 0) return 0; if (maxsz > 0 && tsize > maxsz) return 0; return (tsize + ID.toffset <= fsize) ? 1 : 0; } #ifndef NO_JPEG struct jpegErrorManager { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; longjmp(myerr->setjmp_buffer, 1); } #endif int LibRaw::unpack_thumb(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7; int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { return LIBRAW_NO_THUMBNAIL; } else if (thumb_load_raw) { kodak_thumb_loader(); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { if (write_thumb == &LibRaw::x3f_thumb_loader) { INT64 tsize = x3f_thumb_size(); if (tsize < 2048 || INT64(ID.toffset) + tsize < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } else { if (INT64(ID.toffset) + INT64(T.tlength) < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + INT64(T.tlength) > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } ID.input->seek(ID.toffset, SEEK_SET); if (write_thumb == &LibRaw::jpeg_thumb) { if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "jpeg_thumb()"); ID.input->read(T.thumb, 1, T.tlength); unsigned char *tthumb = (unsigned char *)T.thumb; tthumb[0] = 0xff; tthumb[1] = 0xd8; #ifdef NO_JPEG T.tcolors = 3; #else { jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; if (setjmp(jerr.setjmp_buffer)) { err2: jpeg_destroy_decompress(&cinfo); T.tcolors = 3; } jpeg_create_decompress(&cinfo); jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) goto err2; T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3) ? cinfo.num_components : 3; jpeg_destroy_decompress(&cinfo); } #endif T.tformat = LIBRAW_THUMBNAIL_JPEG; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm_thumb) { if (t_bytesps > 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more bits int t_length = T.twidth * T.theight * t_colors; if (T.tlength && T.tlength < t_length) // try to find tiff ifd with needed offset { int pifd = -1; for (int ii = 0; ii < libraw_internal_data.identify_data.tiff_nifds && ii < LIBRAW_IFD_MAXCOUNT; ii++) if (tiff_ifd[ii].offset == libraw_internal_data.internal_data.toffset) // found { pifd = ii; break; } if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count && tiff_ifd[pifd].strip_byte_counts_count) { // We found it, calculate final size unsigned total_size = 0; for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++) total_size += tiff_ifd[pifd].strip_byte_counts[i]; if (total_size != t_length) // recalculate colors { if (total_size == T.twidth * T.tlength * 3) T.tcolors = 3; else if (total_size == T.twidth * T.tlength) T.tcolors = 1; } T.tlength = total_size; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "ppm_thumb()"); char *dest = T.thumb; INT64 pos = ID.input->tell(); for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count && i < tiff_ifd[pifd].strip_offsets_count; i++) { int remain = T.tlength; int sz = tiff_ifd[pifd].strip_byte_counts[i]; int off = tiff_ifd[pifd].strip_offsets[i]; if (off >= 0 && off + sz <= ID.input->size() && sz <= remain) { ID.input->seek(off, SEEK_SET); ID.input->read(dest, sz, 1); remain -= sz; dest += sz; } } ID.input->seek(pos, SEEK_SET); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } } if (!T.tlength) T.tlength = t_length; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); if (!T.tcolors) T.tcolors = t_colors; merror(T.thumb, "ppm_thumb()"); ID.input->read(T.thumb, 1, T.tlength); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm16_thumb) { if (t_bytesps > 2) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for more bits int o_bps = (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1; int o_length = T.twidth * T.theight * t_colors * o_bps; int i_length = T.twidth * T.theight * t_colors * 2; if (!T.tlength) T.tlength = o_length; ushort *t_thumb = (ushort *)calloc(i_length, 1); ID.input->read(t_thumb, 1, i_length); if ((libraw_internal_data.unpacker_data.order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)t_thumb, (char *)t_thumb, i_length); if (T.thumb) free(T.thumb); if ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS)) { T.thumb = (char *)t_thumb; T.tformat = LIBRAW_THUMBNAIL_BITMAP16; } else { T.thumb = (char *)malloc(o_length); merror(T.thumb, "ppm_thumb()"); for (int i = 0; i < o_length; i++) T.thumb[i] = t_thumb[i] >> 8; free(t_thumb); T.tformat = LIBRAW_THUMBNAIL_BITMAP; } SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::x3f_thumb_loader) { x3f_thumb_loader(); SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { return LIBRAW_UNSUPPORTED_THUMBNAIL; } } // last resort return LIBRAW_UNSUPPORTED_THUMBNAIL; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } int LibRaw::dcraw_thumb_writer(const char *fname) { // CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD); if (!fname) return ENOENT; FILE *tfp = fopen(fname, "wb"); if (!tfp) return errno; if (!T.thumb) { fclose(tfp); return LIBRAW_OUT_OF_ORDER_CALL; } try { switch (T.tformat) { case LIBRAW_THUMBNAIL_JPEG: jpeg_thumb_writer(tfp, T.thumb, T.tlength); break; case LIBRAW_THUMBNAIL_BITMAP: fprintf(tfp, "P6\n%d %d\n255\n", T.twidth, T.theight); fwrite(T.thumb, 1, T.tlength, tfp); break; default: fclose(tfp); return LIBRAW_UNSUPPORTED_THUMBNAIL; } fclose(tfp); return 0; } catch (LibRaw_exceptions err) { fclose(tfp); EXCEPTION_HANDLER(err); } } int LibRaw::adjust_sizes_info_only(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); raw2image_start(); if (O.use_fuji_rotate) { if (IO.fuji_width) { IO.fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink; S.iwidth = (ushort)(IO.fuji_width / sqrt(0.5)); S.iheight = (ushort)((S.iheight - IO.fuji_width) / sqrt(0.5)); } else { if (S.pixel_aspect < 0.995) S.iheight = (ushort)(S.iheight / S.pixel_aspect + 0.5); if (S.pixel_aspect > 1.005) S.iwidth = (ushort)(S.iwidth * S.pixel_aspect + 0.5); } } SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); if (S.flip & 4) { unsigned short t = S.iheight; S.iheight = S.iwidth; S.iwidth = t; SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); } return 0; } int LibRaw::subtract_black() { adjust_bl(); return subtract_black_internal(); } int LibRaw::subtract_black_internal() { CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE); try { if (!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3] || (C.cblack[4] && C.cblack[5]))) { #define BAYERC(row, col, c) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][c] int cblk[4], i; for (i = 0; i < 4; i++) cblk[i] = C.cblack[i]; int size = S.iheight * S.iwidth; #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define CLIP(x) LIM(x, 0, 65535) int dmax = 0; if (C.cblack[4] && C.cblack[5]) { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } else { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } C.data_maximum = dmax & 0xffff; #undef MIN #undef MAX #undef LIM #undef CLIP C.maximum -= C.black; ZERO(C.cblack); // Yeah, we used cblack[6+] values too! C.black = 0; #undef BAYERC } else { // Nothing to Do, maximum is already calculated, black level is 0, so no change // only calculate channel maximum; int idx; ushort *p = (ushort *)imgdata.image; int dmax = 0; for (idx = 0; idx < S.iheight * S.iwidth * 4; idx++) if (dmax < p[idx]) dmax = p[idx]; C.data_maximum = dmax; } return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #define TBLN 65535 void LibRaw::exp_bef(float shift, float smooth) { // params limits if (shift > 8) shift = 8; if (shift < 0.25) shift = 0.25; if (smooth < 0.0) smooth = 0.0; if (smooth > 1.0) smooth = 1.0; unsigned short *lut = (ushort *)malloc((TBLN + 1) * sizeof(unsigned short)); if (shift <= 1.0) { for (int i = 0; i <= TBLN; i++) lut[i] = (unsigned short)((float)i * shift); } else { float x1, x2, y1, y2; float cstops = log(shift) / log(2.0f); float room = cstops * 2; float roomlin = powf(2.0f, room); x2 = (float)TBLN; x1 = (x2 + 1) / roomlin - 1; y1 = x1 * shift; y2 = x2 * (1 + (1 - smooth) * (shift - 1)); float sq3x = powf(x1 * x1 * x2, 1.0f / 3.0f); float B = (y2 - y1 + shift * (3 * x1 - 3.0f * sq3x)) / (x2 + 2.0f * x1 - 3.0f * sq3x); float A = (shift - B) * 3.0f * powf(x1 * x1, 1.0f / 3.0f); float CC = y2 - A * powf(x2, 1.0f / 3.0f) - B * x2; for (int i = 0; i <= TBLN; i++) { float X = (float)i; float Y = A * powf(X, 1.0f / 3.0f) + B * X + CC; if (i < x1) lut[i] = (unsigned short)((float)i * shift); else lut[i] = Y < 0 ? 0 : (Y > TBLN ? TBLN : (unsigned short)(Y)); } } for (int i = 0; i < S.height * S.width; i++) { imgdata.image[i][0] = lut[imgdata.image[i][0]]; imgdata.image[i][1] = lut[imgdata.image[i][1]]; imgdata.image[i][2] = lut[imgdata.image[i][2]]; imgdata.image[i][3] = lut[imgdata.image[i][3]]; } if (C.data_maximum <= TBLN) C.data_maximum = lut[C.data_maximum]; if (C.maximum <= TBLN) C.maximum = lut[C.maximum]; free(lut); } #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y)) #define CLIP(x) LIM(x, 0, 65535) void LibRaw::convert_to_rgb_loop(float out_cam[3][4]) { int row, col, c; float out[3]; ushort *img; memset(libraw_internal_data.output_data.histogram, 0, sizeof(int) * LIBRAW_HISTOGRAM_SIZE * 4); for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { if (!libraw_internal_data.internal_output_params.raw_color) { out[0] = out[1] = out[2] = 0; for (c = 0; c < imgdata.idata.colors; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); } for (c = 0; c < imgdata.idata.colors; c++) libraw_internal_data.output_data.histogram[c][img[c] >> 3]++; } } void LibRaw::scale_colors_loop(float scale_mul[4]) { unsigned size = S.iheight * S.iwidth; if (C.cblack[4] && C.cblack[5]) { int val; for (unsigned i = 0; i < size * 4; i++) { if (!(val = imgdata.image[0][i])) continue; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else if (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3]) { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; if (!val) continue; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else // BL is zero { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } } void LibRaw::adjust_bl() { int clear_repeat = 0; if (O.user_black >= 0) { C.black = O.user_black; clear_repeat = 1; } for (int i = 0; i < 4; i++) if (O.user_cblack[i] > -1000000) { C.cblack[i] = O.user_cblack[i]; clear_repeat = 1; } if (clear_repeat) C.cblack[4] = C.cblack[5] = 0; // Add common part to cblack[] early if (imgdata.idata.filters > 1000 && (C.cblack[4] + 1) / 2 == 1 && (C.cblack[5] + 1) / 2 == 1) { int clrs[4]; int lastg = -1, gcnt = 0; for (int c = 0; c < 4; c++) { clrs[c] = FC(c / 2, c % 2); if (clrs[c] == 1) { gcnt++; lastg = c; } } if (gcnt > 1 && lastg >= 0) clrs[lastg] = 3; for (int c = 0; c < 4; c++) C.cblack[clrs[c]] += C.cblack[6 + c / 2 % C.cblack[4] * C.cblack[5] + c % 2 % C.cblack[5]]; C.cblack[4] = C.cblack[5] = 0; // imgdata.idata.filters = sfilters; } else if (imgdata.idata.filters <= 1000 && C.cblack[4] == 1 && C.cblack[5] == 1) // Fuji RAF dng { for (int c = 0; c < 4; c++) C.cblack[c] += C.cblack[6]; C.cblack[4] = C.cblack[5] = 0; } // remove common part from C.cblack[] int i = C.cblack[3]; int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; // remove common part C.black += i; // Now calculate common part for cblack[6+] part and move it to C.black if (C.cblack[4] && C.cblack[5]) { i = C.cblack[6]; for (c = 1; c < C.cblack[4] * C.cblack[5]; c++) if (i > C.cblack[6 + c]) i = C.cblack[6 + c]; // Remove i from cblack[6+] int nonz = 0; for (c = 0; c < C.cblack[4] * C.cblack[5]; c++) { C.cblack[6 + c] -= i; if (C.cblack[6 + c]) nonz++; } C.black += i; if (!nonz) C.cblack[4] = C.cblack[5] = 0; } for (c = 0; c < 4; c++) C.cblack[c] += C.black; } int LibRaw::dcraw_process(void) { int quality, i; int iterations = -1, dcb_enhance = 1, noiserd = 0; int eeci_refine_fl = 0, es_med_passes_fl = 0; float cared = 0, cablue = 0; float linenoise = 0; float lclean = 0, cclean = 0; float thresh = 0; float preser = 0; float expos = 1.0; CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); // CHECK_ORDER_HIGH(LIBRAW_PROGRESS_PRE_INTERPOLATE); try { int no_crop = 1; if (~O.cropbox[2] && ~O.cropbox[3]) no_crop = 0; libraw_decoder_info_t di; get_decoder_info(&di); bool is_bayer = (imgdata.idata.filters || P1.colors == 1); int subtract_inline = !O.bad_pixels && !O.dark_frame && is_bayer && !IO.zero_is_bad; raw2image_ex(subtract_inline); // allocate imgdata.image and copy data! // Adjust sizes int save_4color = O.four_color_rgb; if (IO.zero_is_bad) { remove_zeroes(); SET_PROC_FLAG(LIBRAW_PROGRESS_REMOVE_ZEROES); } if (O.bad_pixels && no_crop) { bad_pixels(O.bad_pixels); SET_PROC_FLAG(LIBRAW_PROGRESS_BAD_PIXELS); } if (O.dark_frame && no_crop) { subtract(O.dark_frame); SET_PROC_FLAG(LIBRAW_PROGRESS_DARK_FRAME); } /* pre subtract black callback: check for it above to disable subtract inline */ if(callbacks.pre_subtractblack_cb) (callbacks.pre_subtractblack_cb)(this); quality = 2 + !IO.fuji_width; if (O.user_qual >= 0) quality = O.user_qual; if (!subtract_inline || !C.data_maximum) { adjust_bl(); subtract_black_internal(); } if (!(di.decoder_flags & LIBRAW_DECODER_FIXEDMAXC)) adjust_maximum(); if (O.user_sat > 0) C.maximum = O.user_sat; if (P1.is_foveon) { if (load_raw == &LibRaw::x3f_load_raw) { // Filter out zeroes for (int i = 0; i < S.height * S.width * 4; i++) if ((short)imgdata.image[0][i] < 0) imgdata.image[0][i] = 0; } SET_PROC_FLAG(LIBRAW_PROGRESS_FOVEON_INTERPOLATE); } if (O.green_matching && !O.half_size) { green_matching(); } if(callbacks.pre_scalecolors_cb) (callbacks.pre_scalecolors_cb)(this); if (!O.no_auto_scale) { scale_colors(); SET_PROC_FLAG(LIBRAW_PROGRESS_SCALE_COLORS); } if(callbacks.pre_preinterpolate_cb) (callbacks.pre_preinterpolate_cb)(this); pre_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_PRE_INTERPOLATE); if (O.dcb_iterations >= 0) iterations = O.dcb_iterations; if (O.dcb_enhance_fl >= 0) dcb_enhance = O.dcb_enhance_fl; if (O.fbdd_noiserd >= 0) noiserd = O.fbdd_noiserd; /* pre-exposure correction callback */ if (O.exp_correc > 0) { expos = O.exp_shift; preser = O.exp_preser; exp_bef(expos, preser); } if(callbacks.pre_interpolate_cb) (callbacks.pre_interpolate_cb)(this); /* post-exposure correction fallback */ if (P1.filters && !O.no_interpolation) { if (noiserd > 0 && P1.colors == 3 && P1.filters) fbdd(noiserd); if (P1.filters > 1000 && callbacks.interpolate_bayer_cb) (callbacks.interpolate_bayer_cb)(this); else if (P1.filters == 9 && callbacks.interpolate_xtrans_cb) (callbacks.interpolate_xtrans_cb)(this); else if (quality == 0) lin_interpolate(); else if (quality == 1 || P1.colors > 3) vng_interpolate(); else if (quality == 2 && P1.filters > 1000) ppg_interpolate(); else if (P1.filters == LIBRAW_XTRANS) { // Fuji X-Trans xtrans_interpolate(quality > 2 ? 3 : 1); } else if (quality == 3) ahd_interpolate(); // really don't need it here due to fallback op else if (quality == 4) dcb(iterations, dcb_enhance); else if (quality == 11) dht_interpolate(); else if (quality == 12) aahd_interpolate(); // fallback to AHD else { ahd_interpolate(); imgdata.process_warnings |= LIBRAW_WARN_FALLBACK_TO_AHD; } SET_PROC_FLAG(LIBRAW_PROGRESS_INTERPOLATE); } if (IO.mix_green) { for (P1.colors = 3, i = 0; i < S.height * S.width; i++) imgdata.image[i][1] = (imgdata.image[i][1] + imgdata.image[i][3]) >> 1; SET_PROC_FLAG(LIBRAW_PROGRESS_MIX_GREEN); } if(callbacks.post_interpolate_cb) (callbacks.post_interpolate_cb)(this); if (!P1.is_foveon) { if (P1.colors == 3) { /* median filter callback, if not set use own */ median_filter(); SET_PROC_FLAG(LIBRAW_PROGRESS_MEDIAN_FILTER); } } if (O.highlight == 2) { blend_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.highlight > 2) { recover_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.use_fuji_rotate) { fuji_rotate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); } if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_process()"); } #ifndef NO_LCMS if (O.camera_profile) { apply_profile(O.camera_profile, O.output_profile); SET_PROC_FLAG(LIBRAW_PROGRESS_APPLY_PROFILE); } #endif if(callbacks.pre_converttorgb_cb) (callbacks.pre_converttorgb_cb)(this); convert_to_rgb(); SET_PROC_FLAG(LIBRAW_PROGRESS_CONVERT_RGB); if(callbacks.post_converttorgb_cb) (callbacks.post_converttorgb_cb)(this); if (O.use_fuji_rotate) { stretch(); SET_PROC_FLAG(LIBRAW_PROGRESS_STRETCH); } O.four_color_rgb = save_4color; // also, restore return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } // clang-format off // Supported cameras: static const char *static_camera_list[] = { "Adobe Digital Negative (DNG)", "AgfaPhoto DC-833m", "Alcatel 5035D", "Apple iPad Pro", "Apple iPhone SE", "Apple iPhone 6s", "Apple iPhone 6 plus", "Apple iPhone 7", "Apple iPhone 7 plus", "Apple iPhone 8", "Apple iPhone 8 plus", "Apple iPhone X", "Apple QuickTake 100", "Apple QuickTake 150", "Apple QuickTake 200", "ARRIRAW format", "AVT F-080C", "AVT F-145C", "AVT F-201C", "AVT F-510C", "AVT F-810C", "Baumer TXG14", "BlackMagic Cinema Camera", "BlackMagic Micro Cinema Camera", "BlackMagic Pocket Cinema Camera", "BlackMagic Production Camera 4k", "BlackMagic URSA", "BlackMagic URSA Mini 4k", "BlackMagic URSA Mini 4.6k", "BlackMagic URSA Mini Pro 4.6k", "Canon PowerShot 600", "Canon PowerShot A5", "Canon PowerShot A5 Zoom", "Canon PowerShot A50", "Canon PowerShot A410 (CHDK hack)", "Canon PowerShot A460 (CHDK hack)", "Canon PowerShot A470 (CHDK hack)", "Canon PowerShot A530 (CHDK hack)", "Canon PowerShot A540 (CHDK hack)", "Canon PowerShot A550 (CHDK hack)", "Canon PowerShot A570 (CHDK hack)", "Canon PowerShot A590 (CHDK hack)", "Canon PowerShot A610 (CHDK hack)", "Canon PowerShot A620 (CHDK hack)", "Canon PowerShot A630 (CHDK hack)", "Canon PowerShot A640 (CHDK hack)", "Canon PowerShot A650 (CHDK hack)", "Canon PowerShot A710 IS (CHDK hack)", "Canon PowerShot A720 IS (CHDK hack)", "Canon PowerShot A3300 IS (CHDK hack)", "Canon PowerShot D10 (CHDK hack)", "Canon PowerShot ELPH 130 IS (CHDK hack)", "Canon PowerShot ELPH 160 IS (CHDK hack)", "Canon PowerShot Pro70", "Canon PowerShot Pro90 IS", "Canon PowerShot Pro1", "Canon PowerShot G1", "Canon PowerShot G1 X", "Canon PowerShot G1 X Mark II", "Canon PowerShot G1 X Mark III", "Canon PowerShot G2", "Canon PowerShot G3", "Canon PowerShot G3 X", "Canon PowerShot G5", "Canon PowerShot G5 X", "Canon PowerShot G6", "Canon PowerShot G7 (CHDK hack)", "Canon PowerShot G7 X", "Canon PowerShot G7 X Mark II", "Canon PowerShot G9", "Canon PowerShot G9 X", "Canon PowerShot G9 X Mark II", "Canon PowerShot G10", "Canon PowerShot G11", "Canon PowerShot G12", "Canon PowerShot G15", "Canon PowerShot G16", "Canon PowerShot S2 IS (CHDK hack)", "Canon PowerShot S3 IS (CHDK hack)", "Canon PowerShot S5 IS (CHDK hack)", "Canon PowerShot SD300 (CHDK hack)", "Canon PowerShot SD750 (CHDK hack)", "Canon PowerShot SD950 (CHDK hack)", "Canon PowerShot S30", "Canon PowerShot S40", "Canon PowerShot S45", "Canon PowerShot S50", "Canon PowerShot S60", "Canon PowerShot S70", "Canon PowerShot S90", "Canon PowerShot S95", "Canon PowerShot S100", "Canon PowerShot S110", "Canon PowerShot S120", "Canon PowerShot SX1 IS", "Canon PowerShot SX50 HS", "Canon PowerShot SX60 HS", "Canon PowerShot SX100 IS (CHDK hack)", "Canon PowerShot SX110 IS (CHDK hack)", "Canon PowerShot SX120 IS (CHDK hack)", "Canon PowerShot SX130 IS (CHDK hack)", "Canon PowerShot SX160 IS (CHDK hack)", "Canon PowerShot SX220 HS (CHDK hack)", "Canon PowerShot SX510 HS (CHDK hack)", "Canon PowerShot SX10 IS (CHDK hack)", "Canon PowerShot SX20 IS (CHDK hack)", "Canon PowerShot SX30 IS (CHDK hack)", "Canon PowerShot IXUS 160 (CHDK hack)", "Canon PowerShot IXUS 900Ti (CHDK hack)", "Canon EOS D30", "Canon EOS D60", "Canon EOS 5D", "Canon EOS 5DS", "Canon EOS 5DS R", "Canon EOS 5D Mark II", "Canon EOS 5D Mark III", "Canon EOS 5D Mark IV", "Canon EOS 6D", "Canon EOS 6D Mark II", "Canon EOS 7D", "Canon EOS 7D Mark II", "Canon EOS 10D", "Canon EOS 20D", "Canon EOS 20Da", "Canon EOS 30D", "Canon EOS 40D", "Canon EOS 50D", "Canon EOS 60D", "Canon EOS 60Da", "Canon EOS 70D", "Canon EOS 77D", "Canon EOS 80D", "Canon EOS 200D", "Canon EOS 300D / Digital Rebel / Kiss Digital", "Canon EOS 350D / Digital Rebel XT / Kiss Digital N", "Canon EOS 400D / Digital Rebel XTi / Kiss Digital X", "Canon EOS 450D / Digital Rebel XSi / Kiss Digital X2", "Canon EOS 500D / Digital Rebel T1i / Kiss Digital X3", "Canon EOS 550D / Digital Rebel T2i / Kiss Digital X4", "Canon EOS 600D / Digital Rebel T3i / Kiss Digital X5", "Canon EOS 650D / Digital Rebel T4i / Kiss Digital X6i", "Canon EOS 700D / Digital Rebel T5i", "Canon EOS 750D / Digital Rebel T6i", "Canon EOS 760D / Digital Rebel T6S", "Canon EOS 800D", "Canon EOS 100D / Digital Rebel SL1", "Canon EOS 1000D / Digital Rebel XS / Kiss Digital F", "Canon EOS 1100D / Digital Rebel T3 / Kiss Digital X50", "Canon EOS 1200D", "Canon EOS 1300D", "Canon EOS C500", "Canon EOS D2000C", "Canon EOS M", "Canon EOS M2", "Canon EOS M3", "Canon EOS M5", "Canon EOS M6", "Canon EOS M10", "Canon EOS M100", "Canon EOS-1D", "Canon EOS-1DS", "Canon EOS-1D C", "Canon EOS-1D X", "Canon EOS-1D Mark II", "Canon EOS-1D Mark II N", "Canon EOS-1D Mark III", "Canon EOS-1D Mark IV", "Canon EOS-1Ds Mark II", "Canon EOS-1Ds Mark III", "Canon EOS-1D X Mark II", "Casio QV-2000UX", "Casio QV-3000EX", "Casio QV-3500EX", "Casio QV-4000", "Casio QV-5700", "Casio QV-R41", "Casio QV-R51", "Casio QV-R61", "Casio EX-F1", "Casio EX-FC300S", "Casio EX-FC400S", "Casio EX-FH20", "Casio EX-FH25", "Casio EX-FH100", "Casio EX-P600", "Casio EX-S20", "Casio EX-S100", "Casio EX-Z4", "Casio EX-Z50", "Casio EX-Z500", "Casio EX-Z55", "Casio EX-Z60", "Casio EX-Z75", "Casio EX-Z750", "Casio EX-Z8", "Casio EX-Z850", "Casio EX-Z1050", "Casio EX-ZR100", "Casio EX-Z1080", "Casio EX-ZR700", "Casio EX-ZR710", "Casio EX-ZR750", "Casio EX-ZR800", "Casio EX-ZR850", "Casio EX-ZR1000", "Casio EX-ZR1100", "Casio EX-ZR1200", "Casio EX-ZR1300", "Casio EX-ZR1500", "Casio EX-ZR3000", "Casio EX-ZR4000/5000", "Casio EX-ZR4100/5100", "Casio EX-100", "Casio EX-100F", "Casio EX-10", "Casio Exlim Pro 505", "Casio Exlim Pro 600", "Casio Exlim Pro 700", "Contax N Digital", "Creative PC-CAM 600", "Digital Bolex D16", "Digital Bolex D16M", "DJI 4384x3288", "DJI Phantom4 Pro/Pro+", "DJI Zenmuse X5", "DJI Zenmuse X5R", "DXO One", "Epson R-D1", "Epson R-D1s", "Epson R-D1x", "Foculus 531C", "FujiFilm E505", "FujiFilm E550", "FujiFilm E900", "FujiFilm F700", "FujiFilm F710", "FujiFilm F800", "FujiFilm F810", "FujiFilm S2Pro", "FujiFilm S3Pro", "FujiFilm S5Pro", "FujiFilm S20Pro", "FujiFilm S1", "FujiFilm S100FS", "FujiFilm S5000", "FujiFilm S5100/S5500", "FujiFilm S5200/S5600", "FujiFilm S6000fd", "FujiFilm S6500fd", "FujiFilm S7000", "FujiFilm S9000/S9500", "FujiFilm S9100/S9600", "FujiFilm S200EXR", "FujiFilm S205EXR", "FujiFilm SL1000", "FujiFilm HS10/HS11", "FujiFilm HS20EXR", "FujiFilm HS22EXR", "FujiFilm HS30EXR", "FujiFilm HS33EXR", "FujiFilm HS35EXR", "FujiFilm HS50EXR", "FujiFilm F505EXR", "FujiFilm F550EXR", "FujiFilm F600EXR", "FujiFilm F605EXR", "FujiFilm F770EXR", "FujiFilm F775EXR", "FujiFilm F800EXR", "FujiFilm F900EXR", "FujiFilm GFX 50S", "FujiFilm X-Pro1", "FujiFilm X-Pro2", "FujiFilm X-S1", "FujiFilm XQ1", "FujiFilm XQ2", "FujiFilm X100", "FujiFilm X100f", "FujiFilm X100S", "FujiFilm X100T", "FujiFilm X10", "FujiFilm X20", "FujiFilm X30", "FujiFilm X70", "FujiFilm X-A1", "FujiFilm X-A2", "FujiFilm X-A3", "FujiFilm X-A5", "FujiFilm X-A10", "FujiFilm X-A20", "FujiFilm X-E1", "FujiFilm X-E2", "FujiFilm X-E2S", "FujiFilm X-E3", "FujiFilm X-M1", "FujiFilm XF1", "FujiFilm X-H1", "FujiFilm X-T1", "FujiFilm X-T1 Graphite Silver", "FujiFilm X-T2", "FujiFilm X-T10", "FujiFilm X-T20", "FujiFilm IS-1", "Gione E7", "GITUP GIT2", "GITUP GIT2P", "Google Pixel", "Google Pixel XL", "Hasselblad H2D-22", "Hasselblad H2D-39", "Hasselblad H3DII-22", "Hasselblad H3DII-31", "Hasselblad H3DII-39", "Hasselblad H3DII-50", "Hasselblad H3D-22", "Hasselblad H3D-31", "Hasselblad H3D-39", "Hasselblad H4D-60", "Hasselblad H4D-50", "Hasselblad H4D-40", "Hasselblad H4D-31", "Hasselblad H5D-60", "Hasselblad H5D-50", "Hasselblad H5D-50c", "Hasselblad H5D-40", "Hasselblad H6D-100c", "Hasselblad A6D-100c", // Aerial camera "Hasselblad CFV", "Hasselblad CFV-50", "Hasselblad CFH", "Hasselblad CF-22", "Hasselblad CF-31", "Hasselblad CF-39", "Hasselblad V96C", "Hasselblad Lusso", "Hasselblad Lunar", "Hasselblad True Zoom", "Hasselblad Stellar", "Hasselblad Stellar II", "Hasselblad HV", "Hasselblad X1D", "HTC UltraPixel", "HTC MyTouch 4G", "HTC One (A9)", "HTC One (M9)", "HTC 10", "Huawei P9 (EVA-L09/AL00)", "Huawei Honor6a", "Huawei Honor9", "Huawei Mate10 (BLA-L29)", "Imacon Ixpress 96, 96C", "Imacon Ixpress 384, 384C (single shot only)", "Imacon Ixpress 132C", "Imacon Ixpress 528C (single shot only)", "ISG 2020x1520", "Ikonoskop A-Cam dII Panchromatic", "Ikonoskop A-Cam dII", "Kinefinity KineMINI", "Kinefinity KineRAW Mini", "Kinefinity KineRAW S35", "Kodak DC20", "Kodak DC25", "Kodak DC40", "Kodak DC50", "Kodak DC120", "Kodak DCS200", "Kodak DCS315C", "Kodak DCS330C", "Kodak DCS420", "Kodak DCS460", "Kodak DCS460A", "Kodak DCS460D", "Kodak DCS520C", "Kodak DCS560C", "Kodak DCS620C", "Kodak DCS620X", "Kodak DCS660C", "Kodak DCS660M", "Kodak DCS720X", "Kodak DCS760C", "Kodak DCS760M", "Kodak EOSDCS1", "Kodak EOSDCS3B", "Kodak NC2000F", "Kodak ProBack", "Kodak PB645C", "Kodak PB645H", "Kodak PB645M", "Kodak DCS Pro 14n", "Kodak DCS Pro 14nx", "Kodak DCS Pro SLR/c", "Kodak DCS Pro SLR/n", "Kodak C330", "Kodak C603", "Kodak P850", "Kodak P880", "Kodak S-1", "Kodak Z980", "Kodak Z981", "Kodak Z990", "Kodak Z1015", "Kodak KAI-0340", "Konica KD-400Z", "Konica KD-510Z", "Leaf AFi 5", "Leaf AFi 6", "Leaf AFi 7", "Leaf AFi-II 6", "Leaf AFi-II 7", "Leaf AFi-II 10", "Leaf AFi-II 10R", "Leaf Aptus-II 5", "Leaf Aptus-II 6", "Leaf Aptus-II 7", "Leaf Aptus-II 8", "Leaf Aptus-II 10", "Leaf Aptus-II 12", "Leaf Aptus-II 12R", "Leaf Aptus 17", "Leaf Aptus 22", "Leaf Aptus 54S", "Leaf Aptus 65", "Leaf Aptus 65S", "Leaf Aptus 75", "Leaf Aptus 75S", "Leaf Cantare", "Leaf Cantare XY", "Leaf CatchLight", "Leaf CMost", "Leaf Credo 40", "Leaf Credo 50", "Leaf Credo 60", "Leaf Credo 80 (low compression mode only)", "Leaf DCB-II", "Leaf Valeo 6", "Leaf Valeo 11", "Leaf Valeo 17", "Leaf Valeo 17wi", "Leaf Valeo 22", "Leaf Valeo 22wi", "Leaf Volare", "Lenovo a820", "Leica C (Typ 112)", "Leica CL", "Leica Digilux 2", "Leica Digilux 3", "Leica Digital-Modul-R", "Leica D-LUX2", "Leica D-LUX3", "Leica D-LUX4", "Leica D-LUX5", "Leica D-LUX6", "Leica D-Lux (Typ 109)", "Leica M8", "Leica M8.2", "Leica M9", "Leica M10", "Leica M (Typ 240)", "Leica M (Typ 262)", "Leica Monochrom (Typ 240)", "Leica Monochrom (Typ 246)", "Leica M-D (Typ 262)", "Leica M-E", "Leica M-P", "Leica R8", "Leica Q (Typ 116)", "Leica S", "Leica S2", "Leica S (Typ 007)", "Leica SL (Typ 601)", "Leica T (Typ 701)", "Leica TL", "Leica TL2", "Leica X1", "Leica X (Typ 113)", "Leica X2", "Leica X-E (Typ 102)", "Leica X-U (Typ 113)", "Leica V-LUX1", "Leica V-LUX2", "Leica V-LUX3", "Leica V-LUX4", "Leica V-Lux (Typ 114)", "Leica X VARIO (Typ 107)", "LG G3", "LG G4", "LG V20 (F800K)", "LG VS995", "Logitech Fotoman Pixtura", "Mamiya ZD", "Matrix 4608x3288", "Meizy MX4", "Micron 2010", "Minolta RD175", "Minolta DiMAGE 5", "Minolta DiMAGE 7", "Minolta DiMAGE 7i", "Minolta DiMAGE 7Hi", "Minolta DiMAGE A1", "Minolta DiMAGE A2", "Minolta DiMAGE A200", "Minolta DiMAGE G400", "Minolta DiMAGE G500", "Minolta DiMAGE G530", "Minolta DiMAGE G600", "Minolta DiMAGE Z2", "Minolta Alpha/Dynax/Maxxum 5D", "Minolta Alpha/Dynax/Maxxum 7D", "Motorola PIXL", "Nikon D1", "Nikon D1H", "Nikon D1X", "Nikon D2H", "Nikon D2Hs", "Nikon D2X", "Nikon D2Xs", "Nikon D3", "Nikon D3s", "Nikon D3X", "Nikon D4", "Nikon D4s", "Nikon D40", "Nikon D40X", "Nikon D5", "Nikon D50", "Nikon D60", "Nikon D70", "Nikon D70s", "Nikon D80", "Nikon D90", "Nikon D100", "Nikon D200", "Nikon D300", "Nikon D300s", "Nikon D500", "Nikon D600", "Nikon D610", "Nikon D700", "Nikon D750", "Nikon D800", "Nikon D800E", "Nikon D810", "Nikon D810A", "Nikon D850", "Nikon D3000", "Nikon D3100", "Nikon D3200", "Nikon D3300", "Nikon D3400", "Nikon D5000", "Nikon D5100", "Nikon D5200", "Nikon D5300", "Nikon D5500", "Nikon D5600", "Nikon D7000", "Nikon D7100", "Nikon D7200", "Nikon D7500", "Nikon Df", "Nikon 1 AW1", "Nikon 1 J1", "Nikon 1 J2", "Nikon 1 J3", "Nikon 1 J4", "Nikon 1 J5", "Nikon 1 S1", "Nikon 1 S2", "Nikon 1 V1", "Nikon 1 V2", "Nikon 1 V3", "Nikon E700 (\"DIAG RAW\" hack)", "Nikon E800 (\"DIAG RAW\" hack)", "Nikon E880 (\"DIAG RAW\" hack)", "Nikon E900 (\"DIAG RAW\" hack)", "Nikon E950 (\"DIAG RAW\" hack)", "Nikon E990 (\"DIAG RAW\" hack)", "Nikon E995 (\"DIAG RAW\" hack)", "Nikon E2100 (\"DIAG RAW\" hack)", "Nikon E2500 (\"DIAG RAW\" hack)", "Nikon E3200 (\"DIAG RAW\" hack)", "Nikon E3700 (\"DIAG RAW\" hack)", "Nikon E4300 (\"DIAG RAW\" hack)", "Nikon E4500 (\"DIAG RAW\" hack)", "Nikon E5000", "Nikon E5400", "Nikon E5700", "Nikon E8400", "Nikon E8700", "Nikon E8800", "Nikon Coolpix A", "Nikon Coolpix B700", "Nikon Coolpix P330", "Nikon Coolpix P340", "Nikon Coolpix P6000", "Nikon Coolpix P7000", "Nikon Coolpix P7100", "Nikon Coolpix P7700", "Nikon Coolpix P7800", "Nikon Coolpix S6 (\"DIAG RAW\" hack)", "Nikon Coolscan NEF", "Nokia N95", "Nokia X2", "Nokia 1200x1600", "Nokia Lumia 950 XL", "Nokia Lumia 1020", "Nokia Lumia 1520", "Olympus AIR A01", "Olympus C3030Z", "Olympus C5050Z", "Olympus C5060Z", "Olympus C7070WZ", "Olympus C70Z,C7000Z", "Olympus C740UZ", "Olympus C770UZ", "Olympus C8080WZ", "Olympus X200,D560Z,C350Z", "Olympus E-1", "Olympus E-3", "Olympus E-5", "Olympus E-10", "Olympus E-20", "Olympus E-30", "Olympus E-300", "Olympus E-330", "Olympus E-400", "Olympus E-410", "Olympus E-420", "Olympus E-450", "Olympus E-500", "Olympus E-510", "Olympus E-520", "Olympus E-600", "Olympus E-620", "Olympus E-P1", "Olympus E-P2", "Olympus E-P3", "Olympus E-P5", "Olympus E-PL1", "Olympus E-PL1s", "Olympus E-PL2", "Olympus E-PL3", "Olympus E-PL5", "Olympus E-PL6", "Olympus E-PL7", "Olympus E-PL8", "Olympus E-PL9", "Olympus E-PM1", "Olympus E-PM2", "Olympus E-M1", "Olympus E-M1 Mark II", "Olympus E-M10", "Olympus E-M10 Mark II", "Olympus E-M10 Mark III", "Olympus E-M5", "Olympus E-M5 Mark II", "Olympus Pen F", "Olympus SP310", "Olympus SP320", "Olympus SP350", "Olympus SP500UZ", "Olympus SP510UZ", "Olympus SP550UZ", "Olympus SP560UZ", "Olympus SP565UZ", "Olympus SP570UZ", "Olympus STYLUS1", "Olympus STYLUS1s", "Olympus SH-2", "Olympus SH-3", "Olympus TG-4", "Olympus TG-5", "Olympus XZ-1", "Olympus XZ-2", "Olympus XZ-10", "OmniVision 4688", "OmniVision OV5647", "OmniVision OV5648", "OmniVision OV8850", "OmniVision 13860", "OnePlus One", "OnePlus A3303", "OnePlus A5000", "Panasonic DMC-CM1", "Panasonic DMC-FZ8", "Panasonic DMC-FZ18", "Panasonic DMC-FZ28", "Panasonic DMC-FZ30", "Panasonic DMC-FZ35/FZ38", "Panasonic DMC-FZ40", "Panasonic DMC-FZ45", "Panasonic DMC-FZ50", "Panasonic DMC-FZ7", "Panasonic DMC-FZ70", "Panasonic DMC-FZ72", "Panasonic DC-FZ80/82", "Panasonic DMC-FZ100", "Panasonic DMC-FZ150", "Panasonic DMC-FZ200", "Panasonic DMC-FZ300/330", "Panasonic DMC-FZ1000", "Panasonic DMC-FZ2000/2500/FZH1", "Panasonic DMC-FX150", "Panasonic DMC-G1", "Panasonic DMC-G10", "Panasonic DMC-G2", "Panasonic DMC-G3", "Panasonic DMC-G5", "Panasonic DMC-G6", "Panasonic DMC-G7/G70", "Panasonic DMC-G8/80/81/85", "Panasonic DC-G9", "Panasonic DMC-GF1", "Panasonic DMC-GF2", "Panasonic DMC-GF3", "Panasonic DMC-GF5", "Panasonic DMC-GF6", "Panasonic DMC-GF7", "Panasonic DC-GF10/GF90", "Panasonic DMC-GH1", "Panasonic DMC-GH2", "Panasonic DMC-GH3", "Panasonic DMC-GH4", "Panasonic AG-GH4", "Panasonic DC-GH5", "Panasonic DMC-GM1", "Panasonic DMC-GM1s", "Panasonic DMC-GM5", "Panasonic DMC-GX1", "Panasonic DMC-GX7", "Panasonic DMC-GX8", "Panasonic DC-GX9", "Panasonic DMC-GX80/85", "Panasonic DC-GX800/850/GF9", "Panasonic DMC-L1", "Panasonic DMC-L10", "Panasonic DMC-LC1", "Panasonic DMC-LF1", "Panasonic DMC-LX1", "Panasonic DMC-LX2", "Panasonic DMC-LX3", "Panasonic DMC-LX5", "Panasonic DMC-LX7", "Panasonic DMC-LX9/10/15", "Panasonic DMC-LX100", "Panasonic DMC-TZ60/61/SZ40", "Panasonic DMC-TZ70/71/ZS50", "Panasonic DMC-TZ80/81/85/ZS60", "Panasonic DC-ZS70 (DC-TZ90/91/92, DC-T93)", "Panasonic DC-TZ100/101/ZS100", "Panasonic DC-TZ200/ZS200", "PARROT Bebop 2", "PARROT Bebop Drone", "Pentax *ist D", "Pentax *ist DL", "Pentax *ist DL2", "Pentax *ist DS", "Pentax *ist DS2", "Pentax GR", "Pentax K10D", "Pentax K20D", "Pentax K100D", "Pentax K100D Super", "Pentax K110D", "Pentax K200D", "Pentax K2000/K-m", "Pentax KP", "Pentax K-x", "Pentax K-r", "Pentax K-01", "Pentax K-1", "Pentax K-3", "Pentax K-3 II", "Pentax K-30", "Pentax K-5", "Pentax K-5 II", "Pentax K-5 IIs", "Pentax K-50", "Pentax K-500", "Pentax K-7", "Pentax K-70", "Pentax K-S1", "Pentax K-S2", "Pentax MX-1", "Pentax Q", "Pentax Q7", "Pentax Q10", "Pentax QS-1", "Pentax Optio S", "Pentax Optio S4", "Pentax Optio 33WR", "Pentax Optio 750Z", "Pentax 645D", "Pentax 645Z", "PhaseOne IQ140", "PhaseOne IQ150", "PhaseOne IQ160", "PhaseOne IQ180", "PhaseOne IQ180 IR", "PhaseOne IQ250", "PhaseOne IQ260", "PhaseOne IQ260 Achromatic", "PhaseOne IQ280", "PhaseOne IQ3 50MP", "PhaseOne IQ3 60MP", "PhaseOne IQ3 80MP", "PhaseOne IQ3 100MP", "PhaseOne IQ3 100MP Trichromatic", "PhaseOne LightPhase", "PhaseOne Achromatic+", "PhaseOne H 10", "PhaseOne H 20", "PhaseOne H 25", "PhaseOne P 20", "PhaseOne P 20+", "PhaseOne P 21", "PhaseOne P 25", "PhaseOne P 25+", "PhaseOne P 30", "PhaseOne P 30+", "PhaseOne P 40+", "PhaseOne P 45", "PhaseOne P 45+", "PhaseOne P 65", "PhaseOne P 65+", "Photron BC2-HD", "Pixelink A782", "Polaroid x530", "RaspberryPi Camera", "RaspberryPi Camera V2", "Ricoh GR", "Ricoh GR Digital", "Ricoh GR Digital II", "Ricoh GR Digital III", "Ricoh GR Digital IV", "Ricoh GR II", "Ricoh GX100", "Ricoh GX200", "Ricoh GXR MOUNT A12", "Ricoh GXR MOUNT A16 24-85mm F3.5-5.5", "Ricoh GXR, S10 24-72mm F2.5-4.4 VC", "Ricoh GXR, GR A12 50mm F2.5 MACRO", "Ricoh GXR, GR LENS A12 28mm F2.5", "Ricoh GXR, GXR P10", #ifndef NO_JASPER "Redcode R3D format", #endif "Rollei d530flex", "RoverShot 3320af", "Samsung EX1", "Samsung EX2F", "Samsung GX-1L", "Samsung GX-1S", "Samsung GX10", "Samsung GX20", "Samsung Galaxy Nexus", "Samsung Galaxy NX (EK-GN120)", "Samsung Galaxy S3", "Samsung Galaxy S6 (SM-G920F)", "Samsung Galaxy S7", "Samsung Galaxy S7 Edge", "Samsung Galaxy S8 (SM-G950U)", "Samsung NX1", "Samsung NX5", "Samsung NX10", "Samsung NX11", "Samsung NX100", "Samsung NX1000", "Samsung NX1100", "Samsung NX20", "Samsung NX200", "Samsung NX210", "Samsung NX2000", "Samsung NX30", "Samsung NX300", "Samsung NX300M", "Samsung NX3000", "Samsung NX500", "Samsung NX mini", "Samsung Pro815", "Samsung WB550", "Samsung WB2000", "Samsung S85 (hacked)", "Samsung S850 (hacked)", "Sarnoff 4096x5440", "Seitz 6x17", "Seitz Roundshot D3", "Seitz Roundshot D2X", "Seitz Roundshot D2Xs", "Sigma SD9 (raw decode only)", "Sigma SD10 (raw decode only)", "Sigma SD14 (raw decode only)", "Sigma SD15 (raw decode only)", "Sigma SD1", "Sigma SD1 Merill", "Sigma DP1", "Sigma DP1 Merill", "Sigma DP1S", "Sigma DP1X", "Sigma DP2", "Sigma DP2 Merill", "Sigma DP2S", "Sigma DP2X", "Sigma DP3 Merill", "Sigma dp0 Quattro", "Sigma dp1 Quattro", "Sigma dp2 Quattro", "Sigma dp3 Quattro", "Sigma sd Quattro", "Sigma sd Quattro H", "Sinar eMotion 22", "Sinar eMotion 54", "Sinar eSpirit 65", "Sinar eMotion 75", "Sinar eVolution 75", "Sinar 3072x2048", "Sinar 4080x4080", "Sinar 4080x5440", "Sinar STI format", "Sinar Sinarback 54", "SMaL Ultra-Pocket 3", "SMaL Ultra-Pocket 4", "SMaL Ultra-Pocket 5", "Sony A7", "Sony A7 II", "Sony A7R", "Sony A7R II", "Sony A7R III", "Sony A7S", "Sony A7S II", "Sony A9", "Sony ILCA-68 (A68)", "Sony ILCA-77M2 (A77-II)", "Sony ILCA-99M2 (A99-II)", "Sony ILCE-3000", "Sony ILCE-5000", "Sony ILCE-5100", "Sony ILCE-6000", "Sony ILCE-6300", "Sony ILCE-6500", "Sony ILCE-QX1", "Sony DSC-F828", "Sony DSC-R1", "Sony DSC-RX0", "Sony DSC-RX1", "Sony DSC-RX1R", "Sony DSC-RX1R II", "Sony DSC-RX10", "Sony DSC-RX10II", "Sony DSC-RX10III", "Sony DSC-RX10IV", "Sony DSC-RX100", "Sony DSC-RX100II", "Sony DSC-RX100III", "Sony DSC-RX100IV", "Sony DSC-RX100V", "Sony DSC-V3", "Sony DSLR-A100", "Sony DSLR-A200", "Sony DSLR-A230", "Sony DSLR-A290", "Sony DSLR-A300", "Sony DSLR-A330", "Sony DSLR-A350", "Sony DSLR-A380", "Sony DSLR-A390", "Sony DSLR-A450", "Sony DSLR-A500", "Sony DSLR-A550", "Sony DSLR-A560", "Sony DSLR-A580", "Sony DSLR-A700", "Sony DSLR-A850", "Sony DSLR-A900", "Sony NEX-3", "Sony NEX-3N", "Sony NEX-5", "Sony NEX-5N", "Sony NEX-5R", "Sony NEX-5T", "Sony NEX-6", "Sony NEX-7", "Sony NEX-C3", "Sony NEX-F3", "Sony NEX-VG20", "Sony NEX-VG30", "Sony NEX-VG900", "Sony SLT-A33", "Sony SLT-A35", "Sony SLT-A37", "Sony SLT-A55V", "Sony SLT-A57", "Sony SLT-A58", "Sony SLT-A65V", "Sony SLT-A77V", "Sony SLT-A99V", "Sony XCD-SX910CR", "Sony IMX135-mipi 13mp", "Sony IMX135-QCOM", "Sony IMX072-mipi", "Sony IMX214", "Sony IMX219", "Sony IMX230", "Sony IMX298-mipi 16mp", "Sony IMX219-mipi 8mp", "Sony Xperia L", "STV680 VGA", "PtGrey GRAS-50S5C", "JaiPulnix BB-500CL", "JaiPulnix BB-500GE", "SVS SVS625CL", "Yi M1", "YUNEEC CGO3", "YUNEEC CGO3P", "YUNEEC CGO4", "Xiaomi MI3", "Xiaomi RedMi Note3 Pro", "Xiaoyi YIAC3 (YI 4k)", NULL }; // clang-format on const char **LibRaw::cameraList() { return static_camera_list; } int LibRaw::cameraCount() { return (sizeof(static_camera_list) / sizeof(static_camera_list[0])) - 1; } const char *LibRaw::strprogress(enum LibRaw_progress p) { switch (p) { case LIBRAW_PROGRESS_START: return "Starting"; case LIBRAW_PROGRESS_OPEN: return "Opening file"; case LIBRAW_PROGRESS_IDENTIFY: return "Reading metadata"; case LIBRAW_PROGRESS_SIZE_ADJUST: return "Adjusting size"; case LIBRAW_PROGRESS_LOAD_RAW: return "Reading RAW data"; case LIBRAW_PROGRESS_REMOVE_ZEROES: return "Clearing zero values"; case LIBRAW_PROGRESS_BAD_PIXELS: return "Removing dead pixels"; case LIBRAW_PROGRESS_DARK_FRAME: return "Subtracting dark frame data"; case LIBRAW_PROGRESS_FOVEON_INTERPOLATE: return "Interpolating Foveon sensor data"; case LIBRAW_PROGRESS_SCALE_COLORS: return "Scaling colors"; case LIBRAW_PROGRESS_PRE_INTERPOLATE: return "Pre-interpolating"; case LIBRAW_PROGRESS_INTERPOLATE: return "Interpolating"; case LIBRAW_PROGRESS_MIX_GREEN: return "Mixing green channels"; case LIBRAW_PROGRESS_MEDIAN_FILTER: return "Median filter"; case LIBRAW_PROGRESS_HIGHLIGHTS: return "Highlight recovery"; case LIBRAW_PROGRESS_FUJI_ROTATE: return "Rotating Fuji diagonal data"; case LIBRAW_PROGRESS_FLIP: return "Flipping image"; case LIBRAW_PROGRESS_APPLY_PROFILE: return "ICC conversion"; case LIBRAW_PROGRESS_CONVERT_RGB: return "Converting to RGB"; case LIBRAW_PROGRESS_STRETCH: return "Stretching image"; case LIBRAW_PROGRESS_THUMB_LOAD: return "Loading thumbnail"; default: return "Some strange things"; } } #undef ID #include "../internal/libraw_x3f.cpp" void x3f_clear(void *p) { x3f_delete((x3f_t *)p); } void utf2char(utf16_t *str, char *buffer, unsigned bufsz) { if(bufsz<1) return; buffer[bufsz-1] = 0; char *b = buffer; while (*str != 0x00 && --bufsz>0) { char *chr = (char *)str; *b++ = *chr; str++; } *b = 0; } static void *lr_memmem(const void *l, size_t l_len, const void *s, size_t s_len) { register char *cur, *last; const char *cl = (const char *)l; const char *cs = (const char *)s; /* we need something to compare */ if (l_len == 0 || s_len == 0) return NULL; /* "s" must be smaller or equal to "l" */ if (l_len < s_len) return NULL; /* special case where s_len == 1 */ if (s_len == 1) return (void *)memchr(l, (int)*cs, l_len); /* the last position where its possible to find "s" in "l" */ last = (char *)cl + l_len - s_len; for (cur = (char *)cl; cur <= last; cur++) if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) return cur; return NULL; } void LibRaw::parse_x3f() { x3f_t *x3f = x3f_new_from_file(libraw_internal_data.internal_data.input); if (!x3f) return; _x3f_data = x3f; x3f_header_t *H = NULL; x3f_directory_section_t *DS = NULL; H = &x3f->header; // Parse RAW size from RAW section x3f_directory_entry_t *DE = x3f_get_raw(x3f); if (!DE) return; imgdata.sizes.flip = H->rotation; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.sizes.raw_width = ID->columns; imgdata.sizes.raw_height = ID->rows; // Parse other params from property section DE = x3f_get_prop(x3f); if ((x3f_load_data(x3f, DE) == X3F_OK)) { // Parse property list DEH = &DE->header; x3f_property_list_t *PL = &DEH->data_subsection.property_list; utf16_t *datap = (utf16_t*) PL->data; uint32_t maxitems = PL->data_size/sizeof(utf16_t); if (PL->property_table.size != 0) { int i; x3f_property_t *P = PL->property_table.element; for (i = 0; i < PL->num_properties; i++) { char name[100], value[100]; int noffset = (P[i].name - datap); int voffset = (P[i].value - datap); if(noffset < 0 || noffset>maxitems || voffset<0 || voffset>maxitems) throw LIBRAW_EXCEPTION_IO_CORRUPT; int maxnsize = maxitems - (P[i].name - datap); int maxvsize = maxitems - (P[i].value - datap); utf2char(P[i].name, name,MIN(maxnsize,sizeof(name))); utf2char(P[i].value, value,MIN(maxvsize,sizeof(value))); if (!strcmp(name, "ISO")) imgdata.other.iso_speed = atoi(value); if (!strcmp(name, "CAMMANUF")) strcpy(imgdata.idata.make, value); if (!strcmp(name, "CAMMODEL")) strcpy(imgdata.idata.model, value); if (!strcmp(name, "CAMSERIAL")) strcpy(imgdata.shootinginfo.BodySerial, value); if (!strcmp(name, "WB_DESC")) strcpy(imgdata.color.model2, value); if (!strcmp(name, "TIME")) imgdata.other.timestamp = atoi(value); if (!strcmp(name, "SHUTTER")) imgdata.other.shutter = atof(value); if (!strcmp(name, "APERTURE")) imgdata.other.aperture = atof(value); if (!strcmp(name, "FLENGTH")) imgdata.other.focal_len = atof(value); if (!strcmp(name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp(name, "IMAGERTEMP")) imgdata.other.SensorTemperature = atof(value); if (!strcmp(name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp(name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp(name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff imgdata.color.maximum = 0x3fff; // To be reset by color table libraw_internal_data.unpacker_data.order = 0x4949; } } else { // No property list if (imgdata.sizes.raw_width == 5888 || imgdata.sizes.raw_width == 2944 || imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328 || imgdata.sizes.raw_width == 5504 || imgdata.sizes.raw_width == 2752) // Quattro { imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff libraw_internal_data.unpacker_data.order = 0x4949; strcpy(imgdata.idata.make, "SIGMA"); #if 1 // Try to find model number in first 2048 bytes; int pos = libraw_internal_data.internal_data.input->tell(); libraw_internal_data.internal_data.input->seek(0, SEEK_SET); unsigned char buf[2048]; libraw_internal_data.internal_data.input->read(buf, 2048, 1); libraw_internal_data.internal_data.input->seek(pos, SEEK_SET); unsigned char *fnd = (unsigned char *)lr_memmem(buf, 2048, "SIGMA dp", 8); unsigned char *fndsd = (unsigned char *)lr_memmem(buf, 2048, "sd Quatt", 8); if (fnd) { unsigned char *nm = fnd + 8; snprintf(imgdata.idata.model, 64, "dp%c Quattro", *nm <= '9' && *nm >= '0' ? *nm : '2'); } else if (fndsd) { snprintf(imgdata.idata.model, 64, "%s", fndsd); } else #endif if (imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328) strcpy(imgdata.idata.model, "sd Quattro H"); else strcpy(imgdata.idata.model, "dp2 Quattro"); } // else } // Try to get thumbnail data LibRaw_thumbnail_formats format = LIBRAW_THUMBNAIL_UNKNOWN; if ((DE = x3f_get_thumb_jpeg(x3f))) { format = LIBRAW_THUMBNAIL_JPEG; } else if ((DE = x3f_get_thumb_plain(x3f))) { format = LIBRAW_THUMBNAIL_BITMAP; } if (DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; imgdata.thumbnail.tformat = format; libraw_internal_data.internal_data.toffset = DE->input.offset; write_thumb = &LibRaw::x3f_thumb_loader; } } INT64 LibRaw::x3f_thumb_size() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return -1; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return -1; int64_t p = x3f_load_data_size(x3f, DE); if (p < 0 || p > 0xffffffff) return -1; return p; } catch (...) { return -1; } } void LibRaw::x3f_thumb_loader() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return; if (X3F_OK != x3f_load_data(x3f, DE)) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_JPEG) { imgdata.thumbnail.thumb = (char *)malloc(ID->data_size); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); memmove(imgdata.thumbnail.thumb, ID->data, ID->data_size); imgdata.thumbnail.tlength = ID->data_size; } else if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_BITMAP) { imgdata.thumbnail.tlength = ID->columns * ID->rows * 3; imgdata.thumbnail.thumb = (char *)malloc(ID->columns * ID->rows * 3); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); char *src0 = (char *)ID->data; for (int row = 0; row < ID->rows; row++) { int offset = row * ID->row_stride; if (offset + ID->columns * 3 > ID->data_size) break; char *dest = &imgdata.thumbnail.thumb[row * ID->columns * 3]; char *src = &src0[offset]; memmove(dest, src, ID->columns * 3); } } } catch (...) { // do nothing } } static inline uint32_t _clampbits(int x, uint32_t n) { uint32_t _y_temp; if ((_y_temp = x >> n)) x = ~_y_temp >> (32 - n); return x; } void LibRaw::x3f_dpq_interpolate_rg() { int w = imgdata.sizes.raw_width / 2; int h = imgdata.sizes.raw_height / 2; unsigned short *image = (ushort *)imgdata.rawdata.color3_image; for (int color = 0; color < 2; color++) { for (int y = 2; y < (h - 2); y++) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * (y * 2) + color]; // dst[1] uint16_t row0_3 = row0[3]; uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y * 2 + 1) + color]; // dst1[1] uint16_t row1_3 = row1[3]; for (int x = 2; x < (w - 2); x++) { row1[0] = row1[3] = row0[3] = row0[0]; row0 += 6; row1 += 6; } } } } #define _ABS(a) ((a) < 0 ? -(a) : (a)) #undef CLIP #define CLIP(value, high) ((value) > (high) ? (high) : (value)) void LibRaw::x3f_dpq_interpolate_af(int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = 0; y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { if (y < imgdata.rawdata.sizes.top_margin) continue; if (y < scale) continue; if (y > imgdata.rawdata.sizes.raw_height - scale) break; uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже for (int x = 0; x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { if (x < imgdata.rawdata.sizes.left_margin) continue; if (x < scale) continue; if (x > imgdata.rawdata.sizes.raw_width - scale) break; uint16_t *pixel0 = &row0[x * 3]; uint16_t *pixel_top = &row_minus[x * 3]; uint16_t *pixel_bottom = &row_plus[x * 3]; uint16_t *pixel_left = &row0[(x - scale) * 3]; uint16_t *pixel_right = &row0[(x + scale) * 3]; uint16_t *pixf = pixel_top; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_bottom[2] - pixel0[2])) pixf = pixel_bottom; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_left[2] - pixel0[2])) pixf = pixel_left; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_right[2] - pixel0[2])) pixf = pixel_right; int blocal = pixel0[2], bnear = pixf[2]; if (blocal < imgdata.color.black + 16 || bnear < imgdata.color.black + 16) { if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; pixel0[0] = CLIP((pixel0[0] - imgdata.color.black) * 4 + imgdata.color.black, 16383); pixel0[1] = CLIP((pixel0[1] - imgdata.color.black) * 4 + imgdata.color.black, 16383); } else { float multip = float(bnear - imgdata.color.black) / float(blocal - imgdata.color.black); if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; float pixf0 = pixf[0]; if (pixf0 < imgdata.color.black) pixf0 = imgdata.color.black; float pixf1 = pixf[1]; if (pixf1 < imgdata.color.black) pixf1 = imgdata.color.black; pixel0[0] = CLIP(((float(pixf0 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[0] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); pixel0[1] = CLIP(((float(pixf1 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[1] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); // pixel0[1] = float(pixf[1]-imgdata.color.black)*multip + imgdata.color.black; } } } } void LibRaw::x3f_dpq_interpolate_af_sd(int xstart, int ystart, int xend, int yend, int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = ystart; y < yend && y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y + 1)]; // Следующая строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже AF-point (scale=2 -> ниже row1 uint16_t *row_minus1 = &image[imgdata.sizes.raw_width * 3 * (y - 1)]; for (int x = xstart; x < xend && x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { uint16_t *pixel00 = &row0[x * 3]; // Current pixel float sumR = 0.f, sumG = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumR += row_minus[(x + xx) * 3]; sumR += row_plus[(x + xx) * 3]; sumG += row_minus[(x + xx) * 3 + 1]; sumG += row_plus[(x + xx) * 3 + 1]; cnt += 1.f; if (xx) { cnt += 1.f; sumR += row0[(x + xx) * 3]; sumG += row0[(x + xx) * 3 + 1]; } } pixel00[0] = sumR / 8.f; pixel00[1] = sumG / 8.f; if (scale == 2) { uint16_t *pixel0B = &row0[x * 3 + 3]; // right pixel uint16_t *pixel1B = &row1[x * 3 + 3]; // right pixel float sumG0 = 0, sumG1 = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumG0 += row_minus1[(x + xx) * 3 + 2]; sumG1 += row_plus[(x + xx) * 3 + 2]; cnt += 1.f; if (xx) { sumG0 += row0[(x + xx) * 3 + 2]; sumG1 += row1[(x + xx) * 3 + 2]; cnt += 1.f; } } pixel0B[2] = sumG0 / cnt; pixel1B[2] = sumG1 / cnt; } // uint16_t* pixel10 = &row1[x*3]; // Pixel below current // uint16_t* pixel_bottom = &row_plus[x*3]; } } } void LibRaw::x3f_load_raw() { // already in try/catch int raise_error = 0; x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set if (X3F_OK == x3f_load_data(x3f, x3f_get_raw(x3f))) { x3f_directory_entry_t *DE = x3f_get_raw(x3f); x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_quattro_t *Q = ID->quattro; x3f_huffman_t *HUF = ID->huffman; x3f_true_t *TRU = ID->tru; uint16_t *data = NULL; if (ID->rows != S.raw_height || ID->columns != S.raw_width) { raise_error = 1; goto end; } if (HUF != NULL) data = HUF->x3rgb16.data; if (TRU != NULL) data = TRU->x3rgb16.data; if (data == NULL) { raise_error = 1; goto end; } size_t datasize = S.raw_height * S.raw_width * 3 * sizeof(unsigned short); S.raw_pitch = S.raw_width * 3 * sizeof(unsigned short); if (!(imgdata.rawdata.raw_alloc = malloc(datasize))) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (HUF) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && (!Q || !Q->quattro_layout)) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && Q) { // Move quattro data in place // R/B plane for (int prow = 0; prow < TRU->x3rgb16.rows && prow < S.raw_height / 2; prow++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[prow * 2 * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow)[3] = (unsigned short(*)[3]) & data[prow * TRU->x3rgb16.row_stride]; for (int pcol = 0; pcol < TRU->x3rgb16.columns && pcol < S.raw_width / 2; pcol++) { destrow[pcol * 2][0] = srcrow[pcol][0]; destrow[pcol * 2][1] = srcrow[pcol][1]; } } for (int row = 0; row < Q->top16.rows && row < S.raw_height; row++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[row * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow) = (unsigned short *)&Q->top16.data[row * Q->top16.columns]; for (int col = 0; col < Q->top16.columns && col < S.raw_width; col++) destrow[col][2] = srcrow[col]; } } #if 1 if (TRU && Q && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF)) { if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3672) // dpN Quattro normal { x3f_dpq_interpolate_af(32, 8, 2); } else if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3776) // sd Quattro normal raw { x3f_dpq_interpolate_af_sd(216, 464, imgdata.sizes.raw_width - 1, 3312, 16, 32, 2); } else if (imgdata.sizes.raw_width == 6656 && imgdata.sizes.raw_height == 4480) // sd Quattro H normal raw { x3f_dpq_interpolate_af_sd(232, 592, imgdata.sizes.raw_width - 1, 3920, 16, 32, 2); } else if (imgdata.sizes.raw_width == 3328 && imgdata.sizes.raw_height == 2240) // sd Quattro H half size { x3f_dpq_interpolate_af_sd(116, 296, imgdata.sizes.raw_width - 1, 2200, 8, 16, 1); } else if (imgdata.sizes.raw_width == 5504 && imgdata.sizes.raw_height == 3680) // sd Quattro H APS-C raw { x3f_dpq_interpolate_af_sd(8, 192, imgdata.sizes.raw_width - 1, 3185, 16, 32, 2); } else if (imgdata.sizes.raw_width == 2752 && imgdata.sizes.raw_height == 1840) // sd Quattro H APS-C half size { x3f_dpq_interpolate_af_sd(4, 96, imgdata.sizes.raw_width - 1, 1800, 8, 16, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1836) // dpN Quattro small raw { x3f_dpq_interpolate_af(16, 4, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1888) // sd Quattro small { x3f_dpq_interpolate_af_sd(108, 232, imgdata.sizes.raw_width - 1, 1656, 8, 16, 1); } } #endif if (TRU && Q && Q->quattro_layout && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATERG)) x3f_dpq_interpolate_rg(); } else raise_error = 1; end: if (raise_error) throw LIBRAW_EXCEPTION_IO_CORRUPT; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_94_2
crossvul-cpp_data_good_4256_3
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ESTreeIRGen.h" #include "llvh/ADT/SmallString.h" namespace hermes { namespace irgen { //===----------------------------------------------------------------------===// // FunctionContext FunctionContext::FunctionContext( ESTreeIRGen *irGen, Function *function, sem::FunctionInfo *semInfo) : irGen_(irGen), semInfo_(semInfo), oldContext_(irGen->functionContext_), builderSaveState_(irGen->Builder), function(function), scope(irGen->nameTable_) { irGen->functionContext_ = this; // Initialize it to LiteraUndefined by default to avoid corner cases. this->capturedNewTarget = irGen->Builder.getLiteralUndefined(); if (semInfo_) { // Allocate the label table. Each label definition will be encountered in // the AST before it is referenced (because of the nature of JavaScript), at // which point we will initialize the GotoLabel structure with basic blocks // targets. labels_.resize(semInfo_->labelCount); } } FunctionContext::~FunctionContext() { irGen_->functionContext_ = oldContext_; } Identifier FunctionContext::genAnonymousLabelName(StringRef hint) { llvh::SmallString<16> buf; llvh::raw_svector_ostream nameBuilder{buf}; nameBuilder << "?anon_" << anonymousLabelCounter++ << "_" << hint; return function->getContext().getIdentifier(nameBuilder.str()); } //===----------------------------------------------------------------------===// // ESTreeIRGen void ESTreeIRGen::genFunctionDeclaration( ESTree::FunctionDeclarationNode *func) { if (func->_async) { Builder.getModule()->getContext().getSourceErrorManager().error( func->getSourceRange(), Twine("async functions are unsupported")); return; } // Find the name of the function. Identifier functionName = getNameFieldFromID(func->_id); LLVM_DEBUG(dbgs() << "IRGen function \"" << functionName << "\".\n"); auto *funcStorage = nameTable_.lookup(functionName); assert( funcStorage && "function declaration variable should have been hoisted"); Function *newFunc = func->_generator ? genGeneratorFunction(functionName, nullptr, func) : genES5Function(functionName, nullptr, func); // Store the newly created closure into a frame variable with the same name. auto *newClosure = Builder.createCreateFunctionInst(newFunc); emitStore(Builder, newClosure, funcStorage, true); } Value *ESTreeIRGen::genFunctionExpression( ESTree::FunctionExpressionNode *FE, Identifier nameHint) { if (FE->_async) { Builder.getModule()->getContext().getSourceErrorManager().error( FE->getSourceRange(), Twine("async functions are unsupported")); return Builder.getLiteralUndefined(); } LLVM_DEBUG( dbgs() << "Creating anonymous closure. " << Builder.getInsertionBlock()->getParent()->getInternalName() << ".\n"); NameTableScopeTy newScope(nameTable_); Variable *tempClosureVar = nullptr; Identifier originalNameIden = nameHint; if (FE->_id) { auto closureName = genAnonymousLabelName("closure"); tempClosureVar = Builder.createVariable( curFunction()->function->getFunctionScope(), Variable::DeclKind::Var, closureName); // Insert the synthesized variable into the name table, so it can be // looked up internally as well. nameTable_.insertIntoScope( &curFunction()->scope, tempClosureVar->getName(), tempClosureVar); // Alias the lexical name to the synthesized variable. originalNameIden = getNameFieldFromID(FE->_id); nameTable_.insert(originalNameIden, tempClosureVar); } Function *newFunc = FE->_generator ? genGeneratorFunction(originalNameIden, tempClosureVar, FE) : genES5Function(originalNameIden, tempClosureVar, FE); Value *closure = Builder.createCreateFunctionInst(newFunc); if (tempClosureVar) emitStore(Builder, closure, tempClosureVar, true); return closure; } Value *ESTreeIRGen::genArrowFunctionExpression( ESTree::ArrowFunctionExpressionNode *AF, Identifier nameHint) { LLVM_DEBUG( dbgs() << "Creating arrow function. " << Builder.getInsertionBlock()->getParent()->getInternalName() << ".\n"); if (AF->_async) { Builder.getModule()->getContext().getSourceErrorManager().error( AF->getSourceRange(), Twine("async functions are unsupported")); return Builder.getLiteralUndefined(); } auto *newFunc = Builder.createFunction( nameHint, Function::DefinitionKind::ES6Arrow, ESTree::isStrict(AF->strictness), AF->getSourceRange()); { FunctionContext newFunctionContext{this, newFunc, AF->getSemInfo()}; // Propagate captured "this", "new.target" and "arguments" from parents. auto *prev = curFunction()->getPreviousContext(); curFunction()->capturedThis = prev->capturedThis; curFunction()->capturedNewTarget = prev->capturedNewTarget; curFunction()->capturedArguments = prev->capturedArguments; emitFunctionPrologue( AF, Builder.createBasicBlock(newFunc), InitES5CaptureState::No, DoEmitParameters::Yes); genStatement(AF->_body); emitFunctionEpilogue(Builder.getLiteralUndefined()); } // Emit CreateFunctionInst after we have restored the builder state. return Builder.createCreateFunctionInst(newFunc); } #ifndef HERMESVM_LEAN namespace { ESTree::NodeKind getLazyFunctionKind(ESTree::FunctionLikeNode *node) { if (node->isMethodDefinition) { // This is not a regular function expression but getter/setter. // If we want to reparse it later, we have to start from an // identifier and not from a 'function' keyword. return ESTree::NodeKind::Property; } return node->getKind(); } } // namespace Function *ESTreeIRGen::genES5Function( Identifier originalName, Variable *lazyClosureAlias, ESTree::FunctionLikeNode *functionNode, bool isGeneratorInnerFunction) { assert(functionNode && "Function AST cannot be null"); auto *body = ESTree::getBlockStatement(functionNode); assert(body && "body of ES5 function cannot be null"); Function *newFunction = isGeneratorInnerFunction ? Builder.createGeneratorInnerFunction( originalName, Function::DefinitionKind::ES5Function, ESTree::isStrict(functionNode->strictness), functionNode->getSourceRange(), /* insertBefore */ nullptr) : Builder.createFunction( originalName, Function::DefinitionKind::ES5Function, ESTree::isStrict(functionNode->strictness), functionNode->getSourceRange(), /* isGlobal */ false, /* insertBefore */ nullptr); newFunction->setLazyClosureAlias(lazyClosureAlias); if (auto *bodyBlock = llvh::dyn_cast<ESTree::BlockStatementNode>(body)) { if (bodyBlock->isLazyFunctionBody) { // Set the AST position and variable context so we can continue later. newFunction->setLazyScope(saveCurrentScope()); auto &lazySource = newFunction->getLazySource(); lazySource.bufferId = bodyBlock->bufferId; lazySource.nodeKind = getLazyFunctionKind(functionNode); lazySource.isGeneratorInnerFunction = isGeneratorInnerFunction; lazySource.functionRange = functionNode->getSourceRange(); // Set the function's .length. newFunction->setExpectedParamCountIncludingThis( countExpectedArgumentsIncludingThis(functionNode)); return newFunction; } } FunctionContext newFunctionContext{ this, newFunction, functionNode->getSemInfo()}; if (isGeneratorInnerFunction) { // StartGeneratorInst // ResumeGeneratorInst // at the beginning of the function, to allow for the first .next() call. auto *initGenBB = Builder.createBasicBlock(newFunction); Builder.setInsertionBlock(initGenBB); Builder.createStartGeneratorInst(); auto *prologueBB = Builder.createBasicBlock(newFunction); auto *prologueResumeIsReturn = Builder.createAllocStackInst( genAnonymousLabelName("isReturn_prologue")); genResumeGenerator(nullptr, prologueResumeIsReturn, prologueBB); if (hasSimpleParams(functionNode)) { // If there are simple params, then we don't need an extra yield/resume. // They can simply be initialized on the first call to `.next`. Builder.setInsertionBlock(prologueBB); emitFunctionPrologue( functionNode, prologueBB, InitES5CaptureState::Yes, DoEmitParameters::Yes); } else { // If there are non-simple params, then we must add a new yield/resume. // The `.next()` call will occur once in the outer function, before // the iterator is returned to the caller of the `function*`. auto *entryPointBB = Builder.createBasicBlock(newFunction); auto *entryPointResumeIsReturn = Builder.createAllocStackInst(genAnonymousLabelName("isReturn_entry")); // Initialize parameters. Builder.setInsertionBlock(prologueBB); emitFunctionPrologue( functionNode, prologueBB, InitES5CaptureState::Yes, DoEmitParameters::Yes); Builder.createSaveAndYieldInst( Builder.getLiteralUndefined(), entryPointBB); // Actual entry point of function from the caller's perspective. Builder.setInsertionBlock(entryPointBB); genResumeGenerator( nullptr, entryPointResumeIsReturn, Builder.createBasicBlock(newFunction)); } } else { emitFunctionPrologue( functionNode, Builder.createBasicBlock(newFunction), InitES5CaptureState::Yes, DoEmitParameters::Yes); } genStatement(body); emitFunctionEpilogue(Builder.getLiteralUndefined()); return curFunction()->function; } #endif Function *ESTreeIRGen::genGeneratorFunction( Identifier originalName, Variable *lazyClosureAlias, ESTree::FunctionLikeNode *functionNode) { assert(functionNode && "Function AST cannot be null"); // Build the outer function which creates the generator. // Does not have an associated source range. auto *outerFn = Builder.createGeneratorFunction( originalName, Function::DefinitionKind::ES5Function, ESTree::isStrict(functionNode->strictness), /* insertBefore */ nullptr); { FunctionContext outerFnContext{this, outerFn, functionNode->getSemInfo()}; // Build the inner function. This must be done in the outerFnContext // since it's lexically considered a child function. auto *innerFn = genES5Function( genAnonymousLabelName(originalName.isValid() ? originalName.str() : ""), lazyClosureAlias, functionNode, true); emitFunctionPrologue( functionNode, Builder.createBasicBlock(outerFn), InitES5CaptureState::Yes, DoEmitParameters::No); // Create a generator function, which will store the arguments. auto *gen = Builder.createCreateGeneratorInst(innerFn); if (!hasSimpleParams(functionNode)) { // If there are non-simple params, step the inner function once to // initialize them. Value *next = Builder.createLoadPropertyInst(gen, "next"); Builder.createCallInst(next, gen, {}); } emitFunctionEpilogue(gen); } return outerFn; } void ESTreeIRGen::initCaptureStateInES5FunctionHelper() { // Capture "this", "new.target" and "arguments" if there are inner arrows. if (!curFunction()->getSemInfo()->containsArrowFunctions) return; auto *scope = curFunction()->function->getFunctionScope(); // "this". curFunction()->capturedThis = Builder.createVariable( scope, Variable::DeclKind::Var, genAnonymousLabelName("this")); emitStore( Builder, Builder.getFunction()->getThisParameter(), curFunction()->capturedThis, true); // "new.target". curFunction()->capturedNewTarget = Builder.createVariable( scope, Variable::DeclKind::Var, genAnonymousLabelName("new.target")); emitStore( Builder, Builder.createGetNewTargetInst(), curFunction()->capturedNewTarget, true); // "arguments". if (curFunction()->getSemInfo()->containsArrowFunctionsUsingArguments) { curFunction()->capturedArguments = Builder.createVariable( scope, Variable::DeclKind::Var, genAnonymousLabelName("arguments")); emitStore( Builder, curFunction()->createArgumentsInst, curFunction()->capturedArguments, true); } } void ESTreeIRGen::emitFunctionPrologue( ESTree::FunctionLikeNode *funcNode, BasicBlock *entry, InitES5CaptureState doInitES5CaptureState, DoEmitParameters doEmitParameters) { auto *newFunc = curFunction()->function; auto *semInfo = curFunction()->getSemInfo(); LLVM_DEBUG( dbgs() << "Hoisting " << (semInfo->varDecls.size() + semInfo->closures.size()) << " variable decls.\n"); Builder.setLocation(newFunc->getSourceRange().Start); // Start pumping instructions into the entry basic block. Builder.setInsertionBlock(entry); // Always insert a CreateArgumentsInst. We will delete it later if it is // unused. curFunction()->createArgumentsInst = Builder.createCreateArgumentsInst(); // Create variable declarations for each of the hoisted variables and // functions. Initialize only the variables to undefined. for (auto decl : semInfo->varDecls) { auto res = declareVariableOrGlobalProperty( newFunc, decl.kind, getNameFieldFromID(decl.identifier)); // If this is not a frame variable or it was already declared, skip. auto *var = llvh::dyn_cast<Variable>(res.first); if (!var || !res.second) continue; // Otherwise, initialize it to undefined. Builder.createStoreFrameInst(Builder.getLiteralUndefined(), var); if (var->getRelatedVariable()) { Builder.createStoreFrameInst( Builder.getLiteralUndefined(), var->getRelatedVariable()); } } for (auto *fd : semInfo->closures) { declareVariableOrGlobalProperty( newFunc, VarDecl::Kind::Var, getNameFieldFromID(fd->_id)); } // Always create the "this" parameter. It needs to be created before we // initialized the ES5 capture state. Builder.createParameter(newFunc, "this"); if (doInitES5CaptureState != InitES5CaptureState::No) initCaptureStateInES5FunctionHelper(); // Construct the parameter list. Create function parameters and register // them in the scope. if (doEmitParameters == DoEmitParameters::Yes) { emitParameters(funcNode); } else { newFunc->setExpectedParamCountIncludingThis( countExpectedArgumentsIncludingThis(funcNode)); } // Generate the code for import declarations before generating the rest of the // body. for (auto importDecl : semInfo->imports) { genImportDeclaration(importDecl); } // Generate and initialize the code for the hoisted function declarations // before generating the rest of the body. for (auto funcDecl : semInfo->closures) { genFunctionDeclaration(funcDecl); } } void ESTreeIRGen::emitParameters(ESTree::FunctionLikeNode *funcNode) { auto *newFunc = curFunction()->function; LLVM_DEBUG(dbgs() << "IRGen function parameters.\n"); // Create a variable for every parameter. for (auto paramDecl : funcNode->getSemInfo()->paramNames) { Identifier paramName = getNameFieldFromID(paramDecl.identifier); LLVM_DEBUG(dbgs() << "Adding parameter: " << paramName << "\n"); auto *paramStorage = Builder.createVariable( newFunc->getFunctionScope(), Variable::DeclKind::Var, paramName); // Register the storage for the parameter. nameTable_.insert(paramName, paramStorage); } // FIXME: T42569352 TDZ for parameters used in initializer expressions. uint32_t paramIndex = uint32_t{0} - 1; for (auto &elem : ESTree::getParams(funcNode)) { ESTree::Node *param = &elem; ESTree::Node *init = nullptr; ++paramIndex; if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(param)) { createLRef(rest->_argument, true) .emitStore(genBuiltinCall( BuiltinMethod::HermesBuiltin_copyRestArgs, Builder.getLiteralNumber(paramIndex))); break; } // Unpack the optional initialization. if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(param)) { param = assign->_left; init = assign->_right; } Identifier formalParamName = llvh::isa<ESTree::IdentifierNode>(param) ? getNameFieldFromID(param) : genAnonymousLabelName("param"); auto *formalParam = Builder.createParameter(newFunc, formalParamName); createLRef(param, true) .emitStore( emitOptionalInitialization(formalParam, init, formalParamName)); } newFunc->setExpectedParamCountIncludingThis( countExpectedArgumentsIncludingThis(funcNode)); } uint32_t ESTreeIRGen::countExpectedArgumentsIncludingThis( ESTree::FunctionLikeNode *funcNode) { // Start at 1 to account for "this". uint32_t count = 1; for (auto &param : ESTree::getParams(funcNode)) { if (llvh::isa<ESTree::AssignmentPatternNode>(param)) { // Found an initializer, stop counting expected arguments. break; } ++count; } return count; } void ESTreeIRGen::emitFunctionEpilogue(Value *returnValue) { if (returnValue) { Builder.setLocation(SourceErrorManager::convertEndToLocation( Builder.getFunction()->getSourceRange())); Builder.createReturnInst(returnValue); } // Delete CreateArgumentsInst if it is unused. if (!curFunction()->createArgumentsInst->hasUsers()) curFunction()->createArgumentsInst->eraseFromParent(); curFunction()->function->clearStatementCount(); } void ESTreeIRGen::genDummyFunction(Function *dummy) { IRBuilder builder{dummy}; builder.createParameter(dummy, "this"); BasicBlock *firstBlock = builder.createBasicBlock(dummy); builder.setInsertionBlock(firstBlock); builder.createUnreachableInst(); builder.createReturnInst(builder.getLiteralUndefined()); } /// Generate a function which immediately throws the specified SyntaxError /// message. Function *ESTreeIRGen::genSyntaxErrorFunction( Module *M, Identifier originalName, SMRange sourceRange, StringRef error) { IRBuilder builder{M}; Function *function = builder.createFunction( originalName, Function::DefinitionKind::ES5Function, true, sourceRange, false); builder.createParameter(function, "this"); BasicBlock *firstBlock = builder.createBasicBlock(function); builder.setInsertionBlock(firstBlock); builder.createThrowInst(builder.createCallInst( emitLoad( builder, builder.createGlobalObjectProperty("SyntaxError", false)), builder.getLiteralUndefined(), builder.getLiteralString(error))); return function; } } // namespace irgen } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_4256_3
crossvul-cpp_data_bad_4259_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/VM/JSObject.h" #include "hermes/VM/BuildMetadata.h" #include "hermes/VM/Callable.h" #include "hermes/VM/HostModel.h" #include "hermes/VM/InternalProperty.h" #include "hermes/VM/JSArray.h" #include "hermes/VM/JSDate.h" #include "hermes/VM/JSProxy.h" #include "hermes/VM/Operations.h" #include "llvh/ADT/SmallSet.h" namespace hermes { namespace vm { ObjectVTable JSObject::vt{ VTable( CellKind::ObjectKind, cellSize<JSObject>(), nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, // externalMemorySize VTable::HeapSnapshotMetadata{HeapSnapshot::NodeType::Object, JSObject::_snapshotNameImpl, JSObject::_snapshotAddEdgesImpl, nullptr, JSObject::_snapshotAddLocationsImpl}), JSObject::_getOwnIndexedRangeImpl, JSObject::_haveOwnIndexedImpl, JSObject::_getOwnIndexedPropertyFlagsImpl, JSObject::_getOwnIndexedImpl, JSObject::_setOwnIndexedImpl, JSObject::_deleteOwnIndexedImpl, JSObject::_checkAllOwnIndexedImpl, }; void ObjectBuildMeta(const GCCell *cell, Metadata::Builder &mb) { // This call is just for debugging and consistency purposes. mb.addJSObjectOverlapSlots(JSObject::numOverlapSlots<JSObject>()); const auto *self = static_cast<const JSObject *>(cell); mb.addField("parent", &self->parent_); mb.addField("class", &self->clazz_); mb.addField("propStorage", &self->propStorage_); // Declare the direct properties. static const char *directPropName[JSObject::DIRECT_PROPERTY_SLOTS] = { "directProp0", "directProp1", "directProp2", "directProp3"}; for (unsigned i = mb.getJSObjectOverlapSlots(); i < JSObject::DIRECT_PROPERTY_SLOTS; ++i) { mb.addField(directPropName[i], self->directProps() + i); } } #ifdef HERMESVM_SERIALIZE void JSObject::serializeObjectImpl( Serializer &s, const GCCell *cell, unsigned overlapSlots) { auto *self = vmcast<const JSObject>(cell); s.writeData(&self->flags_, sizeof(ObjectFlags)); s.writeRelocation(self->parent_.get(s.getRuntime())); s.writeRelocation(self->clazz_.get(s.getRuntime())); // propStorage_ : GCPointer<PropStorage> is also ArrayStorage. Serialize // *propStorage_ with this JSObject. bool hasArray = (bool)self->propStorage_; s.writeInt<uint8_t>(hasArray); if (hasArray) { ArrayStorage::serializeArrayStorage( s, self->propStorage_.get(s.getRuntime())); } // Record the number of overlap slots, so that the deserialization code // doesn't need to keep track of it. s.writeInt<uint8_t>(overlapSlots); for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) { s.writeHermesValue(self->directProps()[i]); } } void ObjectSerialize(Serializer &s, const GCCell *cell) { JSObject::serializeObjectImpl(s, cell, JSObject::numOverlapSlots<JSObject>()); s.endObject(cell); } void ObjectDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::ObjectKind && "Expected JSObject"); void *mem = d.getRuntime()->alloc</*fixedSize*/ true>(cellSize<JSObject>()); auto *obj = new (mem) JSObject(d, &JSObject::vt.base); d.endObject(obj); } JSObject::JSObject(Deserializer &d, const VTable *vtp) : GCCell(&d.getRuntime()->getHeap(), vtp) { d.readData(&flags_, sizeof(ObjectFlags)); d.readRelocation(&parent_, RelocationKind::GCPointer); d.readRelocation(&clazz_, RelocationKind::GCPointer); if (d.readInt<uint8_t>()) { propStorage_.set( d.getRuntime(), ArrayStorage::deserializeArrayStorage(d), &d.getRuntime()->getHeap()); } auto overlapSlots = d.readInt<uint8_t>(); for (size_t i = overlapSlots; i < JSObject::DIRECT_PROPERTY_SLOTS; i++) { d.readHermesValue(&directProps()[i]); } } #endif PseudoHandle<JSObject> JSObject::create( Runtime *runtime, Handle<JSObject> parentHandle) { JSObjectAlloc<JSObject> mem{runtime}; return mem.initToPseudoHandle(new (mem) JSObject( runtime, &vt.base, *parentHandle, runtime->getHiddenClassForPrototypeRaw( *parentHandle, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS), GCPointerBase::NoBarriers())); } PseudoHandle<JSObject> JSObject::create(Runtime *runtime) { JSObjectAlloc<JSObject> mem{runtime}; JSObject *objProto = runtime->objectPrototypeRawPtr; return mem.initToPseudoHandle(new (mem) JSObject( runtime, &vt.base, objProto, runtime->getHiddenClassForPrototypeRaw( objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS), GCPointerBase::NoBarriers())); } PseudoHandle<JSObject> JSObject::create( Runtime *runtime, unsigned propertyCount) { JSObjectAlloc<JSObject> mem{runtime}; JSObject *objProto = runtime->objectPrototypeRawPtr; auto self = mem.initToPseudoHandle(new (mem) JSObject( runtime, &vt.base, objProto, runtime->getHiddenClassForPrototypeRaw( objProto, numOverlapSlots<JSObject>() + ANONYMOUS_PROPERTY_SLOTS), GCPointerBase::NoBarriers())); return runtime->ignoreAllocationFailure( JSObject::allocatePropStorage(std::move(self), runtime, propertyCount)); } PseudoHandle<JSObject> JSObject::create( Runtime *runtime, Handle<HiddenClass> clazz) { auto obj = JSObject::create(runtime, clazz->getNumProperties()); obj->clazz_.set(runtime, *clazz, &runtime->getHeap()); // If the hidden class has index like property, we need to clear the fast path // flag. if (LLVM_UNLIKELY(obj->clazz_.get(runtime)->getHasIndexLikeProperties())) obj->flags_.fastIndexProperties = false; return obj; } void JSObject::initializeLazyObject( Runtime *runtime, Handle<JSObject> lazyObject) { assert(lazyObject->flags_.lazyObject && "object must be lazy"); // object is now assumed to be a regular object. lazyObject->flags_.lazyObject = 0; // only functions can be lazy. assert(vmisa<Callable>(lazyObject.get()) && "unexpected lazy object"); Callable::defineLazyProperties(Handle<Callable>::vmcast(lazyObject), runtime); } ObjectID JSObject::getObjectID(JSObject *self, Runtime *runtime) { if (LLVM_LIKELY(self->flags_.objectID)) return self->flags_.objectID; // Object ID does not yet exist, get next unique global ID.. self->flags_.objectID = runtime->generateNextObjectID(); // Make sure it is not zero. if (LLVM_UNLIKELY(!self->flags_.objectID)) --self->flags_.objectID; return self->flags_.objectID; } CallResult<PseudoHandle<JSObject>> JSObject::getPrototypeOf( PseudoHandle<JSObject> selfHandle, Runtime *runtime) { if (LLVM_LIKELY(!selfHandle->isProxyObject())) { return createPseudoHandle(selfHandle->getParent(runtime)); } return JSProxy::getPrototypeOf( runtime->makeHandle(std::move(selfHandle)), runtime); } namespace { CallResult<bool> proxyOpFlags( Runtime *runtime, PropOpFlags opFlags, const char *msg, CallResult<bool> res) { if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*res && opFlags.getThrowOnError()) { return runtime->raiseTypeError(msg); } return res; } } // namespace CallResult<bool> JSObject::setParent( JSObject *self, Runtime *runtime, JSObject *parent, PropOpFlags opFlags) { if (LLVM_UNLIKELY(self->isProxyObject())) { return proxyOpFlags( runtime, opFlags, "Object is not extensible.", JSProxy::setPrototypeOf( runtime->makeHandle(self), runtime, runtime->makeHandle(parent))); } // ES9 9.1.2 // 4. if (self->parent_.get(runtime) == parent) return true; // 5. if (!self->isExtensible()) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError("Object is not extensible."); } else { return false; } } // 6-8. Check for a prototype cycle. for (JSObject *cur = parent; cur; cur = cur->parent_.get(runtime)) { if (cur == self) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError("Prototype cycle detected"); } else { return false; } } else if (LLVM_UNLIKELY(cur->isProxyObject())) { // TODO this branch should also be used for module namespace and // immutable prototype exotic objects. break; } } // 9. self->parent_.set(runtime, parent, &runtime->getHeap()); // 10. return true; } void JSObject::allocateNewSlotStorage( Handle<JSObject> selfHandle, Runtime *runtime, SlotIndex newSlotIndex, Handle<> valueHandle) { // If it is a direct property, just store the value and we are done. if (LLVM_LIKELY(newSlotIndex < DIRECT_PROPERTY_SLOTS)) { selfHandle->directProps()[newSlotIndex].set( *valueHandle, &runtime->getHeap()); return; } // Make the slot index relative to the indirect storage. newSlotIndex -= DIRECT_PROPERTY_SLOTS; // Allocate a new property storage if not already allocated. if (LLVM_UNLIKELY(!selfHandle->propStorage_)) { // Allocate new storage. assert(newSlotIndex == 0 && "allocated slot must be at end"); auto arrRes = runtime->ignoreAllocationFailure( PropStorage::create(runtime, DEFAULT_PROPERTY_CAPACITY)); selfHandle->propStorage_.set( runtime, vmcast<PropStorage>(arrRes), &runtime->getHeap()); } else if (LLVM_UNLIKELY( newSlotIndex >= selfHandle->propStorage_.get(runtime)->capacity())) { // Reallocate the existing one. assert( newSlotIndex == selfHandle->propStorage_.get(runtime)->size() && "allocated slot must be at end"); auto hnd = runtime->makeMutableHandle(selfHandle->propStorage_); PropStorage::resize(hnd, runtime, newSlotIndex + 1); selfHandle->propStorage_.set(runtime, *hnd, &runtime->getHeap()); } { NoAllocScope scope{runtime}; auto *const propStorage = selfHandle->propStorage_.getNonNull(runtime); if (newSlotIndex >= propStorage->size()) { assert( newSlotIndex == propStorage->size() && "allocated slot must be at end"); PropStorage::resizeWithinCapacity(propStorage, runtime, newSlotIndex + 1); } // If we don't need to resize, just store it directly. propStorage->at(newSlotIndex).set(*valueHandle, &runtime->getHeap()); } } CallResult<PseudoHandle<>> JSObject::getNamedPropertyValue_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<JSObject> propObj, NamedPropertyDescriptor desc) { assert( !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject && "getNamedPropertyValue_RJS cannot be used with proxy objects"); if (LLVM_LIKELY(!desc.flags.accessor)) return createPseudoHandle(getNamedSlotValue(propObj.get(), runtime, desc)); auto *accessor = vmcast<PropertyAccessor>(getNamedSlotValue(propObj.get(), runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return accessor->getter.get(runtime)->executeCall0( runtime->makeHandle(accessor->getter), runtime, selfHandle); } CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<JSObject> propObj, ComputedPropertyDescriptor desc) { assert( !selfHandle->flags_.proxyObject && !propObj->flags_.proxyObject && "getComputedPropertyValue_RJS cannot be used with proxy objects"); if (LLVM_LIKELY(!desc.flags.accessor)) return createPseudoHandle( getComputedSlotValue(propObj.get(), runtime, desc)); auto *accessor = vmcast<PropertyAccessor>( getComputedSlotValue(propObj.get(), runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return accessor->getter.get(runtime)->executeCall0( runtime->makeHandle(accessor->getter), runtime, selfHandle); } CallResult<PseudoHandle<>> JSObject::getComputedPropertyValue_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<JSObject> propObj, ComputedPropertyDescriptor desc, Handle<> nameValHandle) { if (!propObj) { return createPseudoHandle(HermesValue::encodeEmptyValue()); } if (LLVM_LIKELY(!desc.flags.proxyObject)) { return JSObject::getComputedPropertyValue_RJS( selfHandle, runtime, propObj, desc); } CallResult<Handle<>> keyRes = toPropertyKey(runtime, nameValHandle); if (LLVM_UNLIKELY(keyRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } CallResult<bool> hasRes = JSProxy::hasComputed(propObj, runtime, *keyRes); if (LLVM_UNLIKELY(hasRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*hasRes) { return createPseudoHandle(HermesValue::encodeEmptyValue()); } return JSProxy::getComputed(propObj, runtime, *keyRes, selfHandle); } CallResult<Handle<JSArray>> JSObject::getOwnPropertyKeys( Handle<JSObject> selfHandle, Runtime *runtime, OwnKeysFlags okFlags) { assert( (okFlags.getIncludeNonSymbols() || okFlags.getIncludeSymbols()) && "Can't exclude symbols and strings"); if (LLVM_UNLIKELY( selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) { if (selfHandle->flags_.proxyObject) { CallResult<PseudoHandle<JSArray>> proxyRes = JSProxy::ownPropertyKeys(selfHandle, runtime, okFlags); if (LLVM_UNLIKELY(proxyRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return runtime->makeHandle(std::move(*proxyRes)); } assert(selfHandle->flags_.lazyObject && "descriptor flags are impossible"); initializeLazyObject(runtime, selfHandle); } auto range = getOwnIndexedRange(selfHandle.get(), runtime); // Estimate the capacity of the output array. This estimate is only // reasonable for the non-symbol case. uint32_t capacity = okFlags.getIncludeNonSymbols() ? (selfHandle->clazz_.get(runtime)->getNumProperties() + range.second - range.first) : 0; auto arrayRes = JSArray::create(runtime, capacity, 0); if (LLVM_UNLIKELY(arrayRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto array = runtime->makeHandle(std::move(*arrayRes)); // Optional array of SymbolIDs reported via host object API llvh::Optional<Handle<JSArray>> hostObjectSymbols; size_t hostObjectSymbolCount = 0; // If current object is a host object we need to deduplicate its properties llvh::SmallSet<SymbolID::RawType, 16> dedupSet; // Output index. uint32_t index = 0; // Avoid allocating a new handle per element. MutableHandle<> tmpHandle{runtime}; // Number of indexed properties. uint32_t numIndexed = 0; // Regular properties with names that are array indexes are stashed here, if // encountered. llvh::SmallVector<uint32_t, 8> indexNames{}; // Iterate the named properties excluding those which use Symbols. if (okFlags.getIncludeNonSymbols()) { // Get host object property names if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) { assert( range.first == range.second && "Host objects cannot own indexed range"); auto hostSymbolsRes = vmcast<HostObject>(selfHandle.get())->getHostPropertyNames(); if (hostSymbolsRes == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } if ((hostObjectSymbolCount = (**hostSymbolsRes)->getEndIndex()) != 0) { Handle<JSArray> hostSymbols = *hostSymbolsRes; hostObjectSymbols = std::move(hostSymbols); capacity += hostObjectSymbolCount; } } // Iterate the indexed properties. GCScopeMarkerRAII marker{runtime}; for (auto i = range.first; i != range.second; ++i) { auto res = getOwnIndexedPropertyFlags(selfHandle.get(), runtime, i); if (!res) continue; // If specified, check whether it is enumerable. if (!okFlags.getIncludeNonEnumerable() && !res->enumerable) continue; tmpHandle = HermesValue::encodeDoubleValue(i); JSArray::setElementAt(array, runtime, index++, tmpHandle); marker.flush(); } numIndexed = index; HiddenClass::forEachProperty( runtime->makeHandle(selfHandle->clazz_), runtime, [runtime, okFlags, array, hostObjectSymbolCount, &index, &indexNames, &tmpHandle, &dedupSet](SymbolID id, NamedPropertyDescriptor desc) { if (!isPropertyNamePrimitive(id)) { return; } // If specified, check whether it is enumerable. if (!okFlags.getIncludeNonEnumerable()) { if (!desc.flags.enumerable) return; } // Host properties might overlap with the ones recognized by the // hidden class. If we're dealing with a host object then keep track // of hidden class properties for the deduplication purposes. if (LLVM_UNLIKELY(hostObjectSymbolCount > 0)) { dedupSet.insert(id.unsafeGetRaw()); } // Check if this property is an integer index. If it is, we stash it // away to deal with it later. This check should be fast since most // property names don't start with a digit. auto propNameAsIndex = toArrayIndex( runtime->getIdentifierTable().getStringView(runtime, id)); if (LLVM_UNLIKELY(propNameAsIndex)) { indexNames.push_back(*propNameAsIndex); return; } tmpHandle = HermesValue::encodeStringValue( runtime->getStringPrimFromSymbolID(id)); JSArray::setElementAt(array, runtime, index++, tmpHandle); }); // Iterate over HostObject properties and append them to the array. Do not // append duplicates. if (LLVM_UNLIKELY(hostObjectSymbols)) { for (size_t i = 0; i < hostObjectSymbolCount; ++i) { assert( (*hostObjectSymbols)->at(runtime, i).isSymbol() && "Host object needs to return array of SymbolIDs"); marker.flush(); SymbolID id = (*hostObjectSymbols)->at(runtime, i).getSymbol(); if (dedupSet.count(id.unsafeGetRaw()) == 0) { dedupSet.insert(id.unsafeGetRaw()); assert( !InternalProperty::isInternal(id) && "host object returned reserved symbol"); auto propNameAsIndex = toArrayIndex( runtime->getIdentifierTable().getStringView(runtime, id)); if (LLVM_UNLIKELY(propNameAsIndex)) { indexNames.push_back(*propNameAsIndex); continue; } tmpHandle = HermesValue::encodeStringValue( runtime->getStringPrimFromSymbolID(id)); JSArray::setElementAt(array, runtime, index++, tmpHandle); } } } } // Now iterate the named properties again, including only Symbols. // We could iterate only once, if we chose to ignore (and disallow) // own properties on HostObjects, as we do with Proxies. if (okFlags.getIncludeSymbols()) { MutableHandle<SymbolID> idHandle{runtime}; HiddenClass::forEachProperty( runtime->makeHandle(selfHandle->clazz_), runtime, [runtime, okFlags, array, &index, &idHandle]( SymbolID id, NamedPropertyDescriptor desc) { if (!isSymbolPrimitive(id)) { return; } // If specified, check whether it is enumerable. if (!okFlags.getIncludeNonEnumerable()) { if (!desc.flags.enumerable) return; } idHandle = id; JSArray::setElementAt(array, runtime, index++, idHandle); }); } // The end (exclusive) of the named properties. uint32_t endNamed = index; // Properly set the length of the array. auto cr = JSArray::setLength( array, runtime, endNamed + indexNames.size(), PropOpFlags{}); (void)cr; assert( cr != ExecutionStatus::EXCEPTION && *cr && "JSArray::setLength() failed"); // If we have no index-like names, we are done. if (LLVM_LIKELY(indexNames.empty())) return array; // In the unlikely event that we encountered index-like names, we need to sort // them and merge them with the real indexed properties. Note that it is // guaranteed that there are no clashes. std::sort(indexNames.begin(), indexNames.end()); // Also make space for the new elements by shifting all the named properties // to the right. First, resize the array. JSArray::setStorageEndIndex(array, runtime, endNamed + indexNames.size()); // Shift the non-index property names. The region [numIndexed..endNamed) is // moved to [numIndexed+indexNames.size()..array->size()). // TODO: optimize this by implementing memcpy-like functionality in ArrayImpl. for (uint32_t last = endNamed, toLast = array->getEndIndex(); last != numIndexed;) { --last; --toLast; tmpHandle = array->at(runtime, last); JSArray::setElementAt(array, runtime, toLast, tmpHandle); } // Now we need to merge the indexes in indexNames and the array // [0..numIndexed). We start from the end and copy the larger element from // either array. // 1+ the destination position to copy into. for (uint32_t toLast = numIndexed + indexNames.size(), indexNamesLast = indexNames.size(); toLast != 0;) { if (numIndexed) { uint32_t a = (uint32_t)array->at(runtime, numIndexed - 1).getNumber(); uint32_t b; if (indexNamesLast && (b = indexNames[indexNamesLast - 1]) > a) { tmpHandle = HermesValue::encodeDoubleValue(b); --indexNamesLast; } else { tmpHandle = HermesValue::encodeDoubleValue(a); --numIndexed; } } else { assert(indexNamesLast && "prematurely ran out of source values"); tmpHandle = HermesValue::encodeDoubleValue(indexNames[indexNamesLast - 1]); --indexNamesLast; } --toLast; JSArray::setElementAt(array, runtime, toLast, tmpHandle); } return array; } /// Convert a value to string unless already converted /// \param nameValHandle [Handle<>] the value to convert /// \param str [MutableHandle<StringPrimitive>] the string is stored /// there. Must be initialized to null initially. #define LAZY_TO_STRING(runtime, nameValHandle, str) \ do { \ if (!str) { \ auto status = toString_RJS(runtime, nameValHandle); \ assert( \ status != ExecutionStatus::EXCEPTION && \ "toString() of primitive cannot fail"); \ str = status->get(); \ } \ } while (0) /// Convert a value to an identifier unless already converted /// \param nameValHandle [Handle<>] the value to convert /// \param id [SymbolID] the identifier is stored there. Must be initialized /// to INVALID_IDENTIFIER_ID initially. #define LAZY_TO_IDENTIFIER(runtime, nameValHandle, id) \ do { \ if (id.isInvalid()) { \ CallResult<Handle<SymbolID>> idRes = \ valueToSymbolID(runtime, nameValHandle); \ if (LLVM_UNLIKELY(idRes == ExecutionStatus::EXCEPTION)) { \ return ExecutionStatus::EXCEPTION; \ } \ id = **idRes; \ } \ } while (0) /// Convert a value to array index, if possible. /// \param nameValHandle [Handle<>] the value to convert /// \param str [MutableHandle<StringPrimitive>] the string is stored /// there. Must be initialized to null initially. /// \param arrayIndex [OptValue<uint32_t>] the array index is stored /// there. #define TO_ARRAY_INDEX(runtime, nameValHandle, str, arrayIndex) \ do { \ arrayIndex = toArrayIndexFastPath(*nameValHandle); \ if (!arrayIndex && !nameValHandle->isSymbol()) { \ LAZY_TO_STRING(runtime, nameValHandle, str); \ arrayIndex = toArrayIndex(runtime, str); \ } \ } while (0) /// \return true if the flags of a new property make it suitable for indexed /// storage. All new indexed properties are enumerable, writable and /// configurable and have no accessors. static bool canNewPropertyBeIndexed(DefinePropertyFlags dpf) { return dpf.setEnumerable && dpf.enumerable && dpf.setWritable && dpf.writable && dpf.setConfigurable && dpf.configurable && !dpf.setSetter && !dpf.setGetter; } struct JSObject::Helper { public: LLVM_ATTRIBUTE_ALWAYS_INLINE static ObjectFlags &flags(JSObject *self) { return self->flags_; } LLVM_ATTRIBUTE_ALWAYS_INLINE static OptValue<PropertyFlags> getOwnIndexedPropertyFlags(JSObject *self, Runtime *runtime, uint32_t index) { return JSObject::getOwnIndexedPropertyFlags(self, runtime, index); } LLVM_ATTRIBUTE_ALWAYS_INLINE static NamedPropertyDescriptor &castToNamedPropertyDescriptorRef( ComputedPropertyDescriptor &desc) { return desc.castToNamedPropertyDescriptorRef(); } }; namespace { /// ES5.1 8.12.1. /// A helper which takes a SymbolID which caches the conversion of /// nameValHandle if it's needed. It should be default constructed, /// and may or may not be set. This has been measured to be a useful /// perf win. Note that always_inline seems to be ignored on static /// methods, so this function has to be local to the cpp file in order /// to be inlined for the perf win. LLVM_ATTRIBUTE_ALWAYS_INLINE CallResult<bool> getOwnComputedPrimitiveDescriptorImpl( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, JSObject::IgnoreProxy ignoreProxy, SymbolID &id, ComputedPropertyDescriptor &desc) { assert( !nameValHandle->isObject() && "nameValHandle passed to " "getOwnComputedPrimitiveDescriptor " "cannot be an object"); // Try the fast paths first if we have "fast" index properties and the // property name is an obvious index. if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { if (JSObject::Helper::flags(*selfHandle).fastIndexProperties) { auto res = JSObject::Helper::getOwnIndexedPropertyFlags( selfHandle.get(), runtime, *arrayIndex); if (res) { // This a valid array index, residing in our indexed storage. desc.flags = *res; desc.flags.indexed = 1; desc.slot = *arrayIndex; return true; } // This a valid array index, but we don't have it in our indexed storage, // and we don't have index-like named properties. return false; } if (!selfHandle->getClass(runtime)->getHasIndexLikeProperties() && !selfHandle->isHostObject() && !selfHandle->isLazy() && !selfHandle->isProxyObject()) { // Early return to handle the case where an object definitely has no // index-like properties. This avoids allocating a new StringPrimitive and // uniquing it below. return false; } } // Convert the string to a SymbolID LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); // Look for a named property with this name. if (JSObject::getOwnNamedDescriptor( selfHandle, runtime, id, JSObject::Helper::castToNamedPropertyDescriptorRef(desc))) { return true; } if (LLVM_LIKELY( !JSObject::Helper::flags(*selfHandle).indexedStorage && !selfHandle->isLazy() && !selfHandle->isProxyObject())) { return false; } MutableHandle<StringPrimitive> strPrim{runtime}; // If we have indexed storage, perform potentially expensive conversions // to array index and check it. if (JSObject::Helper::flags(*selfHandle).indexedStorage) { // If the name is a valid integer array index, store it here. OptValue<uint32_t> arrayIndex; // Try to convert the property name to an array index. TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex); if (arrayIndex) { auto res = JSObject::Helper::getOwnIndexedPropertyFlags( selfHandle.get(), runtime, *arrayIndex); if (res) { desc.flags = *res; desc.flags.indexed = 1; desc.slot = *arrayIndex; return true; } } return false; } if (selfHandle->isLazy()) { JSObject::initializeLazyObject(runtime, selfHandle); return JSObject::getOwnComputedPrimitiveDescriptor( selfHandle, runtime, nameValHandle, ignoreProxy, desc); } assert(selfHandle->isProxyObject() && "descriptor flags are impossible"); if (ignoreProxy == JSObject::IgnoreProxy::Yes) { return false; } return JSProxy::getOwnProperty( selfHandle, runtime, nameValHandle, desc, nullptr); } } // namespace CallResult<bool> JSObject::getOwnComputedPrimitiveDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, JSObject::IgnoreProxy ignoreProxy, ComputedPropertyDescriptor &desc) { SymbolID id{}; return getOwnComputedPrimitiveDescriptorImpl( selfHandle, runtime, nameValHandle, ignoreProxy, id, desc); } CallResult<bool> JSObject::getOwnComputedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, ComputedPropertyDescriptor &desc) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return JSObject::getOwnComputedPrimitiveDescriptor( selfHandle, runtime, *converted, IgnoreProxy::No, desc); } CallResult<bool> JSObject::getOwnComputedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, ComputedPropertyDescriptor &desc, MutableHandle<> &valueOrAccessor) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // The proxy is ignored here so we can avoid calling // JSProxy::getOwnProperty twice on proxies, since // getOwnComputedPrimitiveDescriptor doesn't pass back the // valueOrAccessor. CallResult<bool> res = JSObject::getOwnComputedPrimitiveDescriptor( selfHandle, runtime, *converted, IgnoreProxy::Yes, desc); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (*res) { valueOrAccessor = getComputedSlotValue(selfHandle.get(), runtime, desc); return true; } if (LLVM_UNLIKELY(selfHandle->isProxyObject())) { return JSProxy::getOwnProperty( selfHandle, runtime, nameValHandle, desc, &valueOrAccessor); } return false; } JSObject *JSObject::getNamedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropertyFlags expectedFlags, NamedPropertyDescriptor &desc) { if (findProperty(selfHandle, runtime, name, expectedFlags, desc)) return *selfHandle; // Check here for host object flag. This means that "normal" own // properties above win over host-defined properties, but there's no // cost imposed on own property lookups. This should do what we // need in practice, and we can define host vs js property // disambiguation however we want. This is here in order to avoid // impacting perf for the common case where an own property exists // in normal storage. if (LLVM_UNLIKELY(selfHandle->flags_.hostObject)) { desc.flags.hostObject = true; desc.flags.writable = true; return *selfHandle; } if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) { assert( !selfHandle->flags_.proxyObject && "Proxy objects should never be lazy"); // Initialize the object and perform the lookup again. JSObject::initializeLazyObject(runtime, selfHandle); if (findProperty(selfHandle, runtime, name, expectedFlags, desc)) return *selfHandle; } if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) { desc.flags.proxyObject = true; return *selfHandle; } if (selfHandle->parent_) { MutableHandle<JSObject> mutableSelfHandle{ runtime, selfHandle->parent_.getNonNull(runtime)}; do { // Check the most common case first, at the cost of some code duplication. if (LLVM_LIKELY( !mutableSelfHandle->flags_.lazyObject && !mutableSelfHandle->flags_.hostObject && !mutableSelfHandle->flags_.proxyObject)) { findProp: if (findProperty( mutableSelfHandle, runtime, name, PropertyFlags::invalid(), desc)) { assert( !selfHandle->flags_.proxyObject && "Proxy object parents should never have own properties"); return *mutableSelfHandle; } } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.lazyObject)) { JSObject::initializeLazyObject(runtime, mutableSelfHandle); goto findProp; } else if (LLVM_UNLIKELY(mutableSelfHandle->flags_.hostObject)) { desc.flags.hostObject = true; desc.flags.writable = true; return *mutableSelfHandle; } else { assert( mutableSelfHandle->flags_.proxyObject && "descriptor flags are impossible"); desc.flags.proxyObject = true; return *mutableSelfHandle; } } while ((mutableSelfHandle = mutableSelfHandle->parent_.get(runtime))); } return nullptr; } ExecutionStatus JSObject::getComputedPrimitiveDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, MutableHandle<JSObject> &propObj, ComputedPropertyDescriptor &desc) { assert( !nameValHandle->isObject() && "nameValHandle passed to " "getComputedPrimitiveDescriptor cannot " "be an object"); propObj = selfHandle.get(); SymbolID id{}; GCScopeMarkerRAII marker{runtime}; do { // A proxy is ignored here so we can check the bit later and // return it back to the caller for additional processing. Handle<JSObject> loopHandle = propObj; CallResult<bool> res = getOwnComputedPrimitiveDescriptorImpl( loopHandle, runtime, nameValHandle, IgnoreProxy::Yes, id, desc); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (*res) { return ExecutionStatus::RETURNED; } if (LLVM_UNLIKELY(propObj->flags_.hostObject)) { desc.flags.hostObject = true; desc.flags.writable = true; return ExecutionStatus::RETURNED; } if (LLVM_UNLIKELY(propObj->flags_.proxyObject)) { desc.flags.proxyObject = true; return ExecutionStatus::RETURNED; } // This isn't a proxy, so use the faster getParent() instead of // getPrototypeOf. propObj = propObj->getParent(runtime); // Flush at the end of the loop to allow first iteration to be as fast as // possible. marker.flush(); } while (propObj); return ExecutionStatus::RETURNED; } ExecutionStatus JSObject::getComputedDescriptor( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, MutableHandle<JSObject> &propObj, ComputedPropertyDescriptor &desc) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return getComputedPrimitiveDescriptor( selfHandle, runtime, *converted, propObj, desc); } CallResult<PseudoHandle<>> JSObject::getNamedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, Handle<> receiver, PropOpFlags opFlags, PropertyCacheEntry *cacheEntry) { NamedPropertyDescriptor desc; // Locate the descriptor. propObj contains the object which may be anywhere // along the prototype chain. JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc); if (!propObj) { if (LLVM_UNLIKELY(opFlags.getMustExist())) { return runtime->raiseReferenceError( TwineChar16("Property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' doesn't exist"); } return createPseudoHandle(HermesValue::encodeUndefinedValue()); } if (LLVM_LIKELY( !desc.flags.accessor && !desc.flags.hostObject && !desc.flags.proxyObject)) { // Populate the cache if requested. if (cacheEntry && !propObj->getClass(runtime)->isDictionaryNoCache()) { cacheEntry->clazz = propObj->getClassGCPtr().getStorageType(); cacheEntry->slot = desc.slot; } return createPseudoHandle(getNamedSlotValue(propObj, runtime, desc)); } if (desc.flags.accessor) { auto *accessor = vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return Callable::executeCall0( runtime->makeHandle(accessor->getter), runtime, receiver); } else if (desc.flags.hostObject) { auto res = vmcast<HostObject>(propObj)->get(name); if (LLVM_UNLIKELY(res == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return createPseudoHandle(*res); } else { assert(desc.flags.proxyObject && "descriptor flags are impossible"); return JSProxy::getNamed( runtime->makeHandle(propObj), runtime, name, receiver); } } CallResult<PseudoHandle<>> JSObject::getNamedOrIndexed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropOpFlags opFlags) { if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) { // Note that getStringView can be satisfied without materializing the // Identifier. const auto strView = runtime->getIdentifierTable().getStringView(runtime, name); if (auto nameAsIndex = toArrayIndex(strView)) { return getComputed_RJS( selfHandle, runtime, runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex))); } // Here we have indexed properties but the symbol was not index-like. // Fall through to getNamed(). } return getNamed_RJS(selfHandle, runtime, name, opFlags); } CallResult<PseudoHandle<>> JSObject::getComputedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, Handle<> receiver) { // Try the fast-path first: no "index-like" properties and the "name" already // is a valid integer index. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { // Do we have this value present in our array storage? If so, return it. PseudoHandle<> ourValue = createPseudoHandle( getOwnIndexed(selfHandle.get(), runtime, *arrayIndex)); if (LLVM_LIKELY(!ourValue->isEmpty())) return ourValue; } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; // Locate the descriptor. propObj contains the object which may be anywhere // along the prototype chain. MutableHandle<JSObject> propObj{runtime}; if (LLVM_UNLIKELY( getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!propObj) return createPseudoHandle(HermesValue::encodeUndefinedValue()); if (LLVM_LIKELY( !desc.flags.accessor && !desc.flags.hostObject && !desc.flags.proxyObject)) return createPseudoHandle( getComputedSlotValue(propObj.get(), runtime, desc)); if (desc.flags.accessor) { auto *accessor = vmcast<PropertyAccessor>( getComputedSlotValue(propObj.get(), runtime, desc)); if (!accessor->getter) return createPseudoHandle(HermesValue::encodeUndefinedValue()); // Execute the accessor on this object. return accessor->getter.get(runtime)->executeCall0( runtime->makeHandle(accessor->getter), runtime, receiver); } else if (desc.flags.hostObject) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); auto propRes = vmcast<HostObject>(propObj.get())->get(id); if (propRes == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return createPseudoHandle(*propRes); } else { assert(desc.flags.proxyObject && "descriptor flags are impossible"); CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return JSProxy::getComputed(propObj, runtime, *key, receiver); } } CallResult<bool> JSObject::hasNamed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name) { NamedPropertyDescriptor desc; JSObject *propObj = getNamedDescriptor(selfHandle, runtime, name, desc); if (propObj == nullptr) { return false; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { return JSProxy::hasNamed(runtime->makeHandle(propObj), runtime, name); } return true; } CallResult<bool> JSObject::hasNamedOrIndexed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name) { if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) { const auto strView = runtime->getIdentifierTable().getStringView(runtime, name); if (auto nameAsIndex = toArrayIndex(strView)) { if (haveOwnIndexed(selfHandle.get(), runtime, *nameAsIndex)) { return true; } if (selfHandle->flags_.fastIndexProperties) { return false; } } // Here we have indexed properties but the symbol was not stored in the // indexedStorage. // Fall through to getNamed(). } return hasNamed(selfHandle, runtime, name); } CallResult<bool> JSObject::hasComputed( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle) { // Try the fast-path first: no "index-like" properties and the "name" already // is a valid integer index. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { // Do we have this value present in our array storage? If so, return true. if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) { return true; } } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; MutableHandle<JSObject> propObj{runtime}; if (getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } if (!propObj) { return false; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return JSProxy::hasComputed(propObj, runtime, *key); } // For compatibility with polyfills we want to pretend that all HostObject // properties are "own" properties in 'in'. Since there is no way to check for // a HostObject property, we must always assume success. In practice the // property name would have been obtained from enumerating the properties in // JS code that looks something like this: // for(key in hostObj) { // if (key in hostObj) // ... // } return true; } static ExecutionStatus raiseErrorForOverridingStaticBuiltin( Handle<JSObject> selfHandle, Runtime *runtime, Handle<SymbolID> name) { Handle<StringPrimitive> methodNameHnd = runtime->makeHandle(runtime->getStringPrimFromSymbolID(name.get())); // If the 'name' property does not exist or is an accessor, we don't display // the name. NamedPropertyDescriptor desc; auto *obj = JSObject::getNamedDescriptor( selfHandle, runtime, Predefined::getSymbolID(Predefined::name), desc); assert( !selfHandle->isProxyObject() && "raiseErrorForOverridingStaticBuiltin cannot be used with proxy objects"); if (!obj || desc.flags.accessor) { return runtime->raiseTypeError( TwineChar16("Attempting to override read-only builtin method '") + TwineChar16(methodNameHnd.get()) + "'"); } // Display the name property of the builtin object if it is a string. StringPrimitive *objName = dyn_vmcast<StringPrimitive>( JSObject::getNamedSlotValue(selfHandle.get(), runtime, desc)); if (!objName) { return runtime->raiseTypeError( TwineChar16("Attempting to override read-only builtin method '") + TwineChar16(methodNameHnd.get()) + "'"); } return runtime->raiseTypeError( TwineChar16("Attempting to override read-only builtin method '") + TwineChar16(objName) + "." + TwineChar16(methodNameHnd.get()) + "'"); } CallResult<bool> JSObject::putNamedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, Handle<> valueHandle, Handle<> receiver, PropOpFlags opFlags) { NamedPropertyDescriptor desc; // Look for the property in this object or along the prototype chain. JSObject *propObj = getNamedDescriptor( selfHandle, runtime, name, PropertyFlags::defaultNewNamedPropertyFlags(), desc); // If the property exists (or, we hit a proxy/hostobject on the way // up the chain) if (propObj) { // Get the simple case out of the way: If the property already // exists on selfHandle, is not an accessor, selfHandle and // receiver are the same, selfHandle is not a host // object/proxy/internal setter, and the property is writable, // just write into the same slot. if (LLVM_LIKELY( *selfHandle == propObj && selfHandle.getHermesValue().getRaw() == receiver->getRaw() && !desc.flags.accessor && !desc.flags.internalSetter && !desc.flags.hostObject && !desc.flags.proxyObject && desc.flags.writable)) { setNamedSlotValue( *selfHandle, runtime, desc, valueHandle.getHermesValue()); return true; } if (LLVM_UNLIKELY(desc.flags.accessor)) { auto *accessor = vmcast<PropertyAccessor>(getNamedSlotValue(propObj, runtime, desc)); // If it is a read-only accessor, fail. if (!accessor->setter) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Cannot assign to property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' which has only a getter"); } return false; } // Execute the accessor on this object. if (accessor->setter.get(runtime)->executeCall1( runtime->makeHandle(accessor->setter), runtime, receiver, *valueHandle) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return true; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { assert( !opFlags.getMustExist() && "MustExist cannot be used with Proxy objects"); CallResult<bool> setRes = JSProxy::setNamed( runtime->makeHandle(propObj), runtime, name, valueHandle, receiver); if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*setRes && opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Proxy set returned false for property '") + runtime->getIdentifierTable().getStringView(runtime, name) + "'"); } return setRes; } if (LLVM_UNLIKELY(!desc.flags.writable)) { if (desc.flags.staticBuiltin) { return raiseErrorForOverridingStaticBuiltin( selfHandle, runtime, runtime->makeHandle(name)); } if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Cannot assign to read-only property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "'"); } return false; } if (*selfHandle == propObj && desc.flags.internalSetter) { return internalSetter( selfHandle, runtime, name, desc, valueHandle, opFlags); } } // The property does not exist as an conventional own property on // this object. MutableHandle<JSObject> receiverHandle{runtime, *selfHandle}; if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() || receiverHandle->isHostObject() || receiverHandle->isProxyObject()) { if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) { receiverHandle = dyn_vmcast<JSObject>(*receiver); } if (!receiverHandle) { return false; } if (getOwnNamedDescriptor(receiverHandle, runtime, name, desc)) { if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) { return false; } assert( !receiverHandle->isHostObject() && !receiverHandle->isProxyObject() && "getOwnNamedDescriptor never sets hostObject or proxyObject flags"); setNamedSlotValue( *receiverHandle, runtime, desc, valueHandle.getHermesValue()); return true; } // Now deal with host and proxy object cases. We need to call // getOwnComputedPrimitiveDescriptor because it knows how to call // the [[getOwnProperty]] Proxy impl if needed. if (LLVM_UNLIKELY( receiverHandle->isHostObject() || receiverHandle->isProxyObject())) { if (receiverHandle->isHostObject()) { return vmcast<HostObject>(receiverHandle.get()) ->set(name, *valueHandle); } ComputedPropertyDescriptor desc; Handle<> nameValHandle = runtime->makeHandle(name); CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor( receiverHandle, runtime, nameValHandle, IgnoreProxy::No, desc); if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } DefinePropertyFlags dpf; if (*descDefinedRes) { dpf.setValue = 1; } else { dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); } return JSProxy::defineOwnProperty( receiverHandle, runtime, nameValHandle, dpf, valueHandle, opFlags); } } // Does the caller require it to exist? if (LLVM_UNLIKELY(opFlags.getMustExist())) { return runtime->raiseReferenceError( TwineChar16("Property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' doesn't exist"); } // Add a new property. return addOwnProperty( receiverHandle, runtime, name, DefinePropertyFlags::getDefaultNewPropertyFlags(), valueHandle, opFlags); } CallResult<bool> JSObject::putNamedOrIndexed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, Handle<> valueHandle, PropOpFlags opFlags) { if (LLVM_UNLIKELY(selfHandle->flags_.indexedStorage)) { // Note that getStringView can be satisfied without materializing the // Identifier. const auto strView = runtime->getIdentifierTable().getStringView(runtime, name); if (auto nameAsIndex = toArrayIndex(strView)) { return putComputed_RJS( selfHandle, runtime, runtime->makeHandle(HermesValue::encodeNumberValue(*nameAsIndex)), valueHandle, opFlags); } // Here we have indexed properties but the symbol was not index-like. // Fall through to putNamed(). } return putNamed_RJS(selfHandle, runtime, name, valueHandle, opFlags); } CallResult<bool> JSObject::putComputedWithReceiver_RJS( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, Handle<> valueHandle, Handle<> receiver, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "mustExist flag cannot be used with computed properties"); // Try the fast-path first: has "index-like" properties, the "name" // already is a valid integer index, selfHandle and receiver are the // same, and it is present in storage. if (selfHandle->flags_.fastIndexProperties) { if (auto arrayIndex = toArrayIndexFastPath(*nameValHandle)) { if (selfHandle.getHermesValue().getRaw() == receiver->getRaw()) { if (haveOwnIndexed(selfHandle.get(), runtime, *arrayIndex)) { auto result = setOwnIndexed(selfHandle, runtime, *arrayIndex, valueHandle); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_LIKELY(*result)) return true; if (opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError( "Cannot assign to read-only property"); } return false; } } } } // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; ComputedPropertyDescriptor desc; // Look for the property in this object or along the prototype chain. MutableHandle<JSObject> propObj{runtime}; if (LLVM_UNLIKELY( getComputedPrimitiveDescriptor( selfHandle, runtime, nameValPrimitiveHandle, propObj, desc) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } // If the property exists (or, we hit a proxy/hostobject on the way // up the chain) if (propObj) { // Get the simple case out of the way: If the property already // exists on selfHandle, is not an accessor, selfHandle and // receiver are the same, selfHandle is not a host // object/proxy/internal setter, and the property is writable, // just write into the same slot. if (LLVM_LIKELY( selfHandle == propObj && selfHandle.getHermesValue().getRaw() == receiver->getRaw() && !desc.flags.accessor && !desc.flags.internalSetter && !desc.flags.hostObject && !desc.flags.proxyObject && desc.flags.writable)) { if (LLVM_UNLIKELY( setComputedSlotValue(selfHandle, runtime, desc, valueHandle) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } // Is it an accessor? if (LLVM_UNLIKELY(desc.flags.accessor)) { auto *accessor = vmcast<PropertyAccessor>( getComputedSlotValue(propObj.get(), runtime, desc)); // If it is a read-only accessor, fail. if (!accessor->setter) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeErrorForValue( "Cannot assign to property ", nameValPrimitiveHandle, " which has only a getter"); } return false; } // Execute the accessor on this object. if (accessor->setter.get(runtime)->executeCall1( runtime->makeHandle(accessor->setter), runtime, receiver, valueHandle.get()) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } return true; } if (LLVM_UNLIKELY(desc.flags.proxyObject)) { assert( !opFlags.getMustExist() && "MustExist cannot be used with Proxy objects"); CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; CallResult<bool> setRes = JSProxy::setComputed(propObj, runtime, *key, valueHandle, receiver); if (LLVM_UNLIKELY(setRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } if (!*setRes && opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError( TwineChar16("Proxy trap returned false for property")); } return setRes; } if (LLVM_UNLIKELY(!desc.flags.writable)) { if (desc.flags.staticBuiltin) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); return raiseErrorForOverridingStaticBuiltin( selfHandle, runtime, runtime->makeHandle(id)); } if (opFlags.getThrowOnError()) { return runtime->raiseTypeErrorForValue( "Cannot assign to read-only property ", nameValPrimitiveHandle, ""); } return false; } if (selfHandle == propObj && desc.flags.internalSetter) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); return internalSetter( selfHandle, runtime, id, desc.castToNamedPropertyDescriptorRef(), valueHandle, opFlags); } } // The property does not exist as an conventional own property on // this object. MutableHandle<JSObject> receiverHandle{runtime, *selfHandle}; if (selfHandle.getHermesValue().getRaw() != receiver->getRaw() || receiverHandle->isHostObject() || receiverHandle->isProxyObject()) { if (selfHandle.getHermesValue().getRaw() != receiver->getRaw()) { receiverHandle = dyn_vmcast<JSObject>(*receiver); } if (!receiverHandle) { return false; } CallResult<bool> descDefinedRes = getOwnComputedPrimitiveDescriptor( receiverHandle, runtime, nameValPrimitiveHandle, IgnoreProxy::No, desc); if (LLVM_UNLIKELY(descDefinedRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } DefinePropertyFlags dpf; if (*descDefinedRes) { if (LLVM_UNLIKELY(desc.flags.accessor || !desc.flags.writable)) { return false; } if (LLVM_LIKELY( !desc.flags.internalSetter && !receiverHandle->isHostObject() && !receiverHandle->isProxyObject())) { if (LLVM_UNLIKELY( setComputedSlotValue( receiverHandle, runtime, desc, valueHandle) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } } if (LLVM_UNLIKELY( desc.flags.internalSetter || receiverHandle->isHostObject() || receiverHandle->isProxyObject())) { SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); if (desc.flags.internalSetter) { return internalSetter( receiverHandle, runtime, id, desc.castToNamedPropertyDescriptorRef(), valueHandle, opFlags); } else if (receiverHandle->isHostObject()) { return vmcast<HostObject>(receiverHandle.get())->set(id, *valueHandle); } assert( receiverHandle->isProxyObject() && "descriptor flags are impossible"); if (*descDefinedRes) { dpf.setValue = 1; } else { dpf = DefinePropertyFlags::getDefaultNewPropertyFlags(); } return JSProxy::defineOwnProperty( receiverHandle, runtime, nameValPrimitiveHandle, dpf, valueHandle, opFlags); } } /// Can we add more properties? if (LLVM_UNLIKELY(!receiverHandle->isExtensible())) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "cannot add a new property"); // TODO: better message. } return false; } // If we have indexed storage we must check whether the property is an index, // and if it is, store it in indexed storage. if (receiverHandle->flags_.indexedStorage) { OptValue<uint32_t> arrayIndex; MutableHandle<StringPrimitive> strPrim{runtime}; TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex); if (arrayIndex) { // Check whether we need to update array's ".length" property. if (auto *array = dyn_vmcast<JSArray>(receiverHandle.get())) { if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(array))) { auto cr = putNamed_RJS( receiverHandle, runtime, Predefined::getSymbolID(Predefined::length), runtime->makeHandle( HermesValue::encodeNumberValue(*arrayIndex + 1)), opFlags); if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_UNLIKELY(!*cr)) return false; } } auto result = setOwnIndexed(receiverHandle, runtime, *arrayIndex, valueHandle); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (LLVM_LIKELY(*result)) return true; if (opFlags.getThrowOnError()) { // TODO: better message. return runtime->raiseTypeError("Cannot assign to read-only property"); } return false; } } SymbolID id{}; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); // Add a new named property. return addOwnProperty( receiverHandle, runtime, id, DefinePropertyFlags::getDefaultNewPropertyFlags(), valueHandle, opFlags); } CallResult<bool> JSObject::deleteNamed( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "mustExist cannot be specified when deleting"); // Find the property by name. NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, name, desc); // If the property doesn't exist in this object, return success. if (!pos) { if (LLVM_LIKELY( !selfHandle->flags_.lazyObject && !selfHandle->flags_.proxyObject)) { return true; } else if (selfHandle->flags_.lazyObject) { // object is lazy, initialize and read again. initializeLazyObject(runtime, selfHandle); pos = findProperty(selfHandle, runtime, name, desc); if (!pos) // still not there, return true. return true; } else { assert(selfHandle->flags_.proxyObject && "object flags are impossible"); return proxyOpFlags( runtime, opFlags, "Proxy delete returned false", JSProxy::deleteNamed(selfHandle, runtime, name)); } } // If the property isn't configurable, fail. if (LLVM_UNLIKELY(!desc.flags.configurable)) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "' is not configurable"); } return false; } // Clear the deleted property value to prevent memory leaks. setNamedSlotValue( *selfHandle, runtime, desc, HermesValue::encodeEmptyValue()); // Perform the actual deletion. auto newClazz = HiddenClass::deleteProperty( runtime->makeHandle(selfHandle->clazz_), runtime, *pos); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); return true; } CallResult<bool> JSObject::deleteComputed( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "mustExist cannot be specified when deleting"); // If nameValHandle is an object, we should convert it to string now, // because toString may have side-effect, and we want to do this only // once. auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto nameValPrimitiveHandle = *converted; // If the name is a valid integer array index, store it here. OptValue<uint32_t> arrayIndex; // If we have indexed storage, we must attempt to convert the name to array // index, even if the conversion is expensive. if (selfHandle->flags_.indexedStorage) { MutableHandle<StringPrimitive> strPrim{runtime}; TO_ARRAY_INDEX(runtime, nameValPrimitiveHandle, strPrim, arrayIndex); } // Try the fast-path first: the "name" is a valid array index and we don't // have "index-like" named properties. if (arrayIndex && selfHandle->flags_.fastIndexProperties) { // Delete the indexed property. if (deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) return true; // Cannot delete property (for example this may be a typed array). if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot delete property"); } return false; } // slow path, check if object is lazy before continuing. if (LLVM_UNLIKELY(selfHandle->flags_.lazyObject)) { // initialize and try again. initializeLazyObject(runtime, selfHandle); return deleteComputed(selfHandle, runtime, nameValHandle, opFlags); } // Convert the string to an SymbolID; SymbolID id; LAZY_TO_IDENTIFIER(runtime, nameValPrimitiveHandle, id); // Find the property by name. NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, id, desc); // If the property exists, make sure it is configurable. if (pos) { // If the property isn't configurable, fail. if (LLVM_UNLIKELY(!desc.flags.configurable)) { if (opFlags.getThrowOnError()) { // TODO: a better message. return runtime->raiseTypeError("Property is not configurable"); } return false; } } // At this point we know that the named property either doesn't exist, or // is configurable and so can be deleted, or the object is a Proxy. // If it is an "index-like" property, we must also delete the "shadow" indexed // property in order to keep Array.length correct. if (arrayIndex) { if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) { // Cannot delete property (for example this may be a typed array). if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot delete property"); } return false; } } if (pos) { // delete the named property (if it exists). // Clear the deleted property value to prevent memory leaks. setNamedSlotValue( *selfHandle, runtime, desc, HermesValue::encodeEmptyValue()); // Remove the property descriptor. auto newClazz = HiddenClass::deleteProperty( runtime->makeHandle(selfHandle->clazz_), runtime, *pos); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); } else if (LLVM_UNLIKELY(selfHandle->flags_.proxyObject)) { CallResult<Handle<>> key = toPropertyKey(runtime, nameValPrimitiveHandle); if (key == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; return proxyOpFlags( runtime, opFlags, "Proxy delete returned false", JSProxy::deleteComputed(selfHandle, runtime, *key)); } return true; } CallResult<bool> JSObject::defineOwnPropertyInternal( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { assert( !opFlags.getMustExist() && "cannot use mustExist with defineOwnProperty"); assert( !(dpFlags.setValue && dpFlags.isAccessor()) && "Cannot set both value and accessor"); assert( (dpFlags.setValue || dpFlags.isAccessor() || valueOrAccessor.get().isUndefined()) && "value must be undefined when all of setValue/setSetter/setGetter are " "false"); #ifndef NDEBUG if (dpFlags.isAccessor()) { assert(valueOrAccessor.get().isPointer() && "accessor must be non-empty"); assert( !dpFlags.setWritable && !dpFlags.writable && "writable must not be set with accessors"); } #endif // Is it an existing property. NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, name, desc); if (pos) { return updateOwnProperty( selfHandle, runtime, name, *pos, desc, dpFlags, valueOrAccessor, opFlags); } if (LLVM_UNLIKELY( selfHandle->flags_.lazyObject || selfHandle->flags_.proxyObject)) { if (selfHandle->flags_.proxyObject) { return JSProxy::defineOwnProperty( selfHandle, runtime, name.isUniqued() ? runtime->makeHandle(HermesValue::encodeStringValue( runtime->getStringPrimFromSymbolID(name))) : runtime->makeHandle(name), dpFlags, valueOrAccessor, opFlags); } assert(selfHandle->flags_.lazyObject && "descriptor flags are impossible"); // if the property was not found and the object is lazy we need to // initialize it and try again. JSObject::initializeLazyObject(runtime, selfHandle); return defineOwnPropertyInternal( selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags); } return addOwnProperty( selfHandle, runtime, name, dpFlags, valueOrAccessor, opFlags); } ExecutionStatus JSObject::defineNewOwnProperty( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropertyFlags propertyFlags, Handle<> valueOrAccessor) { assert( !selfHandle->flags_.proxyObject && "definedNewOwnProperty cannot be used with proxy objects"); assert( !(propertyFlags.accessor && !valueOrAccessor.get().isPointer()) && "accessor must be non-empty"); assert( !(propertyFlags.accessor && propertyFlags.writable) && "writable must not be set with accessors"); assert( !HiddenClass::debugIsPropertyDefined( selfHandle->clazz_.get(runtime), runtime, name) && "new property is already defined"); return addOwnPropertyImpl( selfHandle, runtime, name, propertyFlags, valueOrAccessor); } CallResult<bool> JSObject::defineOwnComputedPrimitive( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { assert( !nameValHandle->isObject() && "nameValHandle passed to " "defineOwnComputedPrimitive() cannot be " "an object"); assert( !opFlags.getMustExist() && "cannot use mustExist with defineOwnProperty"); assert( !(dpFlags.setValue && dpFlags.isAccessor()) && "Cannot set both value and accessor"); assert( (dpFlags.setValue || dpFlags.isAccessor() || valueOrAccessor.get().isUndefined()) && "value must be undefined when all of setValue/setSetter/setGetter are " "false"); assert( !dpFlags.enableInternalSetter && "Cannot set internalSetter on a computed property"); #ifndef NDEBUG if (dpFlags.isAccessor()) { assert(valueOrAccessor.get().isPointer() && "accessor must be non-empty"); assert( !dpFlags.setWritable && !dpFlags.writable && "writable must not be set with accessors"); } #endif // If the name is a valid integer array index, store it here. OptValue<uint32_t> arrayIndex; // If we have indexed storage, we must attempt to convert the name to array // index, even if the conversion is expensive. if (selfHandle->flags_.indexedStorage) { MutableHandle<StringPrimitive> strPrim{runtime}; TO_ARRAY_INDEX(runtime, nameValHandle, strPrim, arrayIndex); } SymbolID id{}; // If not storing a property with an array index name, or if we don't have // indexed storage, just pass to the named routine. if (!arrayIndex) { LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); return defineOwnPropertyInternal( selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags); } // At this point we know that we have indexed storage and that the property // has an index-like name. // First check if a named property with the same name exists. if (selfHandle->clazz_.get(runtime)->getHasIndexLikeProperties()) { LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); NamedPropertyDescriptor desc; auto pos = findProperty(selfHandle, runtime, id, desc); // If we found a named property, update it. if (pos) { return updateOwnProperty( selfHandle, runtime, id, *pos, desc, dpFlags, valueOrAccessor, opFlags); } } // Does an indexed property with that index exist? auto indexedPropPresent = getOwnIndexedPropertyFlags(selfHandle.get(), runtime, *arrayIndex); if (indexedPropPresent) { // The current value of the property. HermesValue curValueOrAccessor = getOwnIndexed(selfHandle.get(), runtime, *arrayIndex); auto updateStatus = checkPropertyUpdate( runtime, *indexedPropPresent, dpFlags, curValueOrAccessor, valueOrAccessor, opFlags); if (updateStatus == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (updateStatus->first == PropertyUpdateStatus::failed) return false; // The property update is valid, but can the property remain an "indexed" // property, or do we need to convert it to a named property? // If the property flags didn't change, the property remains indexed. if (updateStatus->second == *indexedPropPresent) { // If the value doesn't change, we are done. if (updateStatus->first == PropertyUpdateStatus::done) return true; // If we successfully updated the value, we are done. auto result = setOwnIndexed(selfHandle, runtime, *arrayIndex, valueOrAccessor); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (*result) return true; if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError( "cannot change read-only property value"); } return false; } // OK, we need to convert an indexed property to a named one. // Check whether to use the supplied value, or to reuse the old one, as we // are simply reconfiguring it. MutableHandle<> value{runtime}; if (dpFlags.setValue || dpFlags.isAccessor()) { value = valueOrAccessor.get(); } else { value = curValueOrAccessor; } // Update dpFlags to match the existing property flags. dpFlags.setEnumerable = 1; dpFlags.setWritable = 1; dpFlags.setConfigurable = 1; dpFlags.enumerable = updateStatus->second.enumerable; dpFlags.writable = updateStatus->second.writable; dpFlags.configurable = updateStatus->second.configurable; // Delete the existing indexed property. if (!deleteOwnIndexed(selfHandle, runtime, *arrayIndex)) { if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot define property"); } return false; } // Add the new named property. LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); return addOwnProperty(selfHandle, runtime, id, dpFlags, value, opFlags); } /// Can we add new properties? if (!selfHandle->isExtensible()) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "cannot add a new property"); // TODO: better message. } return false; } // This is a new property with an index-like name. // Check whether we need to update array's ".length" property. bool updateLength = false; if (auto arrayHandle = Handle<JSArray>::dyn_vmcast(selfHandle)) { if (LLVM_UNLIKELY(*arrayIndex >= JSArray::getLength(*arrayHandle))) { NamedPropertyDescriptor lengthDesc; bool lengthPresent = getOwnNamedDescriptor( arrayHandle, runtime, Predefined::getSymbolID(Predefined::length), lengthDesc); (void)lengthPresent; assert(lengthPresent && ".length must be present in JSArray"); if (!lengthDesc.flags.writable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "Cannot assign to read-only 'length' property of array"); } return false; } updateLength = true; } } bool newIsIndexed = canNewPropertyBeIndexed(dpFlags); if (newIsIndexed) { auto result = setOwnIndexed( selfHandle, runtime, *arrayIndex, dpFlags.setValue ? valueOrAccessor : Runtime::getUndefinedValue()); if (LLVM_UNLIKELY(result == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; if (!*result) { if (opFlags.getThrowOnError()) { // TODO: better error message. return runtime->raiseTypeError("Cannot define property"); } return false; } } // If this is an array and we need to update ".length", do so. if (updateLength) { // This should always succeed since we are simply enlarging the length. auto res = JSArray::setLength( Handle<JSArray>::vmcast(selfHandle), runtime, *arrayIndex + 1, opFlags); (void)res; assert( res != ExecutionStatus::EXCEPTION && *res && "JSArray::setLength() failed unexpectedly"); } if (newIsIndexed) return true; // We are adding a new property with an index-like name. LAZY_TO_IDENTIFIER(runtime, nameValHandle, id); return addOwnProperty( selfHandle, runtime, id, dpFlags, valueOrAccessor, opFlags); } CallResult<bool> JSObject::defineOwnComputed( Handle<JSObject> selfHandle, Runtime *runtime, Handle<> nameValHandle, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { auto converted = toPropertyKeyIfObject(runtime, nameValHandle); if (LLVM_UNLIKELY(converted == ExecutionStatus::EXCEPTION)) return ExecutionStatus::EXCEPTION; return defineOwnComputedPrimitive( selfHandle, runtime, *converted, dpFlags, valueOrAccessor, opFlags); } std::string JSObject::getHeuristicTypeName(GC *gc) { PointerBase *const base = gc->getPointerBase(); if (auto constructorVal = tryGetNamedNoAlloc( this, base, Predefined::getSymbolID(Predefined::constructor))) { if (auto *constructor = dyn_vmcast<JSObject>(*constructorVal)) { auto name = constructor->getNameIfExists(base); // If the constructor's name doesn't exist, or it is just the object // constructor, attempt to find a different name. if (!name.empty() && name != "Object") return name; } } std::string name = getVT()->base.snapshotMetaData.defaultNameForNode(this); // A constructor's name was not found, check if the object is in dictionary // mode. if (getClass(base)->isDictionary()) { return name + "(Dictionary)"; } // If it's not an Object, the CellKind is most likely good enough on its own if (getKind() != CellKind::ObjectKind) { return name; } // If the object isn't a dictionary, and it has only a few property names, // make the name based on those property names. std::vector<std::string> propertyNames; HiddenClass::forEachPropertyNoAlloc( getClass(base), base, [gc, &propertyNames](SymbolID id, NamedPropertyDescriptor) { if (InternalProperty::isInternal(id)) { // Internal properties aren't user-visible, skip them. return; } propertyNames.emplace_back(gc->convertSymbolToUTF8(id)); }); // NOTE: One option is to sort the property names before truncation, to // reduce the number of groups; however, by not sorting them it makes it // easier to spot sets of objects with the same properties but in different // orders, and thus find HiddenClass optimizations to make. // For objects with a lot of properties but aren't in dictionary mode yet, // keep the number displayed small. constexpr int kMaxPropertiesForTypeName = 5; bool truncated = false; if (propertyNames.size() > kMaxPropertiesForTypeName) { propertyNames.erase( propertyNames.begin() + kMaxPropertiesForTypeName, propertyNames.end()); truncated = true; } // The final name should look like Object(a, b, c). if (propertyNames.empty()) { // Don't add parentheses for objects with no properties. return name; } name += "("; bool first = true; for (const auto &prop : propertyNames) { if (!first) { name += ", "; } first = false; name += prop; } if (truncated) { // No need to check for comma edge case because this only happens for // greater than one property. static_assert( kMaxPropertiesForTypeName >= 1, "Property truncation should not happen for 0 properties"); name += ", ..."; } name += ")"; return name; } std::string JSObject::getNameIfExists(PointerBase *base) { // Try "displayName" first, if it is defined. if (auto nameVal = tryGetNamedNoAlloc( this, base, Predefined::getSymbolID(Predefined::displayName))) { if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) { return converter(name); } } // Next, use "name" if it is defined. if (auto nameVal = tryGetNamedNoAlloc( this, base, Predefined::getSymbolID(Predefined::name))) { if (auto *name = dyn_vmcast<StringPrimitive>(*nameVal)) { return converter(name); } } // There is no other way to access the "name" property on an object. return ""; } std::string JSObject::_snapshotNameImpl(GCCell *cell, GC *gc) { auto *const self = vmcast<JSObject>(cell); return self->getHeuristicTypeName(gc); } void JSObject::_snapshotAddEdgesImpl(GCCell *cell, GC *gc, HeapSnapshot &snap) { auto *const self = vmcast<JSObject>(cell); // Add the prototype as a property edge, so it's easy for JS developers to // walk the prototype chain on their own. if (self->parent_) { snap.addNamedEdge( HeapSnapshot::EdgeType::Property, // __proto__ chosen for similarity to V8. "__proto__", gc->getObjectID(self->parent_)); } HiddenClass::forEachPropertyNoAlloc( self->clazz_.get(gc->getPointerBase()), gc->getPointerBase(), [self, gc, &snap](SymbolID id, NamedPropertyDescriptor desc) { if (InternalProperty::isInternal(id)) { // Internal properties aren't user-visible, skip them. return; } // Else, it's a user-visible property. GCHermesValue &prop = namedSlotRef(self, gc->getPointerBase(), desc.slot); const llvh::Optional<HeapSnapshot::NodeID> idForProp = gc->getSnapshotID(prop); if (!idForProp) { return; } std::string propName = gc->convertSymbolToUTF8(id); // If the property name is a valid array index, display it as an // "element" instead of a "property". This will put square brackets // around the number and sort it numerically rather than // alphabetically. if (auto index = ::hermes::toArrayIndex(propName)) { snap.addIndexedEdge( HeapSnapshot::EdgeType::Element, index.getValue(), idForProp.getValue()); } else { snap.addNamedEdge( HeapSnapshot::EdgeType::Property, propName, idForProp.getValue()); } }); } void JSObject::_snapshotAddLocationsImpl( GCCell *cell, GC *gc, HeapSnapshot &snap) { auto *const self = vmcast<JSObject>(cell); PointerBase *const base = gc->getPointerBase(); // Add the location of the constructor function for this object, if that // constructor is a user-defined JS function. if (auto constructorVal = tryGetNamedNoAlloc( self, base, Predefined::getSymbolID(Predefined::constructor))) { if (constructorVal->isObject()) { if (auto *constructor = dyn_vmcast<JSFunction>(*constructorVal)) { constructor->addLocationToSnapshot(snap, gc->getObjectID(self)); } } } } std::pair<uint32_t, uint32_t> JSObject::_getOwnIndexedRangeImpl( JSObject *self, Runtime *runtime) { return {0, 0}; } bool JSObject::_haveOwnIndexedImpl(JSObject *self, Runtime *, uint32_t) { return false; } OptValue<PropertyFlags> JSObject::_getOwnIndexedPropertyFlagsImpl( JSObject *self, Runtime *runtime, uint32_t) { return llvh::None; } HermesValue JSObject::_getOwnIndexedImpl(JSObject *, Runtime *, uint32_t) { return HermesValue::encodeEmptyValue(); } CallResult<bool> JSObject::_setOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t, Handle<>) { return false; } bool JSObject::_deleteOwnIndexedImpl(Handle<JSObject>, Runtime *, uint32_t) { return false; } bool JSObject::_checkAllOwnIndexedImpl( JSObject * /*self*/, Runtime * /*runtime*/, ObjectVTable::CheckAllOwnIndexedMode /*mode*/) { return true; } void JSObject::preventExtensions(JSObject *self) { assert( !self->flags_.proxyObject && "[[Extensible]] slot cannot be set directly on Proxy objects"); self->flags_.noExtend = true; } CallResult<bool> JSObject::preventExtensions( Handle<JSObject> selfHandle, Runtime *runtime, PropOpFlags opFlags) { if (LLVM_UNLIKELY(selfHandle->isProxyObject())) { return JSProxy::preventExtensions(selfHandle, runtime, opFlags); } JSObject::preventExtensions(*selfHandle); return true; } ExecutionStatus JSObject::seal(Handle<JSObject> selfHandle, Runtime *runtime) { CallResult<bool> statusRes = JSObject::preventExtensions( selfHandle, runtime, PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } assert( *statusRes && "seal preventExtensions with ThrowOnError returned false"); // Already sealed? if (selfHandle->flags_.sealed) return ExecutionStatus::RETURNED; auto newClazz = HiddenClass::makeAllNonConfigurable( runtime->makeHandle(selfHandle->clazz_), runtime); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); selfHandle->flags_.sealed = true; return ExecutionStatus::RETURNED; } ExecutionStatus JSObject::freeze( Handle<JSObject> selfHandle, Runtime *runtime) { CallResult<bool> statusRes = JSObject::preventExtensions( selfHandle, runtime, PropOpFlags().plusThrowOnError()); if (LLVM_UNLIKELY(statusRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } assert( *statusRes && "freeze preventExtensions with ThrowOnError returned false"); // Already frozen? if (selfHandle->flags_.frozen) return ExecutionStatus::RETURNED; auto newClazz = HiddenClass::makeAllReadOnly( runtime->makeHandle(selfHandle->clazz_), runtime); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); selfHandle->flags_.frozen = true; selfHandle->flags_.sealed = true; return ExecutionStatus::RETURNED; } void JSObject::updatePropertyFlagsWithoutTransitions( Handle<JSObject> selfHandle, Runtime *runtime, PropertyFlags flagsToClear, PropertyFlags flagsToSet, OptValue<llvh::ArrayRef<SymbolID>> props) { auto newClazz = HiddenClass::updatePropertyFlagsWithoutTransitions( runtime->makeHandle(selfHandle->clazz_), runtime, flagsToClear, flagsToSet, props); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); } CallResult<bool> JSObject::isExtensible( PseudoHandle<JSObject> self, Runtime *runtime) { if (LLVM_UNLIKELY(self->isProxyObject())) { return JSProxy::isExtensible(runtime->makeHandle(std::move(self)), runtime); } return self->isExtensible(); } bool JSObject::isSealed(PseudoHandle<JSObject> self, Runtime *runtime) { if (self->flags_.sealed) return true; if (!self->flags_.noExtend) return false; auto selfHandle = runtime->makeHandle(std::move(self)); if (!HiddenClass::areAllNonConfigurable( runtime->makeHandle(selfHandle->clazz_), runtime)) { return false; } if (!checkAllOwnIndexed( *selfHandle, runtime, ObjectVTable::CheckAllOwnIndexedMode::NonConfigurable)) { return false; } // Now that we know we are sealed, set the flag. selfHandle->flags_.sealed = true; return true; } bool JSObject::isFrozen(PseudoHandle<JSObject> self, Runtime *runtime) { if (self->flags_.frozen) return true; if (!self->flags_.noExtend) return false; auto selfHandle = runtime->makeHandle(std::move(self)); if (!HiddenClass::areAllReadOnly( runtime->makeHandle(selfHandle->clazz_), runtime)) { return false; } if (!checkAllOwnIndexed( *selfHandle, runtime, ObjectVTable::CheckAllOwnIndexedMode::ReadOnly)) { return false; } // Now that we know we are sealed, set the flag. selfHandle->flags_.frozen = true; selfHandle->flags_.sealed = true; return true; } CallResult<bool> JSObject::addOwnProperty( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { /// Can we add more properties? if (!selfHandle->isExtensible() && !opFlags.getInternalForce()) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( TwineChar16("Cannot add new property '") + runtime->getIdentifierTable().getStringViewForDev(runtime, name) + "'"); } return false; } PropertyFlags flags{}; // Accessors don't set writeable. if (dpFlags.isAccessor()) { dpFlags.setWritable = 0; flags.accessor = 1; } // Override the default flags if specified. if (dpFlags.setEnumerable) flags.enumerable = dpFlags.enumerable; if (dpFlags.setWritable) flags.writable = dpFlags.writable; if (dpFlags.setConfigurable) flags.configurable = dpFlags.configurable; flags.internalSetter = dpFlags.enableInternalSetter; if (LLVM_UNLIKELY( addOwnPropertyImpl( selfHandle, runtime, name, flags, valueOrAccessor) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } return true; } ExecutionStatus JSObject::addOwnPropertyImpl( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, PropertyFlags propertyFlags, Handle<> valueOrAccessor) { assert( !selfHandle->flags_.proxyObject && "Internal properties cannot be added to Proxy objects"); // Add a new property to the class. // TODO: if we check for OOM here in the future, we must undo the slot // allocation. auto addResult = HiddenClass::addProperty( runtime->makeHandle(selfHandle->clazz_), runtime, name, propertyFlags); if (LLVM_UNLIKELY(addResult == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } selfHandle->clazz_.set(runtime, *addResult->first, &runtime->getHeap()); allocateNewSlotStorage( selfHandle, runtime, addResult->second, valueOrAccessor); // If this is an index-like property, we need to clear the fast path flags. if (LLVM_UNLIKELY( selfHandle->clazz_.getNonNull(runtime)->getHasIndexLikeProperties())) selfHandle->flags_.fastIndexProperties = false; return ExecutionStatus::RETURNED; } CallResult<bool> JSObject::updateOwnProperty( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, HiddenClass::PropertyPos propertyPos, NamedPropertyDescriptor desc, const DefinePropertyFlags dpFlags, Handle<> valueOrAccessor, PropOpFlags opFlags) { auto updateStatus = checkPropertyUpdate( runtime, desc.flags, dpFlags, getNamedSlotValue(selfHandle.get(), runtime, desc), valueOrAccessor, opFlags); if (updateStatus == ExecutionStatus::EXCEPTION) return ExecutionStatus::EXCEPTION; if (updateStatus->first == PropertyUpdateStatus::failed) return false; // If the property flags changed, update them. if (updateStatus->second != desc.flags) { desc.flags = updateStatus->second; auto newClazz = HiddenClass::updateProperty( runtime->makeHandle(selfHandle->clazz_), runtime, propertyPos, desc.flags); selfHandle->clazz_.set(runtime, *newClazz, &runtime->getHeap()); } if (updateStatus->first == PropertyUpdateStatus::done) return true; assert( updateStatus->first == PropertyUpdateStatus::needSet && "unexpected PropertyUpdateStatus"); if (dpFlags.setValue) { if (LLVM_LIKELY(!desc.flags.internalSetter)) setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get()); else return internalSetter( selfHandle, runtime, name, desc, valueOrAccessor, opFlags); } else if (dpFlags.isAccessor()) { setNamedSlotValue(selfHandle.get(), runtime, desc, valueOrAccessor.get()); } else { // If checkPropertyUpdate() returned needSet, but there is no value or // accessor, clear the value. setNamedSlotValue( selfHandle.get(), runtime, desc, HermesValue::encodeUndefinedValue()); } return true; } CallResult<std::pair<JSObject::PropertyUpdateStatus, PropertyFlags>> JSObject::checkPropertyUpdate( Runtime *runtime, const PropertyFlags currentFlags, DefinePropertyFlags dpFlags, const HermesValue curValueOrAccessor, Handle<> valueOrAccessor, PropOpFlags opFlags) { // 8.12.9 [5] Return true, if every field in Desc is absent. if (dpFlags.isEmpty()) return std::make_pair(PropertyUpdateStatus::done, currentFlags); assert( (!dpFlags.isAccessor() || (!dpFlags.setWritable && !dpFlags.writable)) && "can't set both accessor and writable"); assert( !dpFlags.enableInternalSetter && "cannot change the value of internalSetter"); // 8.12.9 [6] Return true, if every field in Desc also occurs in current and // the value of every field in Desc is the same value as the corresponding // field in current when compared using the SameValue algorithm (9.12). // TODO: this would probably be much more efficient with bitmasks. if ((!dpFlags.setEnumerable || dpFlags.enumerable == currentFlags.enumerable) && (!dpFlags.setConfigurable || dpFlags.configurable == currentFlags.configurable)) { if (dpFlags.isAccessor()) { if (currentFlags.accessor) { auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor); auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get()); if ((!dpFlags.setGetter || curAccessor->getter == newAccessor->getter) && (!dpFlags.setSetter || curAccessor->setter == newAccessor->setter)) { return std::make_pair(PropertyUpdateStatus::done, currentFlags); } } } else { if (!currentFlags.accessor && (!dpFlags.setValue || isSameValue(curValueOrAccessor, valueOrAccessor.get())) && (!dpFlags.setWritable || dpFlags.writable == currentFlags.writable)) { return std::make_pair(PropertyUpdateStatus::done, currentFlags); } } } // 8.12.9 [7] // If the property is not configurable, some aspects are not changeable. if (!currentFlags.configurable) { // Trying to change non-configurable to configurable? if (dpFlags.configurable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } // Trying to change the enumerability of non-configurable property? if (dpFlags.setEnumerable && dpFlags.enumerable != currentFlags.enumerable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } } PropertyFlags newFlags = currentFlags; // 8.12.9 [8] If IsGenericDescriptor(Desc) is true, then no further validation // is required. if (!(dpFlags.setValue || dpFlags.setWritable || dpFlags.setGetter || dpFlags.setSetter)) { // Do nothing } // 8.12.9 [9] // Changing between accessor and data descriptor? else if (currentFlags.accessor != dpFlags.isAccessor()) { if (!currentFlags.configurable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } // If we change from accessor to data descriptor, Preserve the existing // values of the converted property’s [[Configurable]] and [[Enumerable]] // attributes and set the rest of the property’s attributes to their default // values. // If it's the other way around, since the accessor doesn't have the // [[Writable]] attribute, do nothing. newFlags.writable = 0; // If we are changing from accessor to non-accessor, we must set a new // value. if (!dpFlags.isAccessor()) dpFlags.setValue = 1; } // 8.12.9 [10] if both are data descriptors. else if (!currentFlags.accessor) { if (!currentFlags.configurable) { if (!currentFlags.writable) { // If the current property is not writable, but the new one is. if (dpFlags.writable) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } // If we are setting a different value. if (dpFlags.setValue && !isSameValue(curValueOrAccessor, valueOrAccessor.get())) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not writable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } } } } // 8.12.9 [11] Both are accessors. else { auto *curAccessor = vmcast<PropertyAccessor>(curValueOrAccessor); auto *newAccessor = vmcast<PropertyAccessor>(valueOrAccessor.get()); // If not configurable, make sure that nothing is changing. if (!currentFlags.configurable) { if ((dpFlags.setGetter && newAccessor->getter != curAccessor->getter) || (dpFlags.setSetter && newAccessor->setter != curAccessor->setter)) { if (opFlags.getThrowOnError()) { return runtime->raiseTypeError( "property is not configurable"); // TODO: better message. } return std::make_pair(PropertyUpdateStatus::failed, PropertyFlags{}); } } // If not setting the getter or the setter, re-use the current one. if (!dpFlags.setGetter) newAccessor->getter.set( runtime, curAccessor->getter, &runtime->getHeap()); if (!dpFlags.setSetter) newAccessor->setter.set( runtime, curAccessor->setter, &runtime->getHeap()); } // 8.12.9 [12] For each attribute field of Desc that is present, set the // correspondingly named attribute of the property named P of object O to the // value of the field. if (dpFlags.setEnumerable) newFlags.enumerable = dpFlags.enumerable; if (dpFlags.setWritable) newFlags.writable = dpFlags.writable; if (dpFlags.setConfigurable) newFlags.configurable = dpFlags.configurable; if (dpFlags.setValue) newFlags.accessor = false; else if (dpFlags.isAccessor()) newFlags.accessor = true; else return std::make_pair(PropertyUpdateStatus::done, newFlags); return std::make_pair(PropertyUpdateStatus::needSet, newFlags); } CallResult<bool> JSObject::internalSetter( Handle<JSObject> selfHandle, Runtime *runtime, SymbolID name, NamedPropertyDescriptor /*desc*/, Handle<> value, PropOpFlags opFlags) { if (vmisa<JSArray>(selfHandle.get())) { if (name == Predefined::getSymbolID(Predefined::length)) { return JSArray::setLength( Handle<JSArray>::vmcast(selfHandle), runtime, value, opFlags); } } llvm_unreachable("unhandled property in Object::internalSetter()"); } namespace { /// Helper function to add all the property names of an object to an /// array, starting at the given index. Only enumerable properties are /// incluced. Returns the index after the last property added, but... CallResult<uint32_t> appendAllPropertyNames( Handle<JSObject> obj, Runtime *runtime, MutableHandle<BigStorage> &arr, uint32_t beginIndex) { uint32_t size = beginIndex; // We know that duplicate property names can only exist between objects in // the prototype chain. Hence there should not be duplicated properties // before we start to look at any prototype. bool needDedup = false; MutableHandle<> prop(runtime); MutableHandle<JSObject> head(runtime, obj.get()); MutableHandle<StringPrimitive> tmpVal{runtime}; while (head.get()) { GCScope gcScope(runtime); // enumerableProps will contain all enumerable own properties from obj. // Impl note: this is the only place where getOwnPropertyKeys will be // called without IncludeNonEnumerable on a Proxy. Everywhere else, // trap ordering is specified but ES9 13.7.5.15 says "The mechanics and // order of enumerating the properties is not specified", which is // unusual. auto cr = JSObject::getOwnPropertyNames(head, runtime, true /* onlyEnumerable */); if (LLVM_UNLIKELY(cr == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } auto enumerableProps = *cr; auto marker = gcScope.createMarker(); for (unsigned i = 0, e = enumerableProps->getEndIndex(); i < e; ++i) { gcScope.flushToMarker(marker); prop = enumerableProps->at(runtime, i); if (!needDedup) { // If no dedup is needed, add it directly. if (LLVM_UNLIKELY( BigStorage::push_back(arr, runtime, prop) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } ++size; continue; } // Otherwise loop through all existing properties and check if we // have seen it before. bool dupFound = false; if (prop->isNumber()) { for (uint32_t j = beginIndex; j < size && !dupFound; ++j) { HermesValue val = arr->at(j); if (val.isNumber()) { dupFound = val.getNumber() == prop->getNumber(); } else { // val is string, prop is number. tmpVal = val.getString(); auto valNum = toArrayIndex( StringPrimitive::createStringView(runtime, tmpVal)); dupFound = valNum && valNum.getValue() == prop->getNumber(); } } } else { for (uint32_t j = beginIndex; j < size && !dupFound; ++j) { HermesValue val = arr->at(j); if (val.isNumber()) { // val is number, prop is string. auto propNum = toArrayIndex(StringPrimitive::createStringView( runtime, Handle<StringPrimitive>::vmcast(prop))); dupFound = propNum && (propNum.getValue() == val.getNumber()); } else { dupFound = val.getString()->equals(prop->getString()); } } } if (LLVM_LIKELY(!dupFound)) { if (LLVM_UNLIKELY( BigStorage::push_back(arr, runtime, prop) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } ++size; } } // Continue to follow the prototype chain. CallResult<PseudoHandle<JSObject>> parentRes = JSObject::getPrototypeOf(head, runtime); if (LLVM_UNLIKELY(parentRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } head = parentRes->get(); needDedup = true; } return size; } /// Adds the hidden classes of the prototype chain of obj to arr, /// starting with the prototype of obj at index 0, etc., and /// terminates with null. /// /// \param obj The object whose prototype chain should be output /// \param[out] arr The array where the classes will be appended. This /// array is cleared if any object is unsuitable for caching. ExecutionStatus setProtoClasses( Runtime *runtime, Handle<JSObject> obj, MutableHandle<BigStorage> &arr) { // Layout of a JSArray stored in the for-in cache: // [class(proto(obj)), class(proto(proto(obj))), ..., null, prop0, prop1, ...] if (!obj->shouldCacheForIn(runtime)) { arr->clear(runtime); return ExecutionStatus::RETURNED; } MutableHandle<JSObject> head(runtime, obj->getParent(runtime)); MutableHandle<> clazz(runtime); GCScopeMarkerRAII marker{runtime}; while (head.get()) { if (!head->shouldCacheForIn(runtime)) { arr->clear(runtime); return ExecutionStatus::RETURNED; } if (JSObject::Helper::flags(*head).lazyObject) { // Ensure all properties have been initialized before caching the hidden // class. Not doing this will result in changes to the hidden class // when getOwnPropertyKeys is called later. JSObject::initializeLazyObject(runtime, head); } clazz = HermesValue::encodeObjectValue(head->getClass(runtime)); if (LLVM_UNLIKELY( BigStorage::push_back(arr, runtime, clazz) == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } head = head->getParent(runtime); marker.flush(); } clazz = HermesValue::encodeNullValue(); return BigStorage::push_back(arr, runtime, clazz); } /// Verifies that the classes of obj's prototype chain still matches those /// previously prefixed to arr by setProtoClasses. /// /// \param obj The object whose prototype chain should be verified /// \param arr Array previously populated by setProtoClasses /// \return The index after the terminating null if everything matches, /// otherwise 0. uint32_t matchesProtoClasses( Runtime *runtime, Handle<JSObject> obj, Handle<BigStorage> arr) { MutableHandle<JSObject> head(runtime, obj->getParent(runtime)); uint32_t i = 0; while (head.get()) { HermesValue protoCls = arr->at(i++); if (protoCls.isNull() || protoCls.getObject() != head->getClass(runtime) || head->isProxyObject()) { return 0; } head = head->getParent(runtime); } // The chains must both end at the same point. if (head || !arr->at(i++).isNull()) { return 0; } assert(i > 0 && "success should be positive"); return i; } } // namespace CallResult<Handle<BigStorage>> getForInPropertyNames( Runtime *runtime, Handle<JSObject> obj, uint32_t &beginIndex, uint32_t &endIndex) { Handle<HiddenClass> clazz(runtime, obj->getClass(runtime)); // Fast case: Check the cache. MutableHandle<BigStorage> arr(runtime, clazz->getForInCache(runtime)); if (arr) { beginIndex = matchesProtoClasses(runtime, obj, arr); if (beginIndex) { // Cache is valid for this object, so use it. endIndex = arr->size(); return arr; } // Invalid for this object. We choose to clear the cache since the // changes to the prototype chain probably affect other objects too. clazz->clearForInCache(runtime); // Clear arr to slightly reduce risk of OOM from allocation below. arr = nullptr; } // Slow case: Build the array of properties. auto ownPropEstimate = clazz->getNumProperties(); auto arrRes = obj->shouldCacheForIn(runtime) ? BigStorage::createLongLived(runtime, ownPropEstimate) : BigStorage::create(runtime, ownPropEstimate); if (LLVM_UNLIKELY(arrRes == ExecutionStatus::EXCEPTION)) { return ExecutionStatus::EXCEPTION; } arr = std::move(*arrRes); if (setProtoClasses(runtime, obj, arr) == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } beginIndex = arr->size(); // If obj or any of its prototypes are unsuitable for caching, then // beginIndex is 0 and we return an array with only the property names. bool canCache = beginIndex; auto end = appendAllPropertyNames(obj, runtime, arr, beginIndex); if (end == ExecutionStatus::EXCEPTION) { return ExecutionStatus::EXCEPTION; } endIndex = *end; // Avoid degenerate memory explosion: if > 75% of the array is properties // or classes from prototypes, then don't cache it. const bool tooMuchProto = *end / 4 > ownPropEstimate; if (canCache && !tooMuchProto) { assert(beginIndex > 0 && "cached array must start with proto classes"); #ifdef HERMES_SLOW_DEBUG assert(beginIndex == matchesProtoClasses(runtime, obj, arr) && "matches"); #endif clazz->setForInCache(*arr, runtime); } return arr; } //===----------------------------------------------------------------------===// // class PropertyAccessor VTable PropertyAccessor::vt{CellKind::PropertyAccessorKind, cellSize<PropertyAccessor>()}; void PropertyAccessorBuildMeta(const GCCell *cell, Metadata::Builder &mb) { const auto *self = static_cast<const PropertyAccessor *>(cell); mb.addField("getter", &self->getter); mb.addField("setter", &self->setter); } #ifdef HERMESVM_SERIALIZE PropertyAccessor::PropertyAccessor(Deserializer &d) : GCCell(&d.getRuntime()->getHeap(), &vt) { d.readRelocation(&getter, RelocationKind::GCPointer); d.readRelocation(&setter, RelocationKind::GCPointer); } void PropertyAccessorSerialize(Serializer &s, const GCCell *cell) { auto *self = vmcast<const PropertyAccessor>(cell); s.writeRelocation(self->getter.get(s.getRuntime())); s.writeRelocation(self->setter.get(s.getRuntime())); s.endObject(cell); } void PropertyAccessorDeserialize(Deserializer &d, CellKind kind) { assert(kind == CellKind::PropertyAccessorKind && "Expected PropertyAccessor"); void *mem = d.getRuntime()->alloc(cellSize<PropertyAccessor>()); auto *cell = new (mem) PropertyAccessor(d); d.endObject(cell); } #endif CallResult<HermesValue> PropertyAccessor::create( Runtime *runtime, Handle<Callable> getter, Handle<Callable> setter) { void *mem = runtime->alloc(cellSize<PropertyAccessor>()); return HermesValue::encodeObjectValue( new (mem) PropertyAccessor(runtime, *getter, *setter)); } } // namespace vm } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_4259_0
crossvul-cpp_data_bad_2804_2
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, int count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width*3*tiff_bps/8; if(tiff_bps <= 8) gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten=0, isix, i, buffer=0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i=0; i < 16; i+=2) raw_image[todo[i]] = (todo[i+1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row,col) = pred[col & 1]) > 4098 && col < width) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[256]; int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) if ((RAW(row,col+i) = curve[ret ? buf[i] : (pred[i & 1] += buf[i])]) >> 12) derror(); } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c=0; c < 16; c+=2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) + (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min=~(max=0)) && (col+=2) < width-3 && row > 2) row--; } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char* pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos+7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos+7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy (ccms, pos, l); ccms[l] = '\0'; pos = strtok (ccms, ","); for (l=0; l<4; l++) { num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok (NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(),get4()))); aperture = powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[]={0,0}; FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if(len<1) return; // not needed, b/c sizeof of make/model is 64 string[len-1]=0; if(len<3) return; // also not needed len = strnlen(string,len-1); for(int i=len-1; i>=0; i--) { if(isspace(string[i])) string[i]=0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_2804_2
crossvul-cpp_data_bad_3218_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_3218_0
crossvul-cpp_data_good_1380_1
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/bz2/bz2-file.h" #include "hphp/runtime/base/array-init.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// BZ2File::BZ2File(): m_bzFile(nullptr), m_innerFile(req::make<PlainFile>()) { m_innerFile->unregister(); setIsLocal(m_innerFile->isLocal()); } BZ2File::BZ2File(req::ptr<PlainFile>&& innerFile) : m_bzFile(nullptr), m_innerFile(std::move(innerFile)) { setIsLocal(m_innerFile->isLocal()); } BZ2File::~BZ2File() { closeImpl(); } void BZ2File::sweep() { closeImpl(); File::sweep(); } bool BZ2File::open(const String& filename, const String& mode) { assertx(m_bzFile == nullptr); return m_innerFile->open(filename, mode) && (m_bzFile = BZ2_bzdopen(dup(m_innerFile->fd()), mode.data())); } bool BZ2File::close() { invokeFiltersOnClose(); return closeImpl(); } int64_t BZ2File::errnu() { assertx(m_bzFile); int errnum = 0; BZ2_bzerror(m_bzFile, &errnum); return errnum; } String BZ2File::errstr() { assertx(m_bzFile); int errnum; return BZ2_bzerror(m_bzFile, &errnum); } const StaticString s_errno("errno"), s_errstr("errstr"); Array BZ2File::error() { assertx(m_bzFile); int errnum; const char * errstr; errstr = BZ2_bzerror(m_bzFile, &errnum); return make_map_array(s_errno, errnum, s_errstr, String(errstr)); } bool BZ2File::flush() { assertx(m_bzFile); return BZ2_bzflush(m_bzFile); } int64_t BZ2File::readImpl(char * buf, int64_t length) { if (length == 0) { return 0; } assertx(m_bzFile); int len = BZ2_bzread(m_bzFile, buf, length); /* Sometimes libbz2 will return fewer bytes than requested, and set bzerror * to BZ_STREAM_END, but it's not actually EOF, and you can keep reading from * the file - so, only set EOF after a failed read. This matches PHP5. */ if (len <= 0) { setEof(true); if (len < 0) { return 0; } } return len; } int64_t BZ2File::writeImpl(const char * buf, int64_t length) { assertx(m_bzFile); return BZ2_bzwrite(m_bzFile, (char *)buf, length); } bool BZ2File::closeImpl() { if (!isClosed()) { if (m_bzFile) { BZ2_bzclose(m_bzFile); m_bzFile = nullptr; } setIsClosed(true); if (m_innerFile) { m_innerFile->close(); } } File::closeImpl(); return true; } bool BZ2File::eof() { assertx(m_bzFile); return getEof(); } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_1380_1
crossvul-cpp_data_bad_849_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/EventBase.h> #include <folly/portability/Sockets.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <chrono> #include <memory> #include <folly/Format.h> #include <folly/Indestructible.h> #include <folly/SocketAddress.h> #include <folly/SpinLock.h> #include <folly/io/Cursor.h> #include <folly/io/IOBuf.h> #include <folly/io/async/ssl/BasicTransportCertificate.h> #include <folly/lang/Bits.h> #include <folly/portability/OpenSSL.h> using folly::SocketAddress; using folly::SSLContext; using std::shared_ptr; using std::string; using folly::Endian; using folly::IOBuf; using folly::SpinLock; using folly::SpinLockGuard; using folly::io::Cursor; using std::bind; using std::unique_ptr; namespace { using folly::AsyncSocket; using folly::AsyncSocketException; using folly::AsyncSSLSocket; using folly::Optional; using folly::SSLContext; // For OpenSSL portability API using namespace folly::ssl; using folly::ssl::OpenSSLUtils; // We have one single dummy SSL context so that we can implement attach // and detach methods in a thread safe fashion without modifying opnessl. static SSLContext* dummyCtx = nullptr; static SpinLock dummyCtxLock; // If given min write size is less than this, buffer will be allocated on // stack, otherwise it is allocated on heap const size_t MAX_STACK_BUF_SIZE = 2048; // This converts "illegal" shutdowns into ZERO_RETURN inline bool zero_return(int error, int rc, int errno_copy) { if (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno_copy == 0)) { return true; } #ifdef _WIN32 // on windows underlying TCP socket may error with this code // if the sending/receiving client crashes or is killed if (error == SSL_ERROR_SYSCALL && errno_copy == WSAECONNRESET) { return true; } #endif return false; } class AsyncSSLSocketConnector : public AsyncSocket::ConnectCallback, public AsyncSSLSocket::HandshakeCB { private: AsyncSSLSocket* sslSocket_; AsyncSSLSocket::ConnectCallback* callback_; std::chrono::milliseconds timeout_; std::chrono::steady_clock::time_point startTime_; protected: ~AsyncSSLSocketConnector() override {} public: AsyncSSLSocketConnector( AsyncSSLSocket* sslSocket, AsyncSocket::ConnectCallback* callback, std::chrono::milliseconds timeout) : sslSocket_(sslSocket), callback_(callback), timeout_(timeout), startTime_(std::chrono::steady_clock::now()) {} void preConnect(folly::NetworkSocket fd) override { VLOG(7) << "client preConnect hook is invoked"; if (callback_) { callback_->preConnect(fd); } } void connectSuccess() noexcept override { VLOG(7) << "client socket connected"; std::chrono::milliseconds timeoutLeft{0}; if (timeout_ > std::chrono::milliseconds::zero()) { auto curTime = std::chrono::steady_clock::now(); timeoutLeft = std::chrono::duration_cast<std::chrono::milliseconds>( timeout_ - (curTime - startTime_)); if (timeoutLeft <= std::chrono::milliseconds::zero()) { AsyncSocketException ex( AsyncSocketException::TIMED_OUT, folly::sformat( "SSL connect timed out after {}ms", timeout_.count())); fail(ex); delete this; return; } } sslSocket_->sslConn(this, timeoutLeft); } void connectErr(const AsyncSocketException& ex) noexcept override { VLOG(1) << "TCP connect failed: " << ex.what(); fail(ex); delete this; } void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override { VLOG(7) << "client handshake success"; if (callback_) { callback_->connectSuccess(); } delete this; } void handshakeErr( AsyncSSLSocket* /* socket */, const AsyncSocketException& ex) noexcept override { VLOG(1) << "client handshakeErr: " << ex.what(); fail(ex); delete this; } void fail(const AsyncSocketException& ex) { // fail is a noop if called twice if (callback_) { AsyncSSLSocket::ConnectCallback* cb = callback_; callback_ = nullptr; cb->connectErr(ex); sslSocket_->closeNow(); // closeNow can call handshakeErr if it hasn't been called already. // So this may have been deleted, no member variable access beyond this // point // Note that closeNow may invoke writeError callbacks if the socket had // write data pending connection completion. } } }; void setup_SSL_CTX(SSL_CTX* ctx) { #ifdef SSL_MODE_RELEASE_BUFFERS SSL_CTX_set_mode( ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_RELEASE_BUFFERS); #else SSL_CTX_set_mode( ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE); #endif // SSL_CTX_set_mode is a Macro #ifdef SSL_MODE_WRITE_IOVEC SSL_CTX_set_mode(ctx, SSL_CTX_get_mode(ctx) | SSL_MODE_WRITE_IOVEC); #endif } // Note: This is a Leaky Meyer's Singleton. The reason we can't use a non-leaky // thing is because we will be setting this BIO_METHOD* inside BIOs owned by // various SSL objects which may get callbacks even during teardown. We may // eventually try to fix this static BIO_METHOD* getSSLBioMethod() { static auto const instance = OpenSSLUtils::newSocketBioMethod().release(); return instance; } void* initsslBioMethod() { auto sslBioMethod = getSSLBioMethod(); // override the bwrite method for MSG_EOR support OpenSSLUtils::setCustomBioWriteMethod(sslBioMethod, AsyncSSLSocket::bioWrite); OpenSSLUtils::setCustomBioReadMethod(sslBioMethod, AsyncSSLSocket::bioRead); // Note that the sslBioMethod.type and sslBioMethod.name are not // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and // then have specific handlings. The sslWriteBioWrite should be compatible // with the one in openssl. // Return something here to enable AsyncSSLSocket to call this method using // a function-scoped static. return nullptr; } } // namespace namespace folly { /** * Create a client AsyncSSLSocket */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, bool deferSecurityNegotiation) : AsyncSocket(evb), ctx_(ctx), handshakeTimeout_(this, evb), connectionTimeout_(this, evb) { init(); if (deferSecurityNegotiation) { sslState_ = STATE_UNENCRYPTED; } } /** * Create a server/client AsyncSSLSocket */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, NetworkSocket fd, bool server, bool deferSecurityNegotiation) : AsyncSocket(evb, fd), server_(server), ctx_(ctx), handshakeTimeout_(this, evb), connectionTimeout_(this, evb) { noTransparentTls_ = true; init(); if (server) { SSL_CTX_set_info_callback( ctx_->getSSLCtx(), AsyncSSLSocket::sslInfoCallback); } if (deferSecurityNegotiation) { sslState_ = STATE_UNENCRYPTED; } } AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, AsyncSocket::UniquePtr oldAsyncSocket, bool server, bool deferSecurityNegotiation) : AsyncSocket(std::move(oldAsyncSocket)), server_(server), ctx_(ctx), handshakeTimeout_(this, AsyncSocket::getEventBase()), connectionTimeout_(this, AsyncSocket::getEventBase()) { noTransparentTls_ = true; init(); if (server) { SSL_CTX_set_info_callback( ctx_->getSSLCtx(), AsyncSSLSocket::sslInfoCallback); } if (deferSecurityNegotiation) { sslState_ = STATE_UNENCRYPTED; } } #if FOLLY_OPENSSL_HAS_SNI /** * Create a client AsyncSSLSocket and allow tlsext_hostname * to be sent in Client Hello. */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, const std::string& serverName, bool deferSecurityNegotiation) : AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) { tlsextHostname_ = serverName; } /** * Create a client AsyncSSLSocket from an already connected fd * and allow tlsext_hostname to be sent in Client Hello. */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, NetworkSocket fd, const std::string& serverName, bool deferSecurityNegotiation) : AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) { tlsextHostname_ = serverName; } #endif // FOLLY_OPENSSL_HAS_SNI AsyncSSLSocket::~AsyncSSLSocket() { VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this << ", evb=" << eventBase_ << ", fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << ")"; } void AsyncSSLSocket::init() { // Do this here to ensure we initialize this once before any use of // AsyncSSLSocket instances and not as part of library load. static const auto sslBioMethodInitializer = initsslBioMethod(); (void)sslBioMethodInitializer; setup_SSL_CTX(ctx_->getSSLCtx()); } void AsyncSSLSocket::closeNow() { // Close the SSL connection. if (ssl_ != nullptr && fd_ != NetworkSocket() && !waitingOnAccept_) { int rc = SSL_shutdown(ssl_.get()); if (rc == 0) { rc = SSL_shutdown(ssl_.get()); } if (rc < 0) { ERR_clear_error(); } } if (sslSession_ != nullptr) { SSL_SESSION_free(sslSession_); sslSession_ = nullptr; } sslState_ = STATE_CLOSED; if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } DestructorGuard dg(this); static const Indestructible<AsyncSocketException> ex( AsyncSocketException::END_OF_FILE, "SSL connection closed locally"); invokeHandshakeErr(*ex); // Close the socket. AsyncSocket::closeNow(); } void AsyncSSLSocket::shutdownWrite() { // SSL sockets do not support half-shutdown, so just perform a full shutdown. // // (Performing a full shutdown here is more desirable than doing nothing at // all. The purpose of shutdownWrite() is normally to notify the other end // of the connection that no more data will be sent. If we do nothing, the // other end will never know that no more data is coming, and this may result // in protocol deadlock.) close(); } void AsyncSSLSocket::shutdownWriteNow() { closeNow(); } bool AsyncSSLSocket::good() const { return ( AsyncSocket::good() && (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING || sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED || sslState_ == STATE_UNINIT)); } // The TAsyncTransport definition of 'good' states that the transport is // ready to perform reads and writes, so sslState_ == UNINIT must report !good. // connecting can be true when the sslState_ == UNINIT because the AsyncSocket // is connected but we haven't initiated the call to SSL_connect. bool AsyncSSLSocket::connecting() const { return ( !server_ && (AsyncSocket::connecting() || (AsyncSocket::good() && (sslState_ == STATE_UNINIT || sslState_ == STATE_CONNECTING)))); } std::string AsyncSSLSocket::getApplicationProtocol() const noexcept { const unsigned char* protoName = nullptr; unsigned protoLength; if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) { return std::string(reinterpret_cast<const char*>(protoName), protoLength); } return ""; } void AsyncSSLSocket::setEorTracking(bool track) { if (isEorTrackingEnabled() != track) { AsyncSocket::setEorTracking(track); appEorByteNo_ = 0; appEorByteWriteFlags_ = {}; minEorRawByteNo_ = 0; } } size_t AsyncSSLSocket::getRawBytesWritten() const { // The bio(s) in the write path are in a chain // each bio flushes to the next and finally written into the socket // to get the rawBytesWritten on the socket, // get the write bytes of the last bio BIO* b; if (!ssl_ || !(b = SSL_get_wbio(ssl_.get()))) { return 0; } BIO* next = BIO_next(b); while (next != nullptr) { b = next; next = BIO_next(b); } return BIO_number_written(b); } size_t AsyncSSLSocket::getRawBytesReceived() const { BIO* b; if (!ssl_ || !(b = SSL_get_rbio(ssl_.get()))) { return 0; } return BIO_number_read(b); } void AsyncSSLSocket::invalidState(HandshakeCB* callback) { LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", " << "events=" << eventFlags_ << ", server=" << short(server_) << "): " << "sslAccept/Connect() called in invalid " << "state, handshake callback " << handshakeCallback_ << ", new callback " << callback; assert(!handshakeTimeout_.isScheduled()); sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INVALID_STATE, "sslAccept() called with socket in invalid state"); handshakeEndTime_ = std::chrono::steady_clock::now(); if (callback) { callback->handshakeErr(this, *ex); } failHandshake(__func__, *ex); } void AsyncSSLSocket::sslAccept( HandshakeCB* callback, std::chrono::milliseconds timeout, const SSLContext::SSLVerifyPeerEnum& verifyPeer) { DestructorGuard dg(this); eventBase_->dcheckIsInEventBaseThread(); verifyPeer_ = verifyPeer; // Make sure we're in the uninitialized state if (!server_ || (sslState_ != STATE_UNINIT && sslState_ != STATE_UNENCRYPTED) || handshakeCallback_ != nullptr) { return invalidState(callback); } // Cache local and remote socket addresses to keep them available // after socket file descriptor is closed. if (cacheAddrOnFailure_) { cacheAddresses(); } handshakeStartTime_ = std::chrono::steady_clock::now(); // Make end time at least >= start time. handshakeEndTime_ = handshakeStartTime_; sslState_ = STATE_ACCEPTING; handshakeCallback_ = callback; if (timeout > std::chrono::milliseconds::zero()) { handshakeTimeout_.scheduleTimeout(timeout); } /* register for a read operation (waiting for CLIENT HELLO) */ updateEventRegistration(EventHandler::READ, EventHandler::WRITE); checkForImmediateRead(); } void AsyncSSLSocket::attachSSLContext(const std::shared_ptr<SSLContext>& ctx) { // Check to ensure we are in client mode. Changing a server's ssl // context doesn't make sense since clients of that server would likely // become confused when the server's context changes. DCHECK(!server_); DCHECK(!ctx_); DCHECK(ctx); DCHECK(ctx->getSSLCtx()); ctx_ = ctx; // It's possible this could be attached before ssl_ is set up if (!ssl_) { return; } // In order to call attachSSLContext, detachSSLContext must have been // previously called. // We need to update the initial_ctx if necessary // The 'initial_ctx' inside an SSL* points to the context that it was created // with, which is also where session callbacks and servername callbacks // happen. // When we switch to a different SSL_CTX, we want to update the initial_ctx as // well so that any callbacks don't go to a different object // NOTE: this will only work if we have access to ssl_ internals, so it may // not work on // OpenSSL version >= 1.1.0 auto sslCtx = ctx->getSSLCtx(); OpenSSLUtils::setSSLInitialCtx(ssl_.get(), sslCtx); // Detach sets the socket's context to the dummy context. Thus we must acquire // this lock. SpinLockGuard guard(dummyCtxLock); SSL_set_SSL_CTX(ssl_.get(), sslCtx); } void AsyncSSLSocket::detachSSLContext() { DCHECK(ctx_); ctx_.reset(); // It's possible for this to be called before ssl_ has been // set up if (!ssl_) { return; } // The 'initial_ctx' inside an SSL* points to the context that it was created // with, which is also where session callbacks and servername callbacks // happen. // Detach the initial_ctx as well. It will be reattached in attachSSLContext // it is used for session info. // NOTE: this will only work if we have access to ssl_ internals, so it may // not work on // OpenSSL version >= 1.1.0 SSL_CTX* initialCtx = OpenSSLUtils::getSSLInitialCtx(ssl_.get()); if (initialCtx) { SSL_CTX_free(initialCtx); OpenSSLUtils::setSSLInitialCtx(ssl_.get(), nullptr); } SpinLockGuard guard(dummyCtxLock); if (nullptr == dummyCtx) { // We need to lazily initialize the dummy context so we don't // accidentally override any programmatic settings to openssl dummyCtx = new SSLContext; } // We must remove this socket's references to its context right now // since this socket could get passed to any thread. If the context has // had its locking disabled, just doing a set in attachSSLContext() // would not be thread safe. SSL_set_SSL_CTX(ssl_.get(), dummyCtx->getSSLCtx()); } #if FOLLY_OPENSSL_HAS_SNI void AsyncSSLSocket::switchServerSSLContext( const std::shared_ptr<SSLContext>& handshakeCtx) { CHECK(server_); if (sslState_ != STATE_ACCEPTING) { // We log it here and allow the switch. // It should not affect our re-negotiation support (which // is not supported now). VLOG(6) << "fd=" << getNetworkSocket() << " renegotation detected when switching SSL_CTX"; } setup_SSL_CTX(handshakeCtx->getSSLCtx()); SSL_CTX_set_info_callback( handshakeCtx->getSSLCtx(), AsyncSSLSocket::sslInfoCallback); handshakeCtx_ = handshakeCtx; SSL_set_SSL_CTX(ssl_.get(), handshakeCtx->getSSLCtx()); } bool AsyncSSLSocket::isServerNameMatch() const { CHECK(!server_); if (!ssl_) { return false; } SSL_SESSION* ss = SSL_get_session(ssl_.get()); if (!ss) { return false; } auto tlsextHostname = SSL_SESSION_get0_hostname(ss); return (tlsextHostname && !tlsextHostname_.compare(tlsextHostname)); } void AsyncSSLSocket::setServerName(std::string serverName) noexcept { tlsextHostname_ = std::move(serverName); } #endif // FOLLY_OPENSSL_HAS_SNI void AsyncSSLSocket::timeoutExpired( std::chrono::milliseconds timeout) noexcept { if (state_ == StateEnum::ESTABLISHED && sslState_ == STATE_ASYNC_PENDING) { sslState_ = STATE_ERROR; // We are expecting a callback in restartSSLAccept. The cache lookup // and rsa-call necessarily have pointers to this ssl socket, so delay // the cleanup until he calls us back. } else if (state_ == StateEnum::CONNECTING) { assert(sslState_ == STATE_CONNECTING); DestructorGuard dg(this); static const Indestructible<AsyncSocketException> ex( AsyncSocketException::TIMED_OUT, "Fallback connect timed out during TFO"); failHandshake(__func__, *ex); } else { assert( state_ == StateEnum::ESTABLISHED && (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING)); DestructorGuard dg(this); AsyncSocketException ex( AsyncSocketException::TIMED_OUT, folly::sformat( "SSL {} timed out after {}ms", (sslState_ == STATE_CONNECTING) ? "connect" : "accept", timeout.count())); failHandshake(__func__, ex); } } int AsyncSSLSocket::getSSLExDataIndex() { static auto index = SSL_get_ex_new_index( 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr); return index; } AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL* ssl) { return static_cast<AsyncSSLSocket*>( SSL_get_ex_data(ssl, getSSLExDataIndex())); } void AsyncSSLSocket::failHandshake( const char* /* fn */, const AsyncSocketException& ex) { startFail(); if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } invokeHandshakeErr(ex); finishFail(); } void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) { handshakeEndTime_ = std::chrono::steady_clock::now(); if (handshakeCallback_ != nullptr) { HandshakeCB* callback = handshakeCallback_; handshakeCallback_ = nullptr; callback->handshakeErr(this, ex); } } void AsyncSSLSocket::invokeHandshakeCB() { handshakeEndTime_ = std::chrono::steady_clock::now(); if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } if (handshakeCallback_) { HandshakeCB* callback = handshakeCallback_; handshakeCallback_ = nullptr; callback->handshakeSuc(this); } } void AsyncSSLSocket::connect( ConnectCallback* callback, const folly::SocketAddress& address, int timeout, const OptionMap& options, const folly::SocketAddress& bindAddr) noexcept { auto timeoutChrono = std::chrono::milliseconds(timeout); connect(callback, address, timeoutChrono, timeoutChrono, options, bindAddr); } void AsyncSSLSocket::connect( ConnectCallback* callback, const folly::SocketAddress& address, std::chrono::milliseconds connectTimeout, std::chrono::milliseconds totalConnectTimeout, const OptionMap& options, const folly::SocketAddress& bindAddr) noexcept { assert(!server_); assert(state_ == StateEnum::UNINIT); assert(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED); noTransparentTls_ = true; totalConnectTimeout_ = totalConnectTimeout; if (sslState_ != STATE_UNENCRYPTED) { callback = new AsyncSSLSocketConnector(this, callback, totalConnectTimeout); } AsyncSocket::connect( callback, address, int(connectTimeout.count()), options, bindAddr); } bool AsyncSSLSocket::needsPeerVerification() const { if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) { return ctx_->needsPeerVerification(); } return ( verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY || verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT); } void AsyncSSLSocket::applyVerificationOptions(const ssl::SSLUniquePtr& ssl) { // apply the settings specified in verifyPeer_ if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) { if (ctx_->needsPeerVerification()) { SSL_set_verify( ssl.get(), ctx_->getVerificationMode(), AsyncSSLSocket::sslVerifyCallback); } } else { if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY || verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) { SSL_set_verify( ssl.get(), SSLContext::getVerificationMode(verifyPeer_), AsyncSSLSocket::sslVerifyCallback); } } } bool AsyncSSLSocket::setupSSLBio() { auto sslBio = BIO_new(getSSLBioMethod()); if (!sslBio) { return false; } OpenSSLUtils::setBioAppData(sslBio, this); OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE); SSL_set_bio(ssl_.get(), sslBio, sslBio); return true; } void AsyncSSLSocket::sslConn( HandshakeCB* callback, std::chrono::milliseconds timeout, const SSLContext::SSLVerifyPeerEnum& verifyPeer) { DestructorGuard dg(this); eventBase_->dcheckIsInEventBaseThread(); // Cache local and remote socket addresses to keep them available // after socket file descriptor is closed. if (cacheAddrOnFailure_) { cacheAddresses(); } verifyPeer_ = verifyPeer; // Make sure we're in the uninitialized state if (server_ || (sslState_ != STATE_UNINIT && sslState_ != STATE_UNENCRYPTED) || handshakeCallback_ != nullptr) { return invalidState(callback); } sslState_ = STATE_CONNECTING; handshakeCallback_ = callback; try { ssl_.reset(ctx_->createSSL()); } catch (std::exception& e) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error calling SSLContext::createSSL()"); LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd=" << fd_ << "): " << e.what(); return failHandshake(__func__, *ex); } if (!setupSSLBio()) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio"); return failHandshake(__func__, *ex); } applyVerificationOptions(ssl_); if (sslSession_ != nullptr) { sessionResumptionAttempted_ = true; SSL_set_session(ssl_.get(), sslSession_); SSL_SESSION_free(sslSession_); sslSession_ = nullptr; } #if FOLLY_OPENSSL_HAS_SNI if (tlsextHostname_.size()) { SSL_set_tlsext_host_name(ssl_.get(), tlsextHostname_.c_str()); } #endif SSL_set_ex_data(ssl_.get(), getSSLExDataIndex(), this); handshakeConnectTimeout_ = timeout; startSSLConnect(); } // This could be called multiple times, during normal ssl connections // and after TFO fallback. void AsyncSSLSocket::startSSLConnect() { handshakeStartTime_ = std::chrono::steady_clock::now(); // Make end time at least >= start time. handshakeEndTime_ = handshakeStartTime_; if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) { handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_); } handleConnect(); } SSL_SESSION* AsyncSSLSocket::getSSLSession() { if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) { return SSL_get1_session(ssl_.get()); } return sslSession_; } const SSL* AsyncSSLSocket::getSSL() const { return ssl_.get(); } void AsyncSSLSocket::setSSLSession(SSL_SESSION* session, bool takeOwnership) { if (sslSession_) { SSL_SESSION_free(sslSession_); } sslSession_ = session; if (!takeOwnership && session != nullptr) { // Increment the reference count // This API exists in BoringSSL and OpenSSL 1.1.0 SSL_SESSION_up_ref(session); } } void AsyncSSLSocket::getSelectedNextProtocol( const unsigned char** protoName, unsigned* protoLen) const { if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) { throw AsyncSocketException( AsyncSocketException::NOT_SUPPORTED, "ALPN not supported"); } } bool AsyncSSLSocket::getSelectedNextProtocolNoThrow( const unsigned char** protoName, unsigned* protoLen) const { *protoName = nullptr; *protoLen = 0; #if FOLLY_OPENSSL_HAS_ALPN SSL_get0_alpn_selected(ssl_.get(), protoName, protoLen); return true; #else return false; #endif } bool AsyncSSLSocket::getSSLSessionReused() const { if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) { return SSL_session_reused(ssl_.get()); } return false; } const char* AsyncSSLSocket::getNegotiatedCipherName() const { return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_.get()) : nullptr; } /* static */ const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) { if (ssl == nullptr) { return nullptr; } #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); #else return nullptr; #endif } const char* AsyncSSLSocket::getSSLServerName() const { if (clientHelloInfo_ && !clientHelloInfo_->clientHelloSNIHostname_.empty()) { return clientHelloInfo_->clientHelloSNIHostname_.c_str(); } #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB return getSSLServerNameFromSSL(ssl_.get()); #else throw AsyncSocketException( AsyncSocketException::NOT_SUPPORTED, "SNI not supported"); #endif } const char* AsyncSSLSocket::getSSLServerNameNoThrow() const { if (clientHelloInfo_ && !clientHelloInfo_->clientHelloSNIHostname_.empty()) { return clientHelloInfo_->clientHelloSNIHostname_.c_str(); } return getSSLServerNameFromSSL(ssl_.get()); } int AsyncSSLSocket::getSSLVersion() const { return (ssl_ != nullptr) ? SSL_version(ssl_.get()) : 0; } const char* AsyncSSLSocket::getSSLCertSigAlgName() const { X509* cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_.get()) : nullptr; if (cert) { int nid = X509_get_signature_nid(cert); return OBJ_nid2ln(nid); } return nullptr; } int AsyncSSLSocket::getSSLCertSize() const { int certSize = 0; X509* cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_.get()) : nullptr; if (cert) { EVP_PKEY* key = X509_get_pubkey(cert); certSize = EVP_PKEY_bits(key); EVP_PKEY_free(key); } return certSize; } const AsyncTransportCertificate* AsyncSSLSocket::getPeerCertificate() const { if (peerCertData_) { return peerCertData_.get(); } if (ssl_ != nullptr) { auto peerX509 = SSL_get_peer_certificate(ssl_.get()); if (peerX509) { // already up ref'd folly::ssl::X509UniquePtr peer(peerX509); auto cn = OpenSSLUtils::getCommonName(peerX509); peerCertData_ = std::make_unique<BasicTransportCertificate>( std::move(cn), std::move(peer)); } } return peerCertData_.get(); } const AsyncTransportCertificate* AsyncSSLSocket::getSelfCertificate() const { if (selfCertData_) { return selfCertData_.get(); } if (ssl_ != nullptr) { auto selfX509 = SSL_get_certificate(ssl_.get()); if (selfX509) { // need to upref X509_up_ref(selfX509); folly::ssl::X509UniquePtr peer(selfX509); auto cn = OpenSSLUtils::getCommonName(selfX509); selfCertData_ = std::make_unique<BasicTransportCertificate>( std::move(cn), std::move(peer)); } } return selfCertData_.get(); } bool AsyncSSLSocket::willBlock( int ret, int* sslErrorOut, unsigned long* errErrorOut) noexcept { *errErrorOut = 0; int error = *sslErrorOut = SSL_get_error(ssl_.get(), ret); if (error == SSL_ERROR_WANT_READ) { // Register for read event if not already. updateEventRegistration(EventHandler::READ, EventHandler::WRITE); return true; } else if (error == SSL_ERROR_WANT_WRITE) { VLOG(3) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "SSL_ERROR_WANT_WRITE"; // Register for write event if not already. updateEventRegistration(EventHandler::WRITE, EventHandler::READ); return true; } else if ((false #ifdef SSL_ERROR_WANT_ASYNC // OpenSSL 1.1.0 Async API || error == SSL_ERROR_WANT_ASYNC #endif )) { // An asynchronous request has been kicked off. On completion, it will // invoke a callback to re-call handleAccept sslState_ = STATE_ASYNC_PENDING; // Unregister for all events while blocked here updateEventRegistration( EventHandler::NONE, EventHandler::READ | EventHandler::WRITE); #ifdef SSL_ERROR_WANT_ASYNC if (error == SSL_ERROR_WANT_ASYNC) { size_t numfds; if (SSL_get_all_async_fds(ssl_.get(), NULL, &numfds) <= 0) { VLOG(4) << "SSL_ERROR_WANT_ASYNC but no async FDs set!"; return false; } if (numfds != 1) { VLOG(4) << "SSL_ERROR_WANT_ASYNC expected exactly 1 async fd, got " << numfds; return false; } OSSL_ASYNC_FD ofd; // This should just be an int in POSIX if (SSL_get_all_async_fds(ssl_.get(), &ofd, &numfds) <= 0) { VLOG(4) << "SSL_ERROR_WANT_ASYNC cant get async fd"; return false; } // On POSIX systems, OSSL_ASYNC_FD is type int, but on win32 // it has type HANDLE. // Our NetworkSocket::native_handle_type is type SOCKET on // win32, which means that we need to explicitly construct // a native handle type to pass to the constructor. auto native_handle = NetworkSocket::native_handle_type(ofd); auto asyncPipeReader = AsyncPipeReader::newReader(eventBase_, NetworkSocket(native_handle)); auto asyncPipeReaderPtr = asyncPipeReader.get(); if (!asyncOperationFinishCallback_) { asyncOperationFinishCallback_.reset( new DefaultOpenSSLAsyncFinishCallback( std::move(asyncPipeReader), this, DestructorGuard(this))); } asyncPipeReaderPtr->setReadCB(asyncOperationFinishCallback_.get()); } #endif // The timeout (if set) keeps running here return true; } else { unsigned long lastError = *errErrorOut = ERR_get_error(); VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", " << "state=" << state_ << ", " << "sslState=" << sslState_ << ", " << "events=" << std::hex << eventFlags_ << "): " << "SSL error: " << error << ", " << "errno: " << errno << ", " << "ret: " << ret << ", " << "read: " << BIO_number_read(SSL_get_rbio(ssl_.get())) << ", " << "written: " << BIO_number_written(SSL_get_wbio(ssl_.get())) << ", " << "func: " << ERR_func_error_string(lastError) << ", " << "reason: " << ERR_reason_error_string(lastError); return false; } } void AsyncSSLSocket::checkForImmediateRead() noexcept { // openssl may have buffered data that it read from the socket already. // In this case we have to process it immediately, rather than waiting for // the socket to become readable again. if (ssl_ != nullptr && SSL_pending(ssl_.get()) > 0) { AsyncSocket::handleRead(); } else { AsyncSocket::checkForImmediateRead(); } } void AsyncSSLSocket::restartSSLAccept() { VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; DestructorGuard dg(this); assert( sslState_ == STATE_ASYNC_PENDING || sslState_ == STATE_ERROR || sslState_ == STATE_CLOSED); if (sslState_ == STATE_CLOSED) { // I sure hope whoever closed this socket didn't delete it already, // but this is not strictly speaking an error return; } if (sslState_ == STATE_ERROR) { // go straight to fail if timeout expired during lookup static const Indestructible<AsyncSocketException> ex( AsyncSocketException::TIMED_OUT, "SSL accept timed out"); failHandshake(__func__, *ex); return; } sslState_ = STATE_ACCEPTING; this->handleAccept(); } void AsyncSSLSocket::handleAccept() noexcept { VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; assert(server_); assert(state_ == StateEnum::ESTABLISHED && sslState_ == STATE_ACCEPTING); if (!ssl_) { /* lazily create the SSL structure */ try { ssl_.reset(ctx_->createSSL()); } catch (std::exception& e) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error calling SSLContext::createSSL()"); LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this << ", fd=" << fd_ << "): " << e.what(); return failHandshake(__func__, *ex); } if (!setupSSLBio()) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error creating write bio"); return failHandshake(__func__, *ex); } SSL_set_ex_data(ssl_.get(), getSSLExDataIndex(), this); applyVerificationOptions(ssl_); } if (server_ && parseClientHello_) { SSL_set_msg_callback( ssl_.get(), &AsyncSSLSocket::clientHelloParsingCallback); SSL_set_msg_callback_arg(ssl_.get(), this); } DCHECK(ctx_->sslAcceptRunner()); updateEventRegistration( EventHandler::NONE, EventHandler::READ | EventHandler::WRITE); DelayedDestruction::DestructorGuard dg(this); ctx_->sslAcceptRunner()->run( [this, dg]() { waitingOnAccept_ = true; return SSL_accept(ssl_.get()); }, [this, dg](int ret) { waitingOnAccept_ = false; handleReturnFromSSLAccept(ret); }); } void AsyncSSLSocket::handleReturnFromSSLAccept(int ret) { if (sslState_ != STATE_ACCEPTING) { return; } if (ret <= 0) { VLOG(3) << "SSL_accept returned: " << ret; int sslError; unsigned long errError; int errnoCopy = errno; if (willBlock(ret, &sslError, &errError)) { return; } else { sslState_ = STATE_ERROR; SSLException ex(sslError, errError, ret, errnoCopy); return failHandshake(__func__, ex); } } handshakeComplete_ = true; updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE); // Move into STATE_ESTABLISHED in the normal case that we are in // STATE_ACCEPTING. sslState_ = STATE_ESTABLISHED; VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_ << " successfully accepted; state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_; // Remember the EventBase we are attached to, before we start invoking any // callbacks (since the callbacks may call detachEventBase()). EventBase* originalEventBase = eventBase_; // Call the accept callback. invokeHandshakeCB(); // Note that the accept callback may have changed our state. // (set or unset the read callback, called write(), closed the socket, etc.) // The following code needs to handle these situations correctly. // // If the socket has been closed, readCallback_ and writeReqHead_ will // always be nullptr, so that will prevent us from trying to read or write. // // The main thing to check for is if eventBase_ is still originalEventBase. // If not, we have been detached from this event base, so we shouldn't // perform any more operations. if (eventBase_ != originalEventBase) { return; } AsyncSocket::handleInitialReadWrite(); } void AsyncSSLSocket::handleConnect() noexcept { VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; assert(!server_); if (state_ < StateEnum::ESTABLISHED) { return AsyncSocket::handleConnect(); } assert( (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) && sslState_ == STATE_CONNECTING); assert(ssl_); auto originalState = state_; int ret = SSL_connect(ssl_.get()); if (ret <= 0) { int sslError; unsigned long errError; int errnoCopy = errno; if (willBlock(ret, &sslError, &errError)) { // We fell back to connecting state due to TFO if (state_ == StateEnum::CONNECTING) { DCHECK_EQ(StateEnum::FAST_OPEN, originalState); if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } } return; } else { sslState_ = STATE_ERROR; SSLException ex(sslError, errError, ret, errnoCopy); return failHandshake(__func__, ex); } } handshakeComplete_ = true; updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE); // Move into STATE_ESTABLISHED in the normal case that we are in // STATE_CONNECTING. sslState_ = STATE_ESTABLISHED; VLOG(3) << "AsyncSSLSocket " << this << ": " << "fd " << fd_ << " successfully connected; " << "state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_; // Remember the EventBase we are attached to, before we start invoking any // callbacks (since the callbacks may call detachEventBase()). EventBase* originalEventBase = eventBase_; // Call the handshake callback. invokeHandshakeCB(); // Note that the connect callback may have changed our state. // (set or unset the read callback, called write(), closed the socket, etc.) // The following code needs to handle these situations correctly. // // If the socket has been closed, readCallback_ and writeReqHead_ will // always be nullptr, so that will prevent us from trying to read or write. // // The main thing to check for is if eventBase_ is still originalEventBase. // If not, we have been detached from this event base, so we shouldn't // perform any more operations. if (eventBase_ != originalEventBase) { return; } AsyncSocket::handleInitialReadWrite(); } void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) { connectionTimeout_.cancelTimeout(); AsyncSocket::invokeConnectErr(ex); if (sslState_ == SSLStateEnum::STATE_CONNECTING) { if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } // If we fell back to connecting state during TFO and the connection // failed, it would be an SSL failure as well. invokeHandshakeErr(ex); } } void AsyncSSLSocket::invokeConnectSuccess() { connectionTimeout_.cancelTimeout(); if (sslState_ == SSLStateEnum::STATE_CONNECTING) { assert(tfoAttempted_); // If we failed TFO, we'd fall back to trying to connect the socket, // to setup things like timeouts. startSSLConnect(); } // still invoke the base class since it re-sets the connect time. AsyncSocket::invokeConnectSuccess(); } void AsyncSSLSocket::scheduleConnectTimeout() { if (sslState_ == SSLStateEnum::STATE_CONNECTING) { // We fell back from TFO, and need to set the timeouts. // We will not have a connect callback in this case, thus if the timer // expires we would have no-one to notify. // Thus we should reset even the connect timers to point to the handshake // timeouts. assert(connectCallback_ == nullptr); // We use a different connect timeout here than the handshake timeout, so // that we can disambiguate the 2 timers. if (connectTimeout_.count() > 0) { if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) { throw AsyncSocketException( AsyncSocketException::INTERNAL_ERROR, withAddr("failed to schedule AsyncSSLSocket connect timeout")); } } return; } AsyncSocket::scheduleConnectTimeout(); } void AsyncSSLSocket::handleRead() noexcept { VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; if (state_ < StateEnum::ESTABLISHED) { return AsyncSocket::handleRead(); } if (sslState_ == STATE_ACCEPTING) { assert(server_); handleAccept(); return; } else if (sslState_ == STATE_CONNECTING) { assert(!server_); handleConnect(); return; } // Normal read AsyncSocket::handleRead(); } AsyncSocket::ReadResult AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) { VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf << ", buflen=" << *buflen; if (sslState_ == STATE_UNENCRYPTED) { return AsyncSocket::performRead(buf, buflen, offset); } int numToRead = 0; if (*buflen > std::numeric_limits<int>::max()) { numToRead = std::numeric_limits<int>::max(); VLOG(4) << "Clamping SSL_read to " << numToRead; } else { numToRead = int(*buflen); } int bytes = SSL_read(ssl_.get(), *buf, numToRead); if (server_ && renegotiateAttempted_) { LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslstate=" << sslState_ << ", events=" << eventFlags_ << "): client intitiated SSL renegotiation not permitted"; return ReadResult( READ_ERROR, std::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION)); } if (bytes <= 0) { int error = SSL_get_error(ssl_.get(), bytes); if (error == SSL_ERROR_WANT_READ) { // The caller will register for read event if not already. if (errno == EWOULDBLOCK || errno == EAGAIN) { return ReadResult(READ_BLOCKING); } else { return ReadResult(READ_ERROR); } } else if (error == SSL_ERROR_WANT_WRITE) { // TODO: Even though we are attempting to read data, SSL_read() may // need to write data if renegotiation is being performed. We currently // don't support this and just fail the read. LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): unsupported SSL renegotiation during read"; return ReadResult( READ_ERROR, std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION)); } else { if (zero_return(error, bytes, errno)) { return ReadResult(bytes); } auto errError = ERR_get_error(); VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", " << "state=" << state_ << ", " << "sslState=" << sslState_ << ", " << "events=" << std::hex << eventFlags_ << "): " << "bytes: " << bytes << ", " << "error: " << error << ", " << "errno: " << errno << ", " << "func: " << ERR_func_error_string(errError) << ", " << "reason: " << ERR_reason_error_string(errError); return ReadResult( READ_ERROR, std::make_unique<SSLException>(error, errError, bytes, errno)); } } else { appBytesReceived_ += bytes; return ReadResult(bytes); } } void AsyncSSLSocket::handleWrite() noexcept { VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; if (state_ < StateEnum::ESTABLISHED) { return AsyncSocket::handleWrite(); } if (sslState_ == STATE_ACCEPTING) { assert(server_); handleAccept(); return; } if (sslState_ == STATE_CONNECTING) { assert(!server_); handleConnect(); return; } // Normal write AsyncSocket::handleWrite(); } AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) { if (error == SSL_ERROR_WANT_READ) { // Even though we are attempting to write data, SSL_write() may // need to read data if renegotiation is being performed. We currently // don't support this and just fail the write. LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "unsupported SSL renegotiation during write"; return WriteResult( WRITE_ERROR, std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION)); } else { if (zero_return(error, rc, errno)) { return WriteResult(0); } auto errError = ERR_get_error(); VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "SSL error: " << error << ", errno: " << errno << ", func: " << ERR_func_error_string(errError) << ", reason: " << ERR_reason_error_string(errError); return WriteResult( WRITE_ERROR, std::make_unique<SSLException>(error, errError, rc, errno)); } } AsyncSocket::WriteResult AsyncSSLSocket::performWrite( const iovec* vec, uint32_t count, WriteFlags flags, uint32_t* countWritten, uint32_t* partialWritten) { if (sslState_ == STATE_UNENCRYPTED) { return AsyncSocket::performWrite( vec, count, flags, countWritten, partialWritten); } if (sslState_ != STATE_ESTABLISHED) { LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "TODO: AsyncSSLSocket currently does not support calling " << "write() before the handshake has fully completed"; return WriteResult( WRITE_ERROR, std::make_unique<SSLException>(SSLError::EARLY_WRITE)); } // Declare a buffer used to hold small write requests. It could point to a // memory block either on stack or on heap. If it is on heap, we release it // manually when scope exits char* combinedBuf{nullptr}; SCOPE_EXIT { // Note, always keep this check consistent with what we do below if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) { delete[] combinedBuf; } }; *countWritten = 0; *partialWritten = 0; ssize_t totalWritten = 0; size_t bytesStolenFromNextBuffer = 0; for (uint32_t i = 0; i < count; i++) { const iovec* v = vec + i; size_t offset = bytesStolenFromNextBuffer; bytesStolenFromNextBuffer = 0; size_t len = v->iov_len - offset; const void* buf; if (len == 0) { (*countWritten)++; continue; } buf = ((const char*)v->iov_base) + offset; ssize_t bytes; uint32_t buffersStolen = 0; auto sslWriteBuf = buf; if ((len < minWriteSize_) && ((i + 1) < count)) { // Combine this buffer with part or all of the next buffers in // order to avoid really small-grained calls to SSL_write(). // Each call to SSL_write() produces a separate record in // the egress SSL stream, and we've found that some low-end // mobile clients can't handle receiving an HTTP response // header and the first part of the response body in two // separate SSL records (even if those two records are in // the same TCP packet). if (combinedBuf == nullptr) { if (minWriteSize_ > MAX_STACK_BUF_SIZE) { // Allocate the buffer on heap combinedBuf = new char[minWriteSize_]; } else { // Allocate the buffer on stack combinedBuf = (char*)alloca(minWriteSize_); } } assert(combinedBuf != nullptr); sslWriteBuf = combinedBuf; memcpy(combinedBuf, buf, len); do { // INVARIANT: i + buffersStolen == complete chunks serialized uint32_t nextIndex = i + buffersStolen + 1; bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len, minWriteSize_ - len); if (bytesStolenFromNextBuffer > 0) { assert(vec[nextIndex].iov_base != nullptr); ::memcpy( combinedBuf + len, vec[nextIndex].iov_base, bytesStolenFromNextBuffer); } len += bytesStolenFromNextBuffer; if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) { // couldn't steal the whole buffer break; } else { bytesStolenFromNextBuffer = 0; buffersStolen++; } } while ((i + buffersStolen + 1) < count && (len < minWriteSize_)); } // Advance any empty buffers immediately after. if (bytesStolenFromNextBuffer == 0) { while ((i + buffersStolen + 1) < count && vec[i + buffersStolen + 1].iov_len == 0) { buffersStolen++; } } // cork the current write if the original flags included CORK or if there // are remaining iovec to write corkCurrentWrite_ = isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count); // track the EoR if: // (1) there are write flags that require EoR tracking (EOR / TIMESTAMP_TX) // (2) if the buffer includes the EOR byte appEorByteWriteFlags_ = flags & kEorRelevantWriteFlags; bool trackEor = appEorByteWriteFlags_ != folly::WriteFlags::NONE && (i + buffersStolen + 1 == count); bytes = eorAwareSSLWrite(ssl_, sslWriteBuf, int(len), trackEor); if (bytes <= 0) { int error = SSL_get_error(ssl_.get(), int(bytes)); if (error == SSL_ERROR_WANT_WRITE) { // The caller will register for write event if not already. *partialWritten = uint32_t(offset); return WriteResult(totalWritten); } auto writeResult = interpretSSLError(int(bytes), error); if (writeResult.writeReturn < 0) { return writeResult; } // else fall through to below to correctly record totalWritten } totalWritten += bytes; if (bytes == (ssize_t)len) { // The full iovec is written. (*countWritten) += 1 + buffersStolen; i += buffersStolen; // continue } else { bytes += offset; // adjust bytes to account for all of v while (bytes >= (ssize_t)v->iov_len) { // We combined this buf with part or all of the next one, and // we managed to write all of this buf but not all of the bytes // from the next one that we'd hoped to write. bytes -= v->iov_len; (*countWritten)++; v = &(vec[++i]); } *partialWritten = uint32_t(bytes); return WriteResult(totalWritten); } } return WriteResult(totalWritten); } int AsyncSSLSocket::eorAwareSSLWrite( const ssl::SSLUniquePtr& ssl, const void* buf, int n, bool eor) { if (eor && isEorTrackingEnabled()) { if (appEorByteNo_) { // cannot track for more than one app byte EOR CHECK(appEorByteNo_ == appBytesWritten_ + n); } else { appEorByteNo_ = appBytesWritten_ + n; } // 1. It is fine to keep updating minEorRawByteNo_. // 2. It is _min_ in the sense that SSL record will add some overhead. minEorRawByteNo_ = getRawBytesWritten() + n; } n = sslWriteImpl(ssl.get(), buf, n); if (n > 0) { appBytesWritten_ += n; if (appEorByteNo_) { if (getRawBytesWritten() >= minEorRawByteNo_) { minEorRawByteNo_ = 0; } if (appBytesWritten_ == appEorByteNo_) { appEorByteNo_ = 0; appEorByteWriteFlags_ = {}; } else { CHECK(appBytesWritten_ < appEorByteNo_); } } } return n; } void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) { AsyncSSLSocket* sslSocket = AsyncSSLSocket::getFromSSL(ssl); if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) { sslSocket->renegotiateAttempted_ = true; } if (sslSocket->handshakeComplete_ && (where & SSL_CB_WRITE_ALERT)) { const char* desc = SSL_alert_desc_string(ret); if (desc && strcmp(desc, "NR") == 0) { sslSocket->renegotiateAttempted_ = true; } } if (where & SSL_CB_READ_ALERT) { const char* type = SSL_alert_type_string(ret); if (type) { const char* desc = SSL_alert_desc_string(ret); sslSocket->alertsReceived_.emplace_back( *type, StringPiece(desc, std::strlen(desc))); } } } int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) { struct msghdr msg; struct iovec iov; AsyncSSLSocket* tsslSock; iov.iov_base = const_cast<char*>(in); iov.iov_len = size_t(inl); memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; auto appData = OpenSSLUtils::getBioAppData(b); CHECK(appData); tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData); CHECK(tsslSock); WriteFlags flags = WriteFlags::NONE; if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ && tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) { flags |= tsslSock->appEorByteWriteFlags_; } if (tsslSock->corkCurrentWrite_) { flags |= WriteFlags::CORK; } int msg_flags = tsslSock->getSendMsgParamsCB()->getFlags( flags, false /*zeroCopyEnabled*/); msg.msg_controllen = tsslSock->getSendMsgParamsCB()->getAncillaryDataSize(flags); CHECK_GE( AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize, msg.msg_controllen); if (msg.msg_controllen != 0) { msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen)); tsslSock->getSendMsgParamsCB()->getAncillaryData(flags, msg.msg_control); } auto result = tsslSock->sendSocketMessage(OpenSSLUtils::getBioFd(b), &msg, msg_flags); BIO_clear_retry_flags(b); if (!result.exception && result.writeReturn <= 0) { if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) { BIO_set_retry_write(b); } } return int(result.writeReturn); } int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) { if (!out) { return 0; } BIO_clear_retry_flags(b); auto appData = OpenSSLUtils::getBioAppData(b); CHECK(appData); auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData); if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) { VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock << ", reading pre-received data"; Cursor cursor(sslSock->preReceivedData_.get()); auto len = cursor.pullAtMost(out, outl); IOBufQueue queue; queue.append(std::move(sslSock->preReceivedData_)); queue.trimStart(len); sslSock->preReceivedData_ = queue.move(); return static_cast<int>(len); } else { auto result = int(netops::recv(OpenSSLUtils::getBioFd(b), out, outl, 0)); if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) { BIO_set_retry_read(b); } return result; } } int AsyncSSLSocket::sslVerifyCallback( int preverifyOk, X509_STORE_CTX* x509Ctx) { SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data( x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl); VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", " << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk; return (self->handshakeCallback_) ? self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) : preverifyOk; } void AsyncSSLSocket::enableClientHelloParsing() { parseClientHello_ = true; clientHelloInfo_ = std::make_unique<ssl::ClientHelloInfo>(); } void AsyncSSLSocket::resetClientHelloParsing(SSL* ssl) { SSL_set_msg_callback(ssl, nullptr); SSL_set_msg_callback_arg(ssl, nullptr); clientHelloInfo_->clientHelloBuf_.clear(); } void AsyncSSLSocket::clientHelloParsingCallback( int written, int /* version */, int contentType, const void* buf, size_t len, SSL* ssl, void* arg) { AsyncSSLSocket* sock = static_cast<AsyncSSLSocket*>(arg); if (written != 0) { sock->resetClientHelloParsing(ssl); return; } if (contentType != SSL3_RT_HANDSHAKE) { return; } if (len == 0) { return; } auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_; clientHelloBuf.append(IOBuf::wrapBuffer(buf, len)); try { Cursor cursor(clientHelloBuf.front()); if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) { sock->resetClientHelloParsing(ssl); return; } if (cursor.totalLength() < 3) { clientHelloBuf.trimEnd(len); clientHelloBuf.append(IOBuf::copyBuffer(buf, len)); return; } uint32_t messageLength = cursor.read<uint8_t>(); messageLength <<= 8; messageLength |= cursor.read<uint8_t>(); messageLength <<= 8; messageLength |= cursor.read<uint8_t>(); if (cursor.totalLength() < messageLength) { clientHelloBuf.trimEnd(len); clientHelloBuf.append(IOBuf::copyBuffer(buf, len)); return; } sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>(); sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>(); cursor.skip(4); // gmt_unix_time cursor.skip(28); // random_bytes cursor.skip(cursor.read<uint8_t>()); // session_id uint16_t cipherSuitesLength = cursor.readBE<uint16_t>(); for (int i = 0; i < cipherSuitesLength; i += 2) { sock->clientHelloInfo_->clientHelloCipherSuites_.push_back( cursor.readBE<uint16_t>()); } uint8_t compressionMethodsLength = cursor.read<uint8_t>(); for (int i = 0; i < compressionMethodsLength; ++i) { sock->clientHelloInfo_->clientHelloCompressionMethods_.push_back( cursor.readBE<uint8_t>()); } if (cursor.totalLength() > 0) { uint16_t extensionsLength = cursor.readBE<uint16_t>(); while (extensionsLength) { ssl::TLSExtension extensionType = static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>()); sock->clientHelloInfo_->clientHelloExtensions_.push_back(extensionType); extensionsLength -= 2; uint16_t extensionDataLength = cursor.readBE<uint16_t>(); extensionsLength -= 2; extensionsLength -= extensionDataLength; if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) { cursor.skip(2); extensionDataLength -= 2; while (extensionDataLength) { ssl::HashAlgorithm hashAlg = static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>()); ssl::SignatureAlgorithm sigAlg = static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>()); extensionDataLength -= 2; sock->clientHelloInfo_->clientHelloSigAlgs_.emplace_back( hashAlg, sigAlg); } } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) { cursor.skip(1); extensionDataLength -= 1; while (extensionDataLength) { sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back( cursor.readBE<uint16_t>()); extensionDataLength -= 2; } } else if (extensionType == ssl::TLSExtension::SERVER_NAME) { cursor.skip(2); extensionDataLength -= 2; while (extensionDataLength) { static_assert( std::is_same< typename std::underlying_type<ssl::NameType>::type, uint8_t>::value, "unexpected underlying type"); ssl::NameType typ = static_cast<ssl::NameType>(cursor.readBE<uint8_t>()); uint16_t nameLength = cursor.readBE<uint16_t>(); if (typ == NameType::HOST_NAME && sock->clientHelloInfo_->clientHelloSNIHostname_.empty() && cursor.canAdvance(nameLength)) { sock->clientHelloInfo_->clientHelloSNIHostname_ = cursor.readFixedString(nameLength); } else { // Must attempt to skip |nameLength| in order to keep cursor // in sync. If the remaining buffer length is smaller than // nameLength, this will throw. cursor.skip(nameLength); } extensionDataLength -= sizeof(typ) + sizeof(nameLength) + nameLength; } } else { cursor.skip(extensionDataLength); } } } } catch (std::out_of_range&) { // we'll use what we found and cleanup below. VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): " << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock; } sock->resetClientHelloParsing(ssl); } void AsyncSSLSocket::getSSLClientCiphers( std::string& clientCiphers, bool convertToString) const { std::string ciphers; if (parseClientHello_ == false || clientHelloInfo_->clientHelloCipherSuites_.empty()) { clientCiphers = ""; return; } bool first = true; for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_) { if (first) { first = false; } else { ciphers += ":"; } bool nameFound = convertToString; if (convertToString) { const auto& name = OpenSSLUtils::getCipherName(originalCipherCode); if (name.empty()) { nameFound = false; } else { ciphers += name; } } if (!nameFound) { folly::hexlify( std::array<uint8_t, 2>{ {static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL), static_cast<uint8_t>(originalCipherCode & 0x00ffL)}}, ciphers, /* append to ciphers = */ true); } } clientCiphers = std::move(ciphers); } std::string AsyncSSLSocket::getSSLClientComprMethods() const { if (!parseClientHello_) { return ""; } return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_); } std::string AsyncSSLSocket::getSSLClientExts() const { if (!parseClientHello_) { return ""; } return folly::join(":", clientHelloInfo_->clientHelloExtensions_); } std::string AsyncSSLSocket::getSSLClientSigAlgs() const { if (!parseClientHello_) { return ""; } std::string sigAlgs; sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4); for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) { if (i) { sigAlgs.push_back(':'); } sigAlgs.append( folly::to<std::string>(clientHelloInfo_->clientHelloSigAlgs_[i].first)); sigAlgs.push_back(','); sigAlgs.append(folly::to<std::string>( clientHelloInfo_->clientHelloSigAlgs_[i].second)); } return sigAlgs; } std::string AsyncSSLSocket::getSSLClientSupportedVersions() const { if (!parseClientHello_) { return ""; } return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_); } std::string AsyncSSLSocket::getSSLAlertsReceived() const { std::string ret; for (const auto& alert : alertsReceived_) { if (!ret.empty()) { ret.append(","); } ret.append(folly::to<std::string>(alert.first, ": ", alert.second)); } return ret; } void AsyncSSLSocket::setSSLCertVerificationAlert(std::string alert) { sslVerificationAlert_ = std::move(alert); } std::string AsyncSSLSocket::getSSLCertVerificationAlert() const { return sslVerificationAlert_; } void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const { char ciphersBuffer[1024]; ciphersBuffer[0] = '\0'; SSL_get_shared_ciphers(ssl_.get(), ciphersBuffer, sizeof(ciphersBuffer) - 1); sharedCiphers = ciphersBuffer; } void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const { serverCiphers = SSL_get_cipher_list(ssl_.get(), 0); int i = 1; const char* cipher; while ((cipher = SSL_get_cipher_list(ssl_.get(), i)) != nullptr) { serverCiphers.append(":"); serverCiphers.append(cipher); i++; } } } // namespace folly
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_849_0
crossvul-cpp_data_bad_4256_2
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "hermes/BCGen/HBC/BytecodeGenerator.h" #include "hermes/BCGen/HBC/ConsecutiveStringStorage.h" #include "hermes/FrontEndDefs/Builtins.h" #include "hermes/Support/OSCompat.h" #include "hermes/Support/UTF8.h" #include "llvh/ADT/SmallString.h" #include "llvh/Support/Format.h" #include "llvh/Support/raw_ostream.h" #include <locale> #include <unordered_map> using hermes::oscompat::to_string; namespace hermes { namespace hbc { unsigned BytecodeFunctionGenerator::getStringID(LiteralString *value) const { return BMGen_.getStringID(value->getValue().str()); } unsigned BytecodeFunctionGenerator::getIdentifierID( LiteralString *value) const { return BMGen_.getIdentifierID(value->getValue().str()); } uint32_t BytecodeFunctionGenerator::addRegExp(CompiledRegExp regexp) { return BMGen_.addRegExp(std::move(regexp)); } uint32_t BytecodeFunctionGenerator::addFilename(StringRef filename) { return BMGen_.addFilename(filename); } void BytecodeFunctionGenerator::addExceptionHandler( HBCExceptionHandlerInfo info) { exceptionHandlers_.push_back(info); } void BytecodeFunctionGenerator::addDebugSourceLocation( const DebugSourceLocation &info) { // If an address is repeated, it means no actual bytecode was emitted for the // previous source location. if (!debugLocations_.empty() && debugLocations_.back().address == info.address) { debugLocations_.back() = info; } else { debugLocations_.push_back(info); } } void BytecodeFunctionGenerator::setJumpTable( std::vector<uint32_t> &&jumpTable) { assert(!jumpTable.empty() && "invoked with no jump table"); jumpTable_ = std::move(jumpTable); } uint32_t BytecodeModuleGenerator::addArrayBuffer(ArrayRef<Literal *> elements) { return literalGenerator_.serializeBuffer(elements, arrayBuffer_, false); } std::pair<uint32_t, uint32_t> BytecodeModuleGenerator::addObjectBuffer( ArrayRef<Literal *> keys, ArrayRef<Literal *> vals) { return std::pair<uint32_t, uint32_t>{ literalGenerator_.serializeBuffer(keys, objKeyBuffer_, true), literalGenerator_.serializeBuffer(vals, objValBuffer_, false)}; } std::unique_ptr<BytecodeFunction> BytecodeFunctionGenerator::generateBytecodeFunction( Function::DefinitionKind definitionKind, ValueKind valueKind, bool strictMode, uint32_t paramCount, uint32_t environmentSize, uint32_t nameID) { return std::unique_ptr<BytecodeFunction>(new BytecodeFunction( std::move(opcodes_), definitionKind, valueKind, strictMode, FunctionHeader( bytecodeSize_, paramCount, frameSize_, environmentSize, nameID, highestReadCacheIndex_, highestWriteCacheIndex_), std::move(exceptionHandlers_), std::move(jumpTable_))); } unsigned BytecodeFunctionGenerator::getFunctionID(Function *F) { return BMGen_.addFunction(F); } void BytecodeFunctionGenerator::shrinkJump(offset_t loc) { // We are shrinking a long jump into a short jump. // The size of operand reduces from 4 bytes to 1 byte, a delta of 3. const static int ShrinkOffset = 3; std::rotate( opcodes_.begin() + loc, opcodes_.begin() + loc + ShrinkOffset, opcodes_.end()); opcodes_.resize(opcodes_.size() - ShrinkOffset); // Change this instruction from long jump to short jump. longToShortJump(loc - 1); } void BytecodeFunctionGenerator::updateJumpTarget( offset_t loc, int newVal, int bytes) { // The jump target is encoded in little-endian. Update it correctly // regardless of host byte order. for (; bytes; --bytes, ++loc) { opcodes_[loc] = (opcode_atom_t)(newVal); newVal >>= 8; } } void BytecodeFunctionGenerator::updateJumpTableOffset( offset_t loc, uint32_t jumpTableOffset, uint32_t instLoc) { assert(opcodes_.size() > instLoc && "invalid switchimm offset"); // The offset is not aligned, but will be aligned when read in the // interpreter. updateJumpTarget( loc, opcodes_.size() + jumpTableOffset * sizeof(uint32_t) - instLoc, sizeof(uint32_t)); } unsigned BytecodeModuleGenerator::addFunction(Function *F) { lazyFunctions_ |= F->isLazy(); return functionIDMap_.allocate(F); } void BytecodeModuleGenerator::setFunctionGenerator( Function *F, unique_ptr<BytecodeFunctionGenerator> BFG) { assert( functionGenerators_.find(F) == functionGenerators_.end() && "Adding same function twice."); functionGenerators_[F] = std::move(BFG); } unsigned BytecodeModuleGenerator::getStringID(StringRef str) const { return stringTable_.getStringID(str); } unsigned BytecodeModuleGenerator::getIdentifierID(StringRef str) const { return stringTable_.getIdentifierID(str); } void BytecodeModuleGenerator::initializeStringTable( StringLiteralTable stringTable) { assert(stringTable_.empty() && "String table must be empty"); stringTable_ = std::move(stringTable); } uint32_t BytecodeModuleGenerator::addRegExp(CompiledRegExp regexp) { return regExpTable_.addRegExp(std::move(regexp)); } uint32_t BytecodeModuleGenerator::addFilename(StringRef filename) { return filenameTable_.addFilename(filename); } void BytecodeModuleGenerator::addCJSModule( uint32_t functionID, uint32_t nameID) { assert( cjsModulesStatic_.empty() && "Statically resolved modules must be in cjsModulesStatic_"); cjsModules_.push_back({nameID, functionID}); } void BytecodeModuleGenerator::addCJSModuleStatic( uint32_t moduleID, uint32_t functionID) { assert(cjsModules_.empty() && "Unresolved modules must be in cjsModules_"); assert( moduleID - cjsModuleOffset_ == cjsModulesStatic_.size() && "Module ID out of order in cjsModulesStatic_"); (void)moduleID; cjsModulesStatic_.push_back(functionID); } std::unique_ptr<BytecodeModule> BytecodeModuleGenerator::generate() { assert( valid_ && "BytecodeModuleGenerator::generate() cannot be called more than once"); valid_ = false; assert( functionIDMap_.getElements().size() == functionGenerators_.size() && "Missing functions."); auto kinds = stringTable_.getStringKinds(); auto hashes = stringTable_.getIdentifierHashes(); BytecodeOptions bytecodeOptions; bytecodeOptions.staticBuiltins = options_.staticBuiltinsEnabled; bytecodeOptions.cjsModulesStaticallyResolved = !cjsModulesStatic_.empty(); std::unique_ptr<BytecodeModule> BM{new BytecodeModule( functionGenerators_.size(), std::move(kinds), std::move(hashes), stringTable_.acquireStringTable(), stringTable_.acquireStringStorage(), regExpTable_.getEntryList(), regExpTable_.getBytecodeBuffer(), entryPointIndex_, std::move(arrayBuffer_), std::move(objKeyBuffer_), std::move(objValBuffer_), cjsModuleOffset_, std::move(cjsModules_), std::move(cjsModulesStatic_), bytecodeOptions)}; DebugInfoGenerator debugInfoGen{std::move(filenameTable_)}; const uint32_t strippedFunctionNameId = options_.stripFunctionNames ? getStringID(kStrippedFunctionName) : 0; auto functions = functionIDMap_.getElements(); std::shared_ptr<Context> contextIfNeeded; for (unsigned i = 0, e = functions.size(); i < e; ++i) { auto *F = functions[i]; auto &BFG = *functionGenerators_[F]; uint32_t functionNameId = options_.stripFunctionNames ? strippedFunctionNameId : getStringID(functions[i]->getOriginalOrInferredName().str()); std::unique_ptr<BytecodeFunction> func = BFG.generateBytecodeFunction( F->getDefinitionKind(), F->getKind(), F->isStrictMode(), F->getExpectedParamCountIncludingThis(), F->getFunctionScope()->getVariables().size(), functionNameId); #ifndef HERMESVM_LEAN if (F->getParent() ->shareContext() ->allowFunctionToStringWithRuntimeSource() || F->isLazy()) { auto context = F->getParent()->shareContext(); assert( (!contextIfNeeded || contextIfNeeded.get() == context.get()) && "Different instances of Context seen"); contextIfNeeded = context; BM->setFunctionSourceRange(i, F->getSourceRange()); } #endif if (F->isLazy()) { #ifdef HERMESVM_LEAN llvm_unreachable("Lazy support compiled out"); #else auto lazyData = llvh::make_unique<LazyCompilationData>(); lazyData->parentScope = F->getLazyScope(); lazyData->nodeKind = F->getLazySource().nodeKind; lazyData->bufferId = F->getLazySource().bufferId; lazyData->originalName = F->getOriginalOrInferredName(); lazyData->closureAlias = F->getLazyClosureAlias() ? F->getLazyClosureAlias()->getName() : Identifier(); lazyData->strictMode = F->isStrictMode(); func->setLazyCompilationData(std::move(lazyData)); #endif } if (BFG.hasDebugInfo()) { uint32_t sourceLocOffset = debugInfoGen.appendSourceLocations( BFG.getSourceLocation(), i, BFG.getDebugLocations()); uint32_t lexicalDataOffset = debugInfoGen.appendLexicalData( BFG.getLexicalParentID(), BFG.getDebugVariableNames()); func->setDebugOffsets({sourceLocOffset, lexicalDataOffset}); } BM->setFunction(i, std::move(func)); } BM->setContext(contextIfNeeded); BM->setDebugInfo(debugInfoGen.serializeWithMove()); return BM; } } // namespace hbc } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_4256_2
crossvul-cpp_data_good_2813_0
/***************************************************************** | | AP4 - avcC Atoms | | Copyright 2002-2008 Axiomatic Systems, LLC | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4AvccAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Utils.h" #include "Ap4Types.h" /*---------------------------------------------------------------------- | dynamic cast support +---------------------------------------------------------------------*/ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_AvccAtom) /*---------------------------------------------------------------------- | AP4_AvccAtom::GetProfileName +---------------------------------------------------------------------*/ const char* AP4_AvccAtom::GetProfileName(AP4_UI08 profile) { switch (profile) { case AP4_AVC_PROFILE_BASELINE: return "Baseline"; case AP4_AVC_PROFILE_MAIN: return "Main"; case AP4_AVC_PROFILE_EXTENDED: return "Extended"; case AP4_AVC_PROFILE_HIGH: return "High"; case AP4_AVC_PROFILE_HIGH_10: return "High 10"; case AP4_AVC_PROFILE_HIGH_422: return "High 4:2:2"; case AP4_AVC_PROFILE_HIGH_444: return "High 4:4:4"; } return NULL; } /*---------------------------------------------------------------------- | AP4_AvccAtom::Create +---------------------------------------------------------------------*/ AP4_AvccAtom* AP4_AvccAtom::Create(AP4_Size size, AP4_ByteStream& stream) { // read the raw bytes in a buffer unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE; AP4_DataBuffer payload_data(payload_size); AP4_Result result = stream.Read(payload_data.UseData(), payload_size); if (AP4_FAILED(result)) return NULL; // check the version const AP4_UI08* payload = payload_data.GetData(); if (payload[0] != 1) { return NULL; } // check the size if (payload_size < 6) return NULL; unsigned int num_seq_params = payload[5]&31; unsigned int cursor = 6; for (unsigned int i=0; i<num_seq_params; i++) { if (cursor+2 > payload_size) return NULL; cursor += 2+AP4_BytesToInt16BE(&payload[cursor]); if (cursor > payload_size) return NULL; } unsigned int num_pic_params = payload[cursor++]; if (cursor > payload_size) return NULL; for (unsigned int i=0; i<num_pic_params; i++) { if (cursor+2 > payload_size) return NULL; cursor += 2+AP4_BytesToInt16BE(&payload[cursor]); if (cursor > payload_size) return NULL; } return new AP4_AvccAtom(size, payload); } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom() : AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE), m_ConfigurationVersion(1), m_Profile(0), m_Level(0), m_ProfileCompatibility(0), m_NaluLengthSize(0) { UpdateRawBytes(); m_Size32 += m_RawBytes.GetDataSize(); } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom(const AP4_AvccAtom& other) : AP4_Atom(AP4_ATOM_TYPE_AVCC, other.m_Size32), m_ConfigurationVersion(other.m_ConfigurationVersion), m_Profile(other.m_Profile), m_Level(other.m_Level), m_ProfileCompatibility(other.m_ProfileCompatibility), m_NaluLengthSize(other.m_NaluLengthSize), m_RawBytes(other.m_RawBytes) { // deep copy of the parameters unsigned int i = 0; for (i=0; i<other.m_SequenceParameters.ItemCount(); i++) { m_SequenceParameters.Append(other.m_SequenceParameters[i]); } for (i=0; i<other.m_PictureParameters.ItemCount(); i++) { m_PictureParameters.Append(other.m_PictureParameters[i]); } } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom(AP4_UI32 size, const AP4_UI08* payload) : AP4_Atom(AP4_ATOM_TYPE_AVCC, size) { // make a copy of our configuration bytes unsigned int payload_size = size-AP4_ATOM_HEADER_SIZE; m_RawBytes.SetData(payload, payload_size); // parse the payload m_ConfigurationVersion = payload[0]; m_Profile = payload[1]; m_ProfileCompatibility = payload[2]; m_Level = payload[3]; m_NaluLengthSize = 1+(payload[4]&3); AP4_UI08 num_seq_params = payload[5]&31; m_SequenceParameters.EnsureCapacity(num_seq_params); unsigned int cursor = 6; for (unsigned int i=0; i<num_seq_params; i++) { if (cursor+2 <= payload_size) { AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]); cursor += 2; if (cursor + param_length < payload_size) { m_SequenceParameters.Append(AP4_DataBuffer()); m_SequenceParameters[i].SetData(&payload[cursor], param_length); cursor += param_length; } } } AP4_UI08 num_pic_params = payload[cursor++]; m_PictureParameters.EnsureCapacity(num_pic_params); for (unsigned int i=0; i<num_pic_params; i++) { if (cursor+2 <= payload_size) { AP4_UI16 param_length = AP4_BytesToInt16BE(&payload[cursor]); cursor += 2; if (cursor + param_length < payload_size) { m_PictureParameters.Append(AP4_DataBuffer()); m_PictureParameters[i].SetData(&payload[cursor], param_length); cursor += param_length; } } } } /*---------------------------------------------------------------------- | AP4_AvccAtom::AP4_AvccAtom +---------------------------------------------------------------------*/ AP4_AvccAtom::AP4_AvccAtom(AP4_UI08 profile, AP4_UI08 level, AP4_UI08 profile_compatibility, AP4_UI08 length_size, const AP4_Array<AP4_DataBuffer>& sequence_parameters, const AP4_Array<AP4_DataBuffer>& picture_parameters) : AP4_Atom(AP4_ATOM_TYPE_AVCC, AP4_ATOM_HEADER_SIZE), m_ConfigurationVersion(1), m_Profile(profile), m_Level(level), m_ProfileCompatibility(profile_compatibility), m_NaluLengthSize(length_size) { // deep copy of the parameters unsigned int i = 0; for (i=0; i<sequence_parameters.ItemCount(); i++) { m_SequenceParameters.Append(sequence_parameters[i]); } for (i=0; i<picture_parameters.ItemCount(); i++) { m_PictureParameters.Append(picture_parameters[i]); } // compute the raw bytes UpdateRawBytes(); // update the size m_Size32 += m_RawBytes.GetDataSize(); } /*---------------------------------------------------------------------- | AP4_AvccAtom::UpdateRawBytes +---------------------------------------------------------------------*/ void AP4_AvccAtom::UpdateRawBytes() { // compute the payload size unsigned int payload_size = 6; for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { payload_size += 2+m_SequenceParameters[i].GetDataSize(); } ++payload_size; for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) { payload_size += 2+m_PictureParameters[i].GetDataSize(); } m_RawBytes.SetDataSize(payload_size); AP4_UI08* payload = m_RawBytes.UseData(); payload[0] = m_ConfigurationVersion; payload[1] = m_Profile; payload[2] = m_ProfileCompatibility; payload[3] = m_Level; payload[4] = 0xFC | (m_NaluLengthSize-1); payload[5] = 0xE0 | (AP4_UI08)m_SequenceParameters.ItemCount(); unsigned int cursor = 6; for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { AP4_UI16 param_length = (AP4_UI16)m_SequenceParameters[i].GetDataSize(); AP4_BytesFromUInt16BE(&payload[cursor], param_length); cursor += 2; AP4_CopyMemory(&payload[cursor], m_SequenceParameters[i].GetData(), param_length); cursor += param_length; } payload[cursor++] = (AP4_UI08)m_PictureParameters.ItemCount(); for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) { AP4_UI16 param_length = (AP4_UI16)m_PictureParameters[i].GetDataSize(); AP4_BytesFromUInt16BE(&payload[cursor], param_length); cursor += 2; AP4_CopyMemory(&payload[cursor], m_PictureParameters[i].GetData(), param_length); cursor += param_length; } } /*---------------------------------------------------------------------- | AP4_AvccAtom::WriteFields +---------------------------------------------------------------------*/ AP4_Result AP4_AvccAtom::WriteFields(AP4_ByteStream& stream) { return stream.Write(m_RawBytes.GetData(), m_RawBytes.GetDataSize()); } /*---------------------------------------------------------------------- | AP4_AvccAtom::InspectFields +---------------------------------------------------------------------*/ AP4_Result AP4_AvccAtom::InspectFields(AP4_AtomInspector& inspector) { inspector.AddField("Configuration Version", m_ConfigurationVersion); const char* profile_name = GetProfileName(m_Profile); if (profile_name) { inspector.AddField("Profile", profile_name); } else { inspector.AddField("Profile", m_Profile); } inspector.AddField("Profile Compatibility", m_ProfileCompatibility, AP4_AtomInspector::HINT_HEX); inspector.AddField("Level", m_Level); inspector.AddField("NALU Length Size", m_NaluLengthSize); for (unsigned int i=0; i<m_SequenceParameters.ItemCount(); i++) { inspector.AddField("Sequence Parameter", m_SequenceParameters[i].GetData(), m_SequenceParameters[i].GetDataSize()); } for (unsigned int i=0; i<m_PictureParameters.ItemCount(); i++) { inspector.AddField("Picture Parameter", m_PictureParameters[i].GetData(), m_PictureParameters[i].GetDataSize()); } return AP4_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_2813_0
crossvul-cpp_data_good_2804_2
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol (int row, int col) { static const char filter[16][16] = { { 2,1,1,3,2,3,2,0,3,2,3,0,1,2,1,0 }, { 0,3,0,2,0,1,3,1,0,1,1,2,0,3,3,2 }, { 2,3,3,2,3,1,1,3,3,1,2,1,2,0,0,3 }, { 0,1,0,1,0,2,0,2,2,0,3,0,1,3,2,1 }, { 3,1,1,2,0,1,0,2,1,3,1,3,0,1,3,0 }, { 2,0,0,3,3,2,3,1,2,0,2,0,3,2,2,1 }, { 2,3,3,1,2,1,2,1,2,1,1,2,3,0,0,1 }, { 1,0,0,2,3,0,0,3,0,3,0,3,2,1,2,3 }, { 2,3,3,1,1,2,1,0,3,2,3,0,2,3,1,3 }, { 1,0,2,0,3,0,3,2,0,1,1,2,0,1,0,2 }, { 0,1,1,3,3,2,2,1,1,3,3,0,2,1,3,2 }, { 2,3,2,0,0,1,3,0,2,0,1,2,3,0,1,0 }, { 1,3,1,2,3,2,3,2,0,2,0,1,1,0,3,0 }, { 0,2,0,3,1,0,0,1,1,3,3,2,3,2,2,1 }, { 2,1,3,2,3,1,2,1,0,3,0,2,0,2,0,2 }, { 0,3,1,0,0,2,0,3,2,1,3,1,1,3,1,3 } }; if (filters == 1) return filter[(row+top_margin)&15][(col+left_margin)&15]; if (filters == 9) return xtrans[(row+6) % 6][(col+6) % 6]; return FC(row,col); } static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return(p ? p-s : n); } /* add OS X version check here ?? */ #define strnlen(a,b) local_strnlen(a,b) #ifdef LIBRAW_LIBRARY_BUILD static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf,len,1); buf[len-1] = 0; return r; } #define stmread(buf,maxlen,fp) stread(buf,MIN(maxlen,sizeof(buf)),fp) #endif #ifndef __GLIBC__ char *my_memmem (char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp (c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr (char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf,sizeof(buf)-1) ushort CLASS sget2 (uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords,int maxlen) { line[maxlen-1] = 0; char *p = line; int nwords = 0; while(1) { while(isspace(*p)) p++; if(*p == '\0') return nwords; words[nwords++] = p; while(!isspace(*p) && *p != '\0') p++; if(*p == '\0') return nwords; *p++ = '\0'; if(nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f){ if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data){ if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = { 0xff,0xff }; fread (str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4 (uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = { 0xff,0xff,0xff,0xff }; fread (str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint (int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float (int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal (int type) { union { char c[8]; double d; } u,v; int i, rev; switch (type) { case 3: return (unsigned short) get2(); case 4: return (unsigned int) get4(); case 5: u.d = (unsigned int) get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short) get2(); case 9: return (signed int) get4(); case 10: u.d = (signed int) get4(); v.d = (signed int)get4(); return u.d / (v.d?v.d:1); case 11: return int_to_float (get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i=0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts (ushort *pixel, int count) { if (fread (pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab ((char*)pixel, (char*)pixel, count*2); } void CLASS cubic_spline (const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **) calloc (((2*len + 4)*sizeof **A + sizeof *A), 2*len); if (!A) return; A[0] = (float *) (A + 2*len); for (i = 1; i < 2*len; i++) A[i] = A[0] + 2*len*i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i*i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len-1; i > 0; i--) { b[i] = (y[i] - y[i-1]) / (x[i] - x[i-1]); d[i-1] = x[i] - x[i-1]; } for (i = 1; i < len-1; i++) { A[i][i] = 2 * (d[i-1] + d[i]); if (i > 1) { A[i][i-1] = d[i-1]; A[i-1][i] = d[i-1]; } A[i][len-1] = 6 * (b[i+1] - b[i]); } for(i = 1; i < len-2; i++) { float v = A[i+1][i] / A[i][i]; for(j = 1; j <= len-1; j++) A[i+1][j] -= v * A[i][j]; } for(i = len-2; i > 0; i--) { float acc = 0; for(j = i; j <= len-2; j++) acc += A[i][j]*c[j]; c[i] = (A[i][len-1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len-1; j++) { if (x[j] <= x_out && x_out <= x[j+1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j+1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j+1] * d[j])/6) * v + (c[j] * 0.5) * v*v + ((c[j+1] - c[j]) / (6 * d[j])) * v*v*v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free (A); } void CLASS canon_600_fixed_wb (int temp) { static const short mul[4][5] = { { 667, 358,397,565,452 }, { 731, 390,367,499,517 }, { 1119, 396,348,448,537 }, { 1399, 485,431,508,688 } }; int lo, hi, i; float frac=0; for (lo=4; --lo; ) if (*mul[lo] <= temp) break; for (hi=0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float) (temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i=1; i < 5; i++) pre_mul[i-1] = 1 / (frac * mul[hi][i] + (1-frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color (int ratio[2], int mar) { int clipped=0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar*4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = { 0,0 }; int test[8], total[2][8], ratio[2][2], stat[2]; memset (&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row=14; row < height-14; row+=4) for (col=10; col < width; col+=2) { for (i=0; i < 8; i++) test[(i & 4) + FC(row+(i >> 1),col+(i & 1))] = BAYER(row+(i >> 1),col+(i & 1)); for (i=0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i=0; i < 4; i++) if (abs(test[i] - test[i+4]) > 50) goto next; for (i=0; i < 2; i++) { for (j=0; j < 4; j+=2) ratio[i][j >> 1] = ((test[i*4+j+1]-test[i*4+j]) << 10) / test[i*4+j]; stat[i] = canon_600_color (ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i=0; i < 2; i++) if (stat[i]) for (j=0; j < 2; j++) test[i*4+j*2+1] = test[i*4+j*2] * (0x400 + ratio[i][j]) >> 10; for (i=0; i < 8; i++) total[st][i] += test[i]; count[st]++; next: ; } if (count[0] | count[1]) { st = count[0]*200 < count[1]; for (i=0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i+4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = { { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -1203,1715,-1136,1648, 1388,-876,267,245, -1641,2153,3921,-3409 }, { -615,1127,-1563,2075, 1437,-925,509,3, -756,1268,2519,-2007 }, { -190,702,-1886,2398, 2153,-1641,763,-251, -452,964,3040,-2528 }, { -190,702,-1878,2390, 1861,-1349,905,-393, -432,944,2617,-2105 }, { -807,1319,-1785,2297, 1388,-876,769,-257, -230,742,2067,-1555 } }; int t=0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t=1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t=3; else if (yc <= 2) t=4; } if (flash_used) t=5; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i*4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow=row=0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row*raw_width; for (dp=data; dp < data+1120; dp+=10, pix+=8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6 ); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6 ); } if ((row+=2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = { { 1141,1145 }, { 1128,1109 }, { 1178,1149 }, { 1128,1109 } }; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) { if ((val = BAYER(row,col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row,col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row=0; row < 100; row++) { fseek (ifp, row*3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff (int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf=0; static int vbits=0, reset=0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar) c; vbits += 8; } c = bitbuf << (32-vbits) >> (32-nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar) huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n,0) #define gethuff(h) getbithuff(*h,h+1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort * CLASS make_decoder_ref (const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max=16; max && !count[max]; max--); huff = (ushort *) calloc (1 + (1 << max), sizeof *huff); merror (huff, "make_decoder()"); huff[0] = max; for (h=len=1; len <= max; len++) for (i=0; i < count[len]; i++, ++*source) for (j=0; j < 1 << (max-len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort * CLASS make_decoder (const uchar *source) { return make_decoder_ref (&source); } void CLASS crw_init_tables (unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, { 0,2,2,3,1,1,1,1,2,0,0,0,0,0,0,0, 0x03,0x02,0x04,0x01,0x05,0x00,0x06,0x07,0x09,0x08,0x0a,0x0b,0xff }, { 0,0,6,3,1,1,2,0,0,0,0,0,0,0,0,0, 0x06,0x05,0x07,0x04,0x08,0x03,0x09,0x02,0x00,0x0a,0x01,0x0b,0xff }, }; static const uchar second_tree[3][180] = { { 0,2,2,2,1,4,2,1,2,5,1,1,0,0,0,139, 0x03,0x04,0x02,0x05,0x01,0x06,0x07,0x08, 0x12,0x13,0x11,0x14,0x09,0x15,0x22,0x00,0x21,0x16,0x0a,0xf0, 0x23,0x17,0x24,0x31,0x32,0x18,0x19,0x33,0x25,0x41,0x34,0x42, 0x35,0x51,0x36,0x37,0x38,0x29,0x79,0x26,0x1a,0x39,0x56,0x57, 0x28,0x27,0x52,0x55,0x58,0x43,0x76,0x59,0x77,0x54,0x61,0xf9, 0x71,0x78,0x75,0x96,0x97,0x49,0xb7,0x53,0xd7,0x74,0xb6,0x98, 0x47,0x48,0x95,0x69,0x99,0x91,0xfa,0xb8,0x68,0xb5,0xb9,0xd6, 0xf7,0xd8,0x67,0x46,0x45,0x94,0x89,0xf8,0x81,0xd5,0xf6,0xb4, 0x88,0xb1,0x2a,0x44,0x72,0xd9,0x87,0x66,0xd4,0xf5,0x3a,0xa7, 0x73,0xa9,0xa8,0x86,0x62,0xc7,0x65,0xc8,0xc9,0xa1,0xf4,0xd1, 0xe9,0x5a,0x92,0x85,0xa6,0xe7,0x93,0xe8,0xc1,0xc6,0x7a,0x64, 0xe1,0x4a,0x6a,0xe6,0xb3,0xf1,0xd3,0xa5,0x8a,0xb2,0x9a,0xba, 0x84,0xa4,0x63,0xe5,0xc5,0xf3,0xd2,0xc4,0x82,0xaa,0xda,0xe4, 0xf2,0xca,0x83,0xa3,0xa2,0xc3,0xea,0xc2,0xe2,0xe3,0xff,0xff }, { 0,2,2,1,4,1,4,1,3,3,1,0,0,0,0,140, 0x02,0x03,0x01,0x04,0x05,0x12,0x11,0x06, 0x13,0x07,0x08,0x14,0x22,0x09,0x21,0x00,0x23,0x15,0x31,0x32, 0x0a,0x16,0xf0,0x24,0x33,0x41,0x42,0x19,0x17,0x25,0x18,0x51, 0x34,0x43,0x52,0x29,0x35,0x61,0x39,0x71,0x62,0x36,0x53,0x26, 0x38,0x1a,0x37,0x81,0x27,0x91,0x79,0x55,0x45,0x28,0x72,0x59, 0xa1,0xb1,0x44,0x69,0x54,0x58,0xd1,0xfa,0x57,0xe1,0xf1,0xb9, 0x49,0x47,0x63,0x6a,0xf9,0x56,0x46,0xa8,0x2a,0x4a,0x78,0x99, 0x3a,0x75,0x74,0x86,0x65,0xc1,0x76,0xb6,0x96,0xd6,0x89,0x85, 0xc9,0xf5,0x95,0xb4,0xc7,0xf7,0x8a,0x97,0xb8,0x73,0xb7,0xd8, 0xd9,0x87,0xa7,0x7a,0x48,0x82,0x84,0xea,0xf4,0xa6,0xc5,0x5a, 0x94,0xa4,0xc6,0x92,0xc3,0x68,0xb5,0xc8,0xe4,0xe5,0xe6,0xe9, 0xa2,0xa3,0xe3,0xc2,0x66,0x67,0x93,0xaa,0xd4,0xd5,0xe7,0xf8, 0x88,0x9a,0xd7,0x77,0xc4,0x64,0xe2,0x98,0xa5,0xca,0xda,0xe8, 0xf3,0xf6,0xa9,0xb2,0xb3,0xf2,0xd2,0x83,0xba,0xd3,0xff,0xff }, { 0,0,6,2,1,3,3,2,5,1,2,2,8,10,0,117, 0x04,0x05,0x03,0x06,0x02,0x07,0x01,0x08, 0x09,0x12,0x13,0x14,0x11,0x15,0x0a,0x16,0x17,0xf0,0x00,0x22, 0x21,0x18,0x23,0x19,0x24,0x32,0x31,0x25,0x33,0x38,0x37,0x34, 0x35,0x36,0x39,0x79,0x57,0x58,0x59,0x28,0x56,0x78,0x27,0x41, 0x29,0x77,0x26,0x42,0x76,0x99,0x1a,0x55,0x98,0x97,0xf9,0x48, 0x54,0x96,0x89,0x47,0xb7,0x49,0xfa,0x75,0x68,0xb6,0x67,0x69, 0xb9,0xb8,0xd8,0x52,0xd7,0x88,0xb5,0x74,0x51,0x46,0xd9,0xf8, 0x3a,0xd6,0x87,0x45,0x7a,0x95,0xd5,0xf6,0x86,0xb4,0xa9,0x94, 0x53,0x2a,0xa8,0x43,0xf5,0xf7,0xd4,0x66,0xa7,0x5a,0x44,0x8a, 0xc9,0xe8,0xc8,0xe7,0x9a,0x6a,0x73,0x4a,0x61,0xc7,0xf4,0xc6, 0x65,0xe9,0x72,0xe6,0x71,0x91,0x93,0xa6,0xda,0x92,0x85,0x62, 0xf3,0xc5,0xb2,0xa4,0x84,0xba,0x64,0xa5,0xb3,0xd2,0x81,0xe5, 0xd3,0xaa,0xc4,0xca,0xf2,0xb1,0xe4,0xd1,0x83,0x63,0xea,0xc3, 0xe2,0x82,0xf1,0xa3,0xc2,0xa1,0xc1,0xe3,0xa2,0xe1,0xff,0xff } }; if (table > 2) table = 2; huff[0] = make_decoder ( first_tree[table]); huff[1] = make_decoder (second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret=1, i; fseek (ifp, 0, SEEK_SET); fread (test, 1, sizeof test, ifp); for (i=540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i+1]) return 1; ret=0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry=0, pnum=0, base[2]; crw_init_tables (tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek (ifp, 540 + lowbits*raw_height*raw_width/4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row+=8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; nblocks = MIN (8, raw_height-row) * raw_width >> 6; for (block=0; block < nblocks; block++) { memset (diffbuf, 0, sizeof diffbuf); for (i=0; i < 64; i++ ) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i=0; i < 64; i++ ) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek (ifp, 26 + row*raw_width/4, SEEK_SET); for (prow=pixel, i=0; i < raw_width*2; i++) { c = fgetc(ifp); for (r=0; r < 8; r+=2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free (huff[c]); throw; } #endif FORC(2) free (huff[c]); } int CLASS ljpeg_start (struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset (jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp),fgetc(ifp)) != 0xd8) return 0; do { if(feof(ifp)) return 0; if(cnt++ > 1024) return 0; // 1024 tags limit if (!fread (data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread (data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data+len && !((c = *dp++) & -20); ) jh->free[c] = jh->huff[c] = make_decoder_ref (&dp); break; case 0xffda: // start of scan jh->psv = data[1+data[0]*2]; jh->bits -= data[3+data[0]*2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c*2+1] << 8 | data[c*2+2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c+1]) jh->huff[c+1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2+c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1+c] = jh->huff[0]; } jh->row = (ushort *) calloc (jh->wide*jh->clrs, 4); merror (jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end (struct jhead *jh) { int c; FORC4 if (jh->free[c]) free (jh->free[c]); free (jh->row); } int CLASS ljpeg_diff (ushort *huff) { int len, diff; if(!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; return diff; } ushort * CLASS ljpeg_row (int jrow, struct jhead *jh) { int col, c, diff, pred, spred=0; ushort mark=0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits-1); if (jrow) { fseek (ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide*jh->clrs*((jrow+c) & 1); for (col=0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff (jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row=0, col=0; struct jhead jh; ushort *rp; if (!ljpeg_start (&jh, 0)) return; if(jh.wide<1 || jh.high<1 || jh.clrs<1 || jh.bits <1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if(jh.clrs == 4 && jwide >= raw_width*2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height-1-jrow/2 : jrow/2; for (jcol=0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow*jwide + jcol; i = jidx / (cr2_slice[1]*raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1]*raw_height); row = jidx / cr2_slice[1+j]; col = jidx % cr2_slice[1+j] + i*cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--,raw_width); if(row>raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp (failure, 3); #endif if ((unsigned) row < raw_height) RAW(row,col) = val; if (++col >= raw_width) col = (row++,0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw; } #endif ljpeg_end (&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp=0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow=0, jcol=0, pix[3], c; int v[3]={0,0,0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start (&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if(load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol=slice=0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width-1) ecol = raw_width & -2; for (row=0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short (*)[4]) image + row*width; for (col=scol; col < ecol; col+=2, jcol+=jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *) ljpeg_row (jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC (jh.clrs-2) { ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col + (c >> 1)*width + (c & 1)][1] = ip[col + (c >> 1)*width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 8192; ip[col][2] = rp[jcol+jh.clrs-1] - 8192; } else #endif { FORC (jh.clrs-2) ip[col + (c >> 1)*width + (c & 1)][0] = rp[jcol+c]; ip[col][1] = rp[jcol+jh.clrs-2] - 16384; ip[col][2] = rp[jcol+jh.clrs-1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end (&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp=model2; *cp && !isdigit(*cp); cp++); sscanf (cp, "%d.%d.%d", v, v+1, v+2); ver = (v[0]*1000 + v[1])*1000 + v[2]; hue = (jh.sraw+1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short (*)[4]) image; rp = ip[0]; for (row=0; row < height; row++, ip+=width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col=0; col < width; col+=2) for (c=1; c < 3; c++) if (row == height-1) { ip[col][c] = ip[col-width][c]; } else { ip[col][c] = (ip[col-width][c] + ip[col+width][c] + 1) >> 1; } } for (col=1; col < width; col+=2) for (c=1; c < 3; c++) if (col == width-1) ip[col][c] = ip[col-1][c]; else ip[col][c] = (ip[col-1][c] + ip[col+1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) ) #endif for ( ; rp < ip[0]; rp+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + (( 50*rp[1] + 22929*rp[2]) >> 14); pix[1] = rp[0] + ((-5640*rp[1] - 11751*rp[2]) >> 14); pix[2] = rp[0] + ((29040*rp[1] - 101*rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778*rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } height = saved_h; width = saved_w; #endif ljpeg_end (&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel (unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row,col) = curve[**rp]; *rp += tiff_samples; } else { if (row < height && col < width) FORC(tiff_samples) image[row*width+col][c] = curve[(*rp)[c]]; *rp += tiff_samples; } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct (struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = { 0 }; static const uchar zigzag[80] = { 0, 1, 8,16, 9, 2, 3,10,17,24,32,25,18,11, 4, 5,12,19,26,33, 40,48,41,34,27,20,13, 6, 7,14,21,28,35,42,49,56,57,50,43,36, 29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54, 47,55,62,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63,63 }; if (!cs[0]) FORC(106) cs[c] = cos((c & 31)*M_PI/16)/2; memset (work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff (jh->huff[0]) * jh->quant[0]; for (i=1; i < 64; i++ ) { len = gethuff (jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len-1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j*2+1)*c]; for (i=0; i < 8; i++) for (j=0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i*2+1)*c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c]+0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow=0, tcol=0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); if (!ljpeg_start (&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN (is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow=0; jrow+7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol=0; jcol+7 < jh.wide; jcol += 8) { ljpeg_idct (&jh); rp = jh.idct; row = trow + jcol/tile_width + jrow*2; col = tcol + jcol%tile_width; for (i=0; i < 16; i+=2) for (j=0; j < 8; j++) adobe_copy_pixel (row+i, col+j, &rp); } } break; case 0xc3: for (row=col=jrow=0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row (jrow, &jh); for (jcol=0; jcol < jwide; jcol++) { adobe_copy_pixel (trow+row, tcol+col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end (&jh); throw ; } #endif fseek (ifp, save+4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end (&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *) calloc (raw_width, tiff_samples*sizeof *pixel); merror (pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts (pixel, raw_width * tiff_samples); else { getbits(-1); for (col=0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp=pixel, col=0; col < raw_width; col++) adobe_copy_pixel (row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (pixel); throw ; } #endif free (pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0,0},{0,0}}, hpred[2]; fseek (ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek (ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i=bit[0][c]; i <= ((bit[0][c]+(4096 >> bit[1][c])-1) & 4095); ) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek (ifp, data_offset, SEEK_SET); getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width*3*tiff_bps/8; if(tiff_bps <= 8) gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,255); else gamma_curve(1.0/imgdata.params.coolscan_nef_gamma,0.,1,65535); fseek (ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char*)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for(int row = 0; row < raw_height; row++) { int red = fread (buf, 1, bufsize, ifp); unsigned short (*ip)[4] = (unsigned short (*)[4]) image + row*width; if(tiff_bps <= 8) for(int col=0; col<width;col++) { ip[col][0] = curve[buf[col*3]]; ip[col][1] = curve[buf[col*3+1]]; ip[col][2] = curve[buf[col*3+2]]; ip[col][3]=0; } else for(int col=0; col<width;col++) { ip[col][0] = curve[ubuf[col*3]]; ip[col][1] = curve[ubuf[col*3+1]]; ip[col][2] = curve[ubuf[col*3+2]]; ip[col][3]=0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy */ 5,4,3,6,2,7,1,0,8,9,11,10,12 }, { 0,1,5,1,1,1,1,1,1,2,0,0,0,0,0,0, /* 12-bit lossy after split */ 0x39,0x5a,0x38,0x27,0x16,5,4,3,2,1,0,11,12,12 }, { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, /* 12-bit lossless */ 5,4,6,3,7,2,8,1,9,0,10,11,12 }, { 0,1,4,3,1,1,1,1,1,2,0,0,0,0,0,0, /* 14-bit lossy */ 5,6,4,7,8,3,9,2,1,0,10,11,12,13,14 }, { 0,1,5,1,1,1,1,1,1,1,2,0,0,0,0,0, /* 14-bit lossy after split */ 8,0x5c,0x4b,0x3a,0x29,7,6,5,4,3,2,1,0,13,14 }, { 0,1,4,2,2,3,1,2,0,0,0,0,0,0,0,0, /* 14-bit lossless */ 7,6,8,5,9,4,10,3,11,12,2,0,1,13,14 } }; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step=0, tree=0, split=0, row, col, len, shl, diff; fseek (ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek (ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts (vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize-1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i=0; i < csize; i++) curve[i*step] = get2(); for (i=0; i < max; i++) curve[i] = ( curve[i-i%step]*(step-i%step) + curve[i-i%step+step]*(i%step) ) / step; fseek (ifp, meta_offset+562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts (curve, max=csize); while (curve[max-2] == curve[max-1]) max--; huff = make_decoder (nikon_tree[tree]); fseek (ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min=row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free (huff); huff = make_decoder (nikon_tree[tree+1]); max += (min = 16) << 1; } for (col=0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len-shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row,col) = curve[LIM((short)hpred[col & 1],0,0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free (huff); throw; } #endif free (huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf=0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c]>0.001f?cam_mul[c]:1.f; } for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64) fgetc(ifp) << c*8; FORC(4) yuv[c] = (bitbuf >> c*12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705*yuv[3]; rgb[1] = yuv[b] - 0.337633*yuv[2] - 0.698001*yuv[3]; rgb[2] = yuv[b] + 1.732446*yuv[2]; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = { 0x00, 0x55, 0xaa, 0xff }; memset (histo, 0, sizeof histo); fseek (ifp, -2000, SEEK_END); for (i=0; i < 2000; i++) histo[fgetc(ifp)]++; for (i=0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek (ifp, 0, SEEK_SET); for (i=0; i < 1024; i++) { fread (t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { { 0x00, "Pentax", "Optio 33WR" }, { 0x03, "Nikon", "E3200" }, { 0x32, "Nikon", "E3700" }, { 0x33, "Olympus", "C740UZ" } }; fseek (ifp, 3072, SEEK_SET); fread (dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i=0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy (make, table[i].t_make ); strcpy (model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek (ifp, -sizeof tail, SEEK_END); fread (tail, 1, sizeof tail, ifp); for (nz=i=0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) malloc (thumb_length); merror (thumb, "ppm_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread (thumb, 1, thumb_length, ifp); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width*thumb_height*3; thumb = (char *) calloc (thumb_length, 2); merror (thumb, "ppm16_thumb()"); read_shorts ((ushort *) thumb, thumb_length); for (i=0; i < thumb_length; i++) thumb[i] = ((ushort *) thumb)[i] >> 8; fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite (thumb, 1, thumb_length, ofp); free (thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = { "012","102" }; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width*thumb_height; thumb = (char *) calloc (colors, thumb_length); merror (thumb, "layer_thumb()"); fprintf (ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread (thumb, thumb_length, colors, ifp); for (i=0; i < thumb_length; i++) FORCC putc (thumb[i+thumb_length*(map[thumb_misc >> 8][c]-'0')], ofp); free (thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *) calloc (thumb_length, 2); merror (thumb, "rollei_thumb()"); fprintf (ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts (thumb, thumb_length); for (i=0; i < thumb_length; i++) { putc (thumb[i] << 3, ofp); putc (thumb[i] >> 5 << 2, ofp); putc (thumb[i] >> 11 << 3, ofp); } free (thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten=0, isix, i, buffer=0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread (pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i=0; i < 10; i+=2) { todo[i] = iten++; todo[i+1] = pixel[i] << 8 | pixel[i+1]; buffer = pixel[i] >> 2 | buffer << 6; } for ( ; i < 16; i+=2) { todo[i] = isix++; todo[i+1] = buffer >> (14-i)*5; } for (i=0; i < 16; i+=2) raw_image[todo[i]] = (todo[i+1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw (unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row,col) : 0; } void CLASS phase_one_flat_field (int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts (head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *) calloc (nc*wide, sizeof *mrow); merror (mrow, "phase_one_flat_field()"); for (y=0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) { num = is_float ? getreal(11) : get2()/32768.0; if (y==0) mrow[c*wide+x] = num; else mrow[(c+1)*wide+x] = (num - mrow[c*wide+x]) / head[5]; } if (y==0) continue; rend = head[1] + y*head[5]; for (row = rend-head[5]; row < raw_height && row < rend && row < head[1]+head[3]-head[5]; row++) { for (x=1; x < wide; x++) { for (c=0; c < nc; c+=2) { mult[c] = mrow[c*wide+x-1]; mult[c+1] = (mrow[c*wide+x] - mult[c]) / head[4]; } cend = head[0] + x*head[4]; for (col = cend-head[4]; col < raw_width && col < cend && col < head[0]+head[2]-head[4]; col++) { c = nc > 2 ? FC(row-top_margin,col-left_margin) : 0; if (!(c & 1)) { c = RAW(row,col) * mult[c]; RAW(row,col) = LIM(c,0,65535); } for (c=0; c < nc; c+=2) mult[c] += mult[c+1]; } } for (x=0; x < wide; x++) for (c=0; c < nc; c+=2) mrow[c*wide+x] += mrow[(c+1)*wide+x]; } } free (mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff=INT_MAX, off_412=0; /* static */ const signed char dir[12][2] = { {-1,-1}, {-1,1}, {1,-1}, {1,1}, {-2,0}, {0,-2}, {0,2}, {2,0}, {-2,-2}, {-2,2}, {2,-2}, {2,2} }; float poly[8], num, cfrac, frac, mult[2], *yval[2]={NULL,NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Phase One correction...\n")); #endif fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i=0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i=0; i < 0x10000; i++) { num = (poly[5]*i + poly[3])*i + poly[1]; curve[i] = LIM(num,0,65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i=0; i < 4; i++) poly[i] = getreal(11); for (i=0; i < 0x10000; i++) { for (num=0, j=4; j--; ) num = num * i + poly[j]; curve[i] = LIM(num+i,0,65535); } apply: /* apply to whole image */ for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1)*ph1.split_col; col < raw_width; col++) RAW(row,col) = curve[RAW(row,col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row=0; row < raw_height; row++) if (FC(row-top_margin,col-left_margin) == 1) { for (sum=i=0; i < 4; i++) sum += val[i] = raw (row+dir[i][0], col+dir[i][1]); for (max=i=0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row,col) = (sum - val[max])/3.0 + 0.5; } else { for (sum=0, i=8; i < 12; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = 0.5 + sum * 0.0732233 + (raw(row,col-2) + raw(row,col+2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row-top_margin,col-left_margin) != 1) * 4; for (sum=0, i=j; i < j+8; i++) sum += raw (row+dir[i][0], col+dir[i][1]); RAW(row,col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field (1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field (0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field (0, 4); } else if (tag == 0x412) { fseek (ifp, 36, SEEK_CUR); diff = abs (get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1+i] = lc[qr][qc][i]; cf[1+i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = { { 1, 1 }, { 1, 1 } }; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row,col); RAW(row,col) = LIM(i,0,65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1+i] = ref[i]; cf[1+i] = ((unsigned) ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row,col) = curve[RAW(row,col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek (ifp, save, SEEK_SET); } if (off_412) { fseek (ifp, off_412, SEEK_SET); for (i=0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *) calloc (head[1]*head[3] + head[2]*head[4], 6); merror (yval[0], "phase_one_correct()"); yval[1] = (float *) (yval[0] + head[1]*head[3]); xval[0] = (ushort *) (yval[1] + head[2]*head[4]); xval[1] = (ushort *) (xval[0] + head[1]*head[3]); get2(); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) yval[i][j] = getreal(11); for (i=0; i < 2; i++) for (j=0; j < head[i+1]*head[i+3]; j++) xval[i][j] = get2(); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { cfrac = (float) col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row,col) * 0.5; for (i=cip; i < cip+2; i++) { for (k=j=0; j < head[1]; j++) if (num < xval[0][k = head[1]*i+j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k-1]); mult[i-cip] = yval[0][k-1] * frac + yval[0][k] * (1-frac); } i = ((mult[0] * (1-cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row,col) = LIM(i,0,65535); } } free (yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek (ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555:0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw()"); if (ph1.black_col) { fseek (ifp, ph1.black_col, SEEK_SET); read_shorts ((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height*2); } if (ph1.black_row) { fseek (ifp, ph1.black_row, SEEK_SET); read_shorts ((ushort *) imgdata.rawdata.ph1_rblack[0], raw_width*2); } } #endif fseek (ifp, data_offset, SEEK_SET); read_shorts (raw_image, raw_width*raw_height); if (ph1.format) for (i=0; i < raw_width*raw_height; i+=2) { a = raw_image[i+0] ^ akey; b = raw_image[i+1] ^ bkey; raw_image[i+0] = (a & t_mask) | (b & ~t_mask); raw_image[i+1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff (int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf=0; static int vbits=0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64-vbits) >> (64-nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar) huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n,0) #define ph1_huff(h) ph1_bithuff(*h,h+1) void CLASS phase_one_load_raw_c() { static const int length[] = { 8,7,6,9,11,10,5,12,14,13 }; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short (*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if(ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *) calloc (raw_width*3 + raw_height*4, 2); merror (pixel, "phase_one_load_raw_c()"); offset = (int *) (pixel + raw_width); fseek (ifp, strip_offset, SEEK_SET); for (row=0; row < raw_height; row++) offset[row] = get4(); c_black = (short (*)[2]) (offset + raw_height); fseek (ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts ((ushort *) c_black[0], raw_height*2); r_black = c_black + raw_height; fseek (ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts ((ushort *) r_black[0], raw_width*2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row ) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack,(ushort*)c_black[0],raw_height*2*sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width*2,sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack,"phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack,(ushort*)r_black[0],raw_width*2*sizeof(ushort)); } #endif for (i=0; i < 256; i++) curve[i] = i*i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col=0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i=0; i < 2; i++) { for (j=0; j < 5 && !ph1_bits(1); j++); if (j--) len[i] = length[j*2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col=0; col < raw_width; col++) { int shift = ph1.format == 8? 0: 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row,col) = i; } #else if(ph1.format == 8) memmove(&RAW(row,0),&pixel[0],raw_width*2); else for (col=0; col < raw_width; col++) RAW(row,col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start (&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *) calloc (raw_width, 3*sizeof **back); merror (back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c*raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c+3) & 3] = back[c]; for (col=0; col < raw_width; col+=2) { for (s=0; s < tiff_samples*2; s+=2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s+c] = ph1_bits(len[c]); if ((diff[s+c] & (1 << (len[c]-1))) == 0) diff[s+c] -= (1 << len[c]) - 1; if (diff[s+c] == 65535) diff[s+c] = -32768; } } for (s=col; s < col+2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s-2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s]/2 - back[0][s-2]/2; break; } f = (row & 1)*3 ^ ((col+s) & 1); FORC (tiff_samples) { pred += diff[(s & 1)*tiff_samples+c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row,s) = upix; if (image) { urow = row-top_margin + (c & 1); ucol = col-left_margin - ((c >> 1) & 1); ip = &image[urow*width+ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (back[4]); ljpeg_end (&jh); throw; } #endif free (back[4]); ljpeg_end (&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel=0; unsigned tile=0, r, c, row, col; if (!filters) { pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r=0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek (ifp, data_offset + 4*tile++, SEEK_SET); fseek (ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters) pixel = raw_image + r*raw_width; read_shorts (pixel, raw_width); if (!filters && (row = r - top_margin) < height) for (col=0; col < width; col++) image[row*width+col][c] = pixel[col+left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if(!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free (pixel); } } void CLASS unpacked_load_raw() { int row, col, bits=0; while (1 << ++bits < maximum); read_shorts (raw_image, raw_width*raw_height); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits=0; while (1 << ++bits < maximum); for (row=raw_height-1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts (&raw_image[row*raw_width], raw_width); for (col=0; col < raw_width; col++) if ((RAW(row,col) >>= load_flags) >> bits && (unsigned) (row-top_margin) < height && (unsigned) (col-left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM (shot_select, 1, 4) - 1; fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *) calloc (raw_width, sizeof *pixel); merror (pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot=0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, data_offset + shot*4, SEEK_SET); fseek (ifp, get4(), SEEK_SET); for (row=0; row < raw_height; row++) { read_shorts (pixel, raw_width); if ((r = row-top_margin - (shot >> 1 & 1)) >= height) continue; for (col=0; col < raw_width; col++) { if ((c = col-left_margin - (shot & 1)) >= width) continue; image[r*width+c][(row & 1)*3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free (pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width*3*sizeof(unsigned short)); merror(buf,"imacon_full_load_raw"); #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf,width*3); unsigned short (*rowp)[4] = &image[row*width]; for (col=0; col < width; col++) { rowp[col][0]=buf[col*3]; rowp[col][1]=buf[col*3+1]; rowp[col][2]=buf[col*3+2]; rowp[col][3]=0; } #else for (col=0; col < width; col++) read_shorts (image[row*width+col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits=0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf=0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height+1) >> 1; for (irow=0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits=0, tiff_compress) fseek (ifp, data_offset - (-half*bwide & -2048), SEEK_SET); else { fseek (ifp, 0, SEEK_END); fseek (ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col=0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } val = bitbuf << (64-tiff_bps-vbits) >> (64-tiff_bps); RAW(row,col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height+top_margin && col < width+left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom () { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek (ifp, 0xb0 - 0x20, SEEK_CUR); fread (&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right)*5)+3)>>2) + 0x1f)&(~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *) malloc (raw_stride*2); merror (data, "broadcom_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data+raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[]={0,0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *) malloc (dwide*2); merror (data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (data+dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide+(c ^ rev)]; for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...){ free (data); throw; } #endif free (data); maximum = 0x3ff; if (strncmp(make,"OmniVision",10)) return; row = raw_height/2; FORC(width-1) { sum[ c & 1] += SQR(RAW(row,c)-RAW(row+1,c+1)); sum[~c & 1] += SQR(RAW(row+1,c)-RAW(row,c+1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5*raw_width >> 5) << 3; data = (uchar *) malloc (bwide); merror (data, "android_tight_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=5, col+=4) FORC4 RAW(row,col+c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free (data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf=0; bwide = (raw_width+5)/6 << 3; data = (uchar *) malloc (bwide); merror (data, "android_loose_load_raw()"); for (row=0; row < raw_height; row++) { if (fread (data, 1, bwide, ifp) < bwide) derror(); for (dp=data, col=0; col < raw_width; dp+=8, col+=6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c^7]; FORC(6) RAW(row,col+c) = (bitbuf >> c*10) & 0x3ff; } } free (data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int*)malloc(sizeof(int)*(raw_width/3+1)); merror(words,"canon_rmf_load_raw"); #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words,sizeof(int),raw_width/3,ifp); for (col=0; col < raw_width-2; col+=3) { bits = words[col/3]; FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #else for (col=0; col < raw_width-2; col+=3) { bits = get4(); FORC3 { orow = row; if ((ocol = col+c-4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow,ocol) = curve[bits >> (10*c+2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits (int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits=0; if (!vbits) { fread (buf+load_flags, 1, 0x4000-load_flags, ifp); fread (buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte+1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh=0, pred[2], nonz[2]; pana_bits(0); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row,col) = pred[col & 1]) > 4098 && col < width) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n=0] = 0xc0c; for (i=12; i--; ) FORC(2048 >> i) huff[++n] = (i+1) << 8 | i; fseek (ifp, 7, SEEK_CUR); getbits(-1); for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset (acarry, 0, sizeof acarry); for (col=0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits=2+i; (ushort) carry[0] >> (nbits+i); nbits++); low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12,huff)) == 12) high = getbits(16-nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff*3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2]+1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row,col-2); else if (col < 2) pred = RAW(row-2,col); else { w = RAW(row,col-2); n = RAW(row-2,col); nw = RAW(row-2,col-2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w-nw) > 32 || ABS(n-nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w-nw) > ABS(n-nw) ? w : n; } if ((RAW(row,col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow=0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box-12)*2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col=0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row,col) = (col+1) & 2 ? pixel[col/2-1] + pixel[col/2+1] : pixel[col/2] << 1; RAW(row,1) = pixel[1] << 1; RAW(row,1533) = pixel[765] << 1; } else for (col=row & 1; col < 1534; col+=2) RAW(row,col) = pixel[col/2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = { -89,-60,-44,-32,-22,-15,-8,-2,2,8,15,22,32,44,60,89 }; static const short rstep[6][4] = { { -3,-1,1,3 }, { -5,-1,1,5 }, { -8,-2,2,8 }, { -13,-3,3,13 }, { -19,-4,4,19 }, { -28,-6,6,28 } }; static const short t_curve[256] = { 0,1,2,3,4,5,6,7,8,9,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27, 28,29,30,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,53, 54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,74,75,76,77,78, 79,80,81,82,83,84,86,88,90,92,94,97,99,101,103,105,107,110,112,114,116, 118,120,123,125,127,129,131,134,136,138,140,142,144,147,149,151,153,155, 158,160,162,164,166,168,171,173,175,177,179,181,184,186,188,190,192,195, 197,199,201,203,205,208,210,212,214,216,218,221,223,226,230,235,239,244, 248,252,257,261,265,270,274,278,283,287,291,296,300,305,309,313,318,322, 326,331,335,339,344,348,352,357,361,365,370,374,379,383,387,392,396,400, 405,409,413,418,422,426,431,435,440,444,448,453,457,461,466,470,474,479, 483,487,492,496,500,508,519,531,542,553,564,575,587,598,609,620,631,643, 654,665,676,687,698,710,721,732,743,754,766,777,788,799,810,822,833,844, 855,866,878,889,900,911,922,933,945,956,967,978,989,1001,1012,1023 }; int rb, row, col, sharp, val=0; getbits(-1); memset (pixel, 0x80, sizeof pixel); for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=2+(row & 1); col < width+2; col+=2) { val = ((pixel[row-1][col-1] + 2*pixel[row-1][col+1] + pixel[row][col-2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val,0,255); if (col < 4) pixel[row][col-2] = pixel[row+1][~row & 1] = val; if (row == 2) pixel[row-1][col+1] = pixel[row-1][col+3] = val; } pixel[row][col] = val; } for (rb=0; rb < 2; rb++) for (row=2+rb; row < height+2; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row-2][col] - pixel[row][col-2]) + ABS(pixel[row-2][col] - pixel[row-2][col-2]) + ABS(pixel[row][col-2] - pixel[row-2][col-2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row-2][col] + pixel[row][col-2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val,0,255); if (row < 4) pixel[row-2][col+2] = val; if (col < 4) pixel[row+2][col-2] = val; } } for (row=2; row < height+2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=3-(row & 1); col < width+2; col+=2) { val = ((pixel[row][col-1] + (pixel[row][col] << 2) + pixel[row][col+1]) >> 1) - 0x100; pixel[row][col] = LIM(val,0,255); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = t_curve[pixel[row+2][col+2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char) getbithuff(8,huff[tree])) #define FORYX for (y=1; y < 3; y++) for (x=col+1; x >= col; x--) #define PREDICTOR (c ? (buf[c][y-1][x] + buf[c][y][x+1]) / 2 \ : (buf[c][y-1][x+1] + 2*buf[c][y-1][x] + buf[c][y][x+1]) / 4) #ifdef __GNUC__ # if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) # pragma GCC optimize("no-aggressive-loop-optimizations") # endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1,1, 2,3, 3,4, 4,2, 5,7, 6,5, 7,6, 7,8, 1,0, 2,1, 3,3, 4,4, 5,2, 6,7, 7,6, 8,5, 8,8, 2,1, 2,3, 3,0, 3,2, 3,4, 4,6, 5,5, 6,7, 6,8, 2,0, 2,1, 2,3, 3,2, 4,4, 5,6, 6,7, 7,5, 7,8, 2,1, 2,4, 3,0, 3,2, 3,3, 4,7, 5,5, 6,6, 6,8, 2,3, 3,1, 3,2, 3,4, 3,5, 3,6, 4,7, 5,0, 5,8, 2,3, 2,6, 3,0, 3,1, 4,4, 4,5, 4,7, 5,2, 5,8, 2,4, 2,7, 3,3, 3,6, 4,1, 4,2, 4,5, 5,0, 5,8, 2,6, 3,1, 3,3, 3,5, 3,7, 3,8, 4,0, 5,2, 5,4, 2,0, 2,1, 3,2, 3,3, 4,4, 4,5, 5,6, 5,7, 4,8, 1,0, 2,2, 2,-2, 1,-3, 1,3, 2,-17, 2,-5, 2,5, 2,17, 2,-7, 2,2, 2,9, 2,18, 2,-18, 2,-9, 2,-2, 2,7, 2,-28, 2,28, 3,-49, 3,-9, 3,9, 4,49, 5,-79, 5,79, 2,-1, 2,13, 2,26, 3,39, 4,-16, 5,55, 6,-37, 6,76, 2,-26, 2,-13, 2,1, 3,-39, 4,16, 5,-55, 6,-76, 6,37 }; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = { 16,16,16 }, mul[3], buf[3][3][386]; static const ushort pt[] = { 0,0, 1280,1344, 2320,3616, 3328,8000, 4095,16383, 65535,16383 }; for (i=2; i < 12; i+=2) for (c=pt[i-2]; c <= pt[i]; c++) curve[c] = (float) (c-pt[i-2]) / (pt[i]-pt[i-2]) * (pt[i+1]-pt[i-1]) + pt[i-1] + 0.5; for (s=i=0; i < sizeof src; i+=2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar) src[i+1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8-s) << 8 | c >> s << s | 1 << (s-1); getbits(-1); for (i=0; i < sizeof(buf)/sizeof(short); i++) ((short *)buf)[i] = 2048; for (row=0; row < height; row+=4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000/last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10:12; x = ~((~0u) << (s-1)); val <<= 12-s; for (i=0; i < sizeof(buf[0])/sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r=0; r <= !c; r++) { buf[c][1][width/2] = buf[c][2][width/2] = mul[c] << 7; for (tree=1, col=width/2; col > 0; ) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar) radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree+10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep=0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y=0; y < 2; y++) for (x=0; x < width/2; x++) { val = (buf[c][y+1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row+y*2+c-1,x*2+2-c) = val; else RAW(row+r*2+y,x*2+y) = val; } memcpy (buf[c][0]+!c, buf[c][2], sizeof buf[c][0]-2*!c); } } for (y=row; y < row+4; y++) for (x=0; x < width; x++) if ((x+y) & 1) { r = x ? x-1 : x+1; s = x+1 < width ? x+1 : x-1; val = (RAW(y,x)-2048)*2 + (RAW(y,r)+RAW(y,s))/2; if (val < 0) val = 0; RAW(y,x) = val; } } for (i=0; i < height*width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer (j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread (jpeg_buffer, 1, 4096, ifp); swab (jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; int row, col; cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); jpeg_stdio_src (&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { fprintf (stderr,_("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress (&cinfo); longjmp (failure, 3); } buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, width*3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit (j_common_ptr cinfo) { jpegErrorManager* myerr = (jpegErrorManager*) cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if(data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf,"kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char*) malloc(width*3); jpeg_create_decompress (&cinfo); merror(pixel_buf,"kodak_jpeg_load_raw"); fread(jpg_buf,data_size,1,ifp); swab ((char*)jpg_buf, (char*)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if(rc!=1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress (&cinfo); if ((cinfo.output_width != width ) || (cinfo.output_height*2 != height ) || (cinfo.output_components != 3 )) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines (&cinfo, buf, 1); unsigned char (*pixel)[3] = (unsigned char (*)[3]) buf[0]; for (col=0; col < width; col+=2) { RAW(row+0,col+0) = pixel[col+0][1] << 1; RAW(row+1,col+1) = pixel[col+1][1] << 1; RAW(row+0,col+1) = pixel[col][0] + pixel[col+1][0]; RAW(row+1,col+0) = pixel[col][2] + pixel[col+1][2]; } } } catch (...) { jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress (&cinfo); jpeg_destroy_decompress (&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve (double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE (*pixel)[3]; unsigned sorder=order, ntags, opcode, deg, i, j, c; unsigned save=data_offset-4, trow=0, tcol=0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek (ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek (ifp, get4(), SEEK_CUR); continue; } fseek (ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek (ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i=0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i=0; i < 256; i++) { for (tot=j=0; j <= deg; j++) tot += coeff[j] * pow(i/255.0, (int)j); cur[c][i] = tot*0xffff; } } order = sorder; } else { gamma_curve (1/2.4, 12.92, 1, 255); FORC3 memcpy (cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error (&jerr); jpeg_create_decompress (&cinfo); while (trow < raw_height) { fseek (ifp, save+=4, SEEK_SET); if (tile_length < INT_MAX) fseek (ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src (&cinfo, ifp); #endif jpeg_read_header (&cinfo, TRUE); jpeg_start_decompress (&cinfo); buf = (*cinfo.mem->alloc_sarray) ((j_common_ptr) &cinfo, JPOOL_IMAGE, cinfo.output_width*3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines (&cinfo, buf, 1); pixel = (JSAMPLE (*)[3]) buf[0]; for (col=0; col < cinfo.output_width && tcol+col < width; col++) { FORC3 image[row*width+tcol+col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { jpeg_destroy_decompress (&cinfo); throw; } #endif jpeg_abort_decompress (&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress (&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = { 162, 192, 187, 92 }; static const int add[4] = { 0, 636, 424, 212 }; uchar pixel[848]; int row, shift, col; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col=0; col < width; col++) RAW(row,col) = (ushort) pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *) calloc (raw_width, sizeof *pixel); merror (pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, 1, raw_width, ifp) < raw_width) derror(); for (col=0; col < raw_width; col++) RAW(row,col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 2*sizeof *pixel); merror (pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread (pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek (ifp, raw_width*32, SEEK_CUR); for (col=0; col < width; col++) { y = pixel[col*2]; cb = pixel[(col*2 & -4) | 1] - 128; cr = pixel[(col*2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *) calloc (raw_width, 3*sizeof *pixel); merror (pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread (pixel, raw_width, 3, ifp) < 3) derror(); for (col=0; col < width; col++) { y = pixel[width*2*(row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2)+1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row*width+col][c] = curve[LIM(rgb[c],0,255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { { 0,1,5,1,1,2,0,0,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 }, { 0,3,1,1,1,1,1,2,0,0,0,0,0,0,0,0, 0,1,2,3,4,5,6,7,8,9 } }; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi=0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder (kodak_tree[c]); ns = (raw_height+63) >> 5; pixel = (uchar *) malloc (raw_width*32 + ns*4); merror (pixel, "kodak_262_load_raw()"); strip = (int *) (pixel + raw_width*32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek (ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col=0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi-2 : pi-raw_width-1; pi2 = chess ? pi-2*raw_width : pi-raw_width+1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi-2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff (huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row,col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (pixel); throw; } #endif free (pixel); FORC(2) free (huff[c]); } int CLASS kodak_65000_decode (short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf=0; int save, bits=0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i=0; i < bsize; i+=2) { c = fgetc(ifp); if ((blen[i ] = c & 15) > 12 || (blen[i+1] = c >> 4) > 12 ) { fseek (ifp, save, SEEK_SET); for (i=0; i < bsize; i+=8) { read_shorts (raw, 6); out[i ] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i+1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j=0; j < 6; j++) out[i+2+j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i=0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j=0; j < 32; j+=8) bitbuf += (INT64) fgetc(ifp) << (bits+(j^8)); bits += 32; } diff = bitbuf & (0xffff >> (16-len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len-1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[256]; int row, col, len, pred[2], ret, i; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { pred[0] = pred[1] = 0; len = MIN (256, width-col); ret = kodak_65000_decode (buf, len); for (i=0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx <= 0xffff) { if ((RAW(row,col+i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17)?load_flags:10; for (row=0; row < height; row+=2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=128) { len = MIN (128, width-col); kodak_65000_decode (buf, len*3); y[0][1] = y[1][1] = cb = cr = 0; for (bp=buf, i=0; i < len; i+=2, bp+=2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j=0; j < 2; j++) for (k=0; k < 2; k++) { if ((y[j][k] = y[j][k^1] + *bp++) >> bits) derror(); ip = image[(row+j)*width + col+i+k]; FORC3 ip[c] = curve[LIM(y[j][k]+rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3],ret; ushort *ip=image[0]; for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col+=256) { len = MIN (256, width-col); ret = kodak_65000_decode (buf, len*3); memset (rgb, 0, sizeof rgb); for (bp=buf, i=0; i < len; i++, ip+=4) #ifdef LIBRAW_LIBRARY_BUILD if(load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row=0; row < height; row++) for (col=0; col < width; col++) read_shorts (image[row*width+col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt (unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p=0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0]^pad[2]) >> 31; for (p=4; p < 127; p++) pad[p] = (pad[p-4]^pad[p-2]) << 1 | (pad[p-3]^pad[p-1]) >> 31; for (p=0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p+1) & 127] ^ pad[(p+65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek (ifp, 200896, SEEK_SET); fseek (ifp, (unsigned) fgetc(ifp)*4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek (ifp, 164600, SEEK_SET); fread (head, 1, 40, ifp); sony_decrypt ((unsigned *) head, 10, 1, key); for (i=26; i-- > 22; ) key = key << 8 | head[i]; fseek (ifp, data_offset, SEEK_SET); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row*raw_width; if (fread (pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt ((unsigned *) pixel, raw_width/2, !row, key); for (col=0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = { 0xf11,0xf10,0xe0f,0xd0e,0xc0d,0xb0c,0xa0b,0x90a,0x809, 0x708,0x607,0x506,0x405,0x304,0x303,0x300,0x202,0x201 }; int i, c, n, col, row, sum=0; huff[0] = 15; for (n=i=0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--; ) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row=0; row < raw_height+1; row+=2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row,col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *) malloc (raw_width+1); merror (data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread (data, 1, raw_width, ifp); for (dp=data, col=0; col < raw_width-30; dp+=16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh=0; sh < 4 && 0x80 << sh <= max-min; sh++); #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if(! (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) ) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i]=0; } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit=30, i=0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp+(bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i=0; i < 16; i++, col+=2) { unsigned slope = pix[i] < 1001? 2 : curve[pix[i]<<1]-curve[(pix[i]<<1)-2]; unsigned step = 1 << sh; RAW(row,col)=curve[pix[i]<<1]>black+imgdata.params.sony_arw2_posterization_thr? LIM(((slope*step*1000)/(curve[pix[i]<<1]-black)),0,10000):0; } } else { for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1]; } #else for (i=0; i < 16; i++, col+=2) RAW(row,col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1:31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch(...) { free (data); throw; } if(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum=10000; #endif free (data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, strip_offset+row*4, SEEK_SET); fseek (ifp, data_offset+get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7:4; for (col=0; col < raw_width; col+=16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c=0; c < 16; c+=2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row,col+c) = ((signed) ph1_bits(i) << (32-i) >> (32-i)) + (dir ? RAW(row+(~c | -2),col+c) : col ? RAW(row,col+(c | -2)) : 128); if (c == 14) c = -1; } } } for (row=0; row < raw_height-1; row+=2) for (col=0; col < raw_width-1; col+=2) SWAP (RAW(row,col+1), RAW(row+1,col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = { 0x304,0x307,0x206,0x205,0x403,0x600,0x709, 0x80a,0x90b,0xa0c,0xa0d,0x501,0x408,0x402 }; ushort huff[1026], vpred[2][2] = {{0,0},{0,0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n=i=0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < raw_width; col++) { diff = ljpeg_diff (huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row,col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek (ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(),get2()); for (row=0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek (ifp, (data_offset-ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6) ((ushort *)lent)[c] = row < 2 ? 7:4; prow[ row & 1] = &RAW(row-1,1-((row & 1) << 1)); // green prow[~row & 1] = &RAW(row-2,0); // red and blue for (tab=0; tab+15 < raw_width; tab+=16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag-'2'+"204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4*ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0]-'1'+"120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1)^(c >> 3)^(row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row,tab-2+(col & 1)) : init) : (prow[col & 1][col-'4'+"0224468"[pmode]] + prow[col & 1][col-'4'+"0244668"[pmode]] + 1) >> 1; diff = ph1_bits (i = len[c >> 2]); if (diff >> (i-1)) diff -= 1 << i; diff = diff * (mag*2+1) + mag; RAW(row,col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row) - raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment (unsigned seg[2][2], int holes) { uchar hist[3][13] = { { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0 }, { 3, 3, 0, 0, 63, 47, 31, 15, 0 } }; int low, high=0xff, carry=0, nbits=8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[]={0,0}; ushort data=0, range=0; fseek (ifp, seg[0][1]+1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width*raw_height) seg[1][0] = raw_width*raw_height; for (pix=seg[0][0]; pix < seg[1][0]; pix++) { for (s=0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry+1) < 1 ? nbits-1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits-1)) - 1)) << 1) | ((data + (((data & (1 << (nbits-1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data-range+1) & 0xffff) << 2) - 1) / (high >> 4); for (bin=0; hist[s][bin+5] > count; bin++); low = hist[s][bin+5] * (high >> 4) >> 2; if (bin) high = hist[s][bin+4] * (high >> 4) >> 2; high -= low; for (nbits=0; high << nbits < 128; nbits++); range = (range+low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next+1) & hist[s][0]; hist[s][3] = (hist[s][next+4] - hist[s][next+5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1]+4] - hist[s][hist[s][1]+5] > 1) { if (bin < hist[s][1]) for (i=bin; i < hist[s][1]; i++) hist[s][i+5]--; else if (next <= bin) for (i=hist[s][1]; i < bin; i++) hist[s][i+5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if(pix>=raw_width*raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek (ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment (seg, 0); } int CLASS median4 (int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i=1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes (int holes) { int row, col, val[4]; for (row=2; row < height-2; row++) { if (!HOLE(row)) continue; for (col=1; col < width-1; col+=4) { val[0] = RAW(row-1,col-1); val[1] = RAW(row-1,col+1); val[2] = RAW(row+1,col-1); val[3] = RAW(row+1,col+1); RAW(row,col) = median4(val); } for (col=2; col < width-2; col+=4) if (HOLE(row-2) || HOLE(row+2)) RAW(row,col) = (RAW(row,col-2) + RAW(row,col+2)) >> 1; else { val[0] = RAW(row,col-2); val[1] = RAW(row,col+2); val[2] = RAW(row-2,col); val[3] = RAW(row+2,col); RAW(row,col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek (ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar) fgetc(ifp); fseek (ifp, offset, SEEK_SET); for (i=0; i < nseg*2; i++) ((unsigned *)seg)[i] = get4() + data_offset*(i & 1); fseek (ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek (ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i=0; i < nseg; i++) smal_decode_segment (seg+i, holes); if (holes) fill_holes (holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen (ifname, "rb"); #else in = (jas_stream_t*)ifp->make_jas_stream(); if(!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek (in, data_offset+20, SEEK_SET); jimg = jas_image_decode (in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp (failure, 3); #else if(!jimg) { jas_stream_close (in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create (height/2, width/2); merror (jmat, "redcine_load_raw()"); img = (ushort *) calloc ((height+2), (width+2)*2); merror (img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt (jimg, c, 0, 0, width/2, height/2, jmat); data = jas_matrix_getref (jmat, 0, 0); for (row = c >> 1; row < height; row+=2) for (col = c & 1; col < width; col+=2) img[(row+1)*(width+2)+col+1] = data[(row/2)*(width/2)+col/2]; } for (col=1; col <= width; col++) { img[col] = img[2*(width+2)+col]; img[(height+1)*(width+2)+col] = img[(height-1)*(width+2)+col]; } for (row=0; row < height+2; row++) { img[row*(width+2)] = img[row*(width+2)+2]; img[(row+1)*(width+2)-1] = img[(row+1)*(width+2)-3]; } for (row=1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row*(width+2) + (col = 1 + (FC(row,1) & 1)); for ( ; col <= width; col+=2, pix+=2) { c = (((pix[0] - 0x800) << 3) + pix[-(width+2)] + pix[width+2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c,0,4095); } } for (row=0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col=0; col < width; col++) RAW(row,col) = curve[img[(row+1)*(width+2)+col+1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag=true; } #endif free (img); jas_matrix_destroy (jmat); jas_image_destroy (jimg); jas_stream_close (in); #ifdef LIBRAW_LIBRARY_BUILD if(fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width*2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row=0; row < raw_height-top_margin*2; row++) { for (col=0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row+1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col+1) >> 1); } if (r < height && c < width) BAYER(r,c) = RAW(row+top_margin,col+left_margin); } } } else { for (row=0; row < height; row++) for (col=0; col < width; col++) BAYER2(row,col) = RAW(row+top_margin,col+left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model,"DC2",3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin+height; mask[0][3] += left_margin; mask[1][1] += left_margin+width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset (mblack, 0, sizeof mblack); for (zero=m=0; m < 8; m++) for (row=MAX(mask[m][0],0); row < MIN(mask[m][2],raw_height); row++) for (col=MAX(mask[m][1],0); col < MIN(mask[m][3],raw_width); col++) { c = FC(row-top_margin,col-left_margin); mblack[c] += val = raw_image[(row)*raw_pitch/2+(col)]; mblack[4+c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0]+mblack[1]+mblack[2]+mblack[3]) / (mblack[4]+mblack[5]+mblack[6]+mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4+c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,0,2); #endif for (row=0; row < height; row++) for (col=0; col < width; col++) if (BAYER(row,col) == 0) { tot = n = 0; for (r = row-2; r <= row+2; r++) for (c = col-2; c <= col+2; c++) if (r < height && c < width && FC(r,c) == FC(row,col) && BAYER(r,c)) tot += (n++,BAYER(r,c)); if (n) BAYER(row,col) = tot/n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES,1,2); #endif } static const uchar xlat[2][256] = { { 0xc1,0xbf,0x6d,0x0d,0x59,0xc5,0x13,0x9d,0x83,0x61,0x6b,0x4f,0xc7,0x7f,0x3d,0x3d, 0x53,0x59,0xe3,0xc7,0xe9,0x2f,0x95,0xa7,0x95,0x1f,0xdf,0x7f,0x2b,0x29,0xc7,0x0d, 0xdf,0x07,0xef,0x71,0x89,0x3d,0x13,0x3d,0x3b,0x13,0xfb,0x0d,0x89,0xc1,0x65,0x1f, 0xb3,0x0d,0x6b,0x29,0xe3,0xfb,0xef,0xa3,0x6b,0x47,0x7f,0x95,0x35,0xa7,0x47,0x4f, 0xc7,0xf1,0x59,0x95,0x35,0x11,0x29,0x61,0xf1,0x3d,0xb3,0x2b,0x0d,0x43,0x89,0xc1, 0x9d,0x9d,0x89,0x65,0xf1,0xe9,0xdf,0xbf,0x3d,0x7f,0x53,0x97,0xe5,0xe9,0x95,0x17, 0x1d,0x3d,0x8b,0xfb,0xc7,0xe3,0x67,0xa7,0x07,0xf1,0x71,0xa7,0x53,0xb5,0x29,0x89, 0xe5,0x2b,0xa7,0x17,0x29,0xe9,0x4f,0xc5,0x65,0x6d,0x6b,0xef,0x0d,0x89,0x49,0x2f, 0xb3,0x43,0x53,0x65,0x1d,0x49,0xa3,0x13,0x89,0x59,0xef,0x6b,0xef,0x65,0x1d,0x0b, 0x59,0x13,0xe3,0x4f,0x9d,0xb3,0x29,0x43,0x2b,0x07,0x1d,0x95,0x59,0x59,0x47,0xfb, 0xe5,0xe9,0x61,0x47,0x2f,0x35,0x7f,0x17,0x7f,0xef,0x7f,0x95,0x95,0x71,0xd3,0xa3, 0x0b,0x71,0xa3,0xad,0x0b,0x3b,0xb5,0xfb,0xa3,0xbf,0x4f,0x83,0x1d,0xad,0xe9,0x2f, 0x71,0x65,0xa3,0xe5,0x07,0x35,0x3d,0x0d,0xb5,0xe9,0xe5,0x47,0x3b,0x9d,0xef,0x35, 0xa3,0xbf,0xb3,0xdf,0x53,0xd3,0x97,0x53,0x49,0x71,0x07,0x35,0x61,0x71,0x2f,0x43, 0x2f,0x11,0xdf,0x17,0x97,0xfb,0x95,0x3b,0x7f,0x6b,0xd3,0x25,0xbf,0xad,0xc7,0xc5, 0xc5,0xb5,0x8b,0xef,0x2f,0xd3,0x07,0x6b,0x25,0x49,0x95,0x25,0x49,0x6d,0x71,0xc7 }, { 0xa7,0xbc,0xc9,0xad,0x91,0xdf,0x85,0xe5,0xd4,0x78,0xd5,0x17,0x46,0x7c,0x29,0x4c, 0x4d,0x03,0xe9,0x25,0x68,0x11,0x86,0xb3,0xbd,0xf7,0x6f,0x61,0x22,0xa2,0x26,0x34, 0x2a,0xbe,0x1e,0x46,0x14,0x68,0x9d,0x44,0x18,0xc2,0x40,0xf4,0x7e,0x5f,0x1b,0xad, 0x0b,0x94,0xb6,0x67,0xb4,0x0b,0xe1,0xea,0x95,0x9c,0x66,0xdc,0xe7,0x5d,0x6c,0x05, 0xda,0xd5,0xdf,0x7a,0xef,0xf6,0xdb,0x1f,0x82,0x4c,0xc0,0x68,0x47,0xa1,0xbd,0xee, 0x39,0x50,0x56,0x4a,0xdd,0xdf,0xa5,0xf8,0xc6,0xda,0xca,0x90,0xca,0x01,0x42,0x9d, 0x8b,0x0c,0x73,0x43,0x75,0x05,0x94,0xde,0x24,0xb3,0x80,0x34,0xe5,0x2c,0xdc,0x9b, 0x3f,0xca,0x33,0x45,0xd0,0xdb,0x5f,0xf5,0x52,0xc3,0x21,0xda,0xe2,0x22,0x72,0x6b, 0x3e,0xd0,0x5b,0xa8,0x87,0x8c,0x06,0x5d,0x0f,0xdd,0x09,0x19,0x93,0xd0,0xb9,0xfc, 0x8b,0x0f,0x84,0x60,0x33,0x1c,0x9b,0x45,0xf1,0xf0,0xa3,0x94,0x3a,0x12,0x77,0x33, 0x4d,0x44,0x78,0x28,0x3c,0x9e,0xfd,0x65,0x57,0x16,0x94,0x6b,0xfb,0x59,0xd0,0xc8, 0x22,0x36,0xdb,0xd2,0x63,0x98,0x43,0xa1,0x04,0x87,0x86,0xf7,0xa6,0x26,0xbb,0xd6, 0x59,0x4d,0xbf,0x6a,0x2e,0xaa,0x2b,0xef,0xe6,0x78,0xb6,0x4e,0xe0,0x2f,0xdc,0x7c, 0xbe,0x57,0x19,0x32,0x7e,0x2a,0xd0,0xb8,0xba,0x29,0x00,0x3c,0x52,0x7d,0xa8,0x49, 0x3b,0x2d,0xeb,0x25,0x49,0xfa,0xa3,0xaa,0x39,0xa7,0xc5,0xa7,0x50,0x11,0x36,0xfb, 0xc6,0x67,0x4a,0xf5,0xa5,0x12,0x65,0x7e,0xb0,0xdf,0xaf,0x4e,0xb3,0x61,0x7f,0x2f } }; void CLASS gamma_curve (double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2]={0,0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1]-1)*(g[0]-1) <= 0) { for (i=0; i < 48; i++) { g[2] = (bnd[0] + bnd[1])/2; if (g[0]) bnd[(pow(g[2]/g[1],-g[0]) - 1)/g[0] - 1/g[2] > -1] = g[2]; else bnd[g[2]/exp(1-1/g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1/g[0] - 1); } if (g[0]) g[5] = 1 / (g[1]*SQR(g[3])/2 - g[4]*(1 - g[3]) + (1 - pow(g[3],1+g[0]))*(1 + g[4])/(1 + g[0])) - 1; else g[5] = 1 / (g[1]*SQR(g[3])/2 + 1 - g[2] - g[3] - g[2]*g[3]*(log(g[3]) - 1)) - 1; if (!mode--) { memcpy (gamm, g, sizeof gamm); return; } for (i=0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double) i / imax) < 1) curve[i] = 0x10000 * ( mode ? (r < g[3] ? r*g[1] : (g[0] ? pow( r,g[0])*(1+g[4])-g[4] : log(r)*g[2]+1)) : (r < g[2] ? r/g[1] : (g[0] ? pow((r+g[4])/(1+g[4]),1/g[0]) : exp((r-1)/g[2])))); } } void CLASS pseudoinverse (double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i=0; i < 3; i++) { for (j=0; j < 6; j++) work[i][j] = j == i+3; for (j=0; j < 3; j++) for (k=0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i=0; i < 3; i++) { num = work[i][i]; for (j=0; j < 6; j++) work[i][j] /= num; for (k=0; k < 3; k++) { if (k==i) continue; num = work[k][i]; for (j=0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i=0; i < size; i++) for (j=0; j < 3; j++) for (out[i][j]=k=0; k < 3; k++) out[i][j] += work[j][k+3] * in[i][k]; } void CLASS cam_xyz_coeff (float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i=0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j=0; j < 3; j++) for (cam_rgb[i][j] = k=0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i=0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num=j=0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if(num > 0.00001) { for (j=0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j=0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse (cam_rgb, inverse, colors); for (i=0; i < 3; i++) for (j=0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = { { 0.400, 0.350, 10.1 }, // Dark Skin { 0.377, 0.345, 35.8 }, // Light Skin { 0.247, 0.251, 19.3 }, // Blue Sky { 0.337, 0.422, 13.3 }, // Foliage { 0.265, 0.240, 24.3 }, // Blue Flower { 0.261, 0.343, 43.1 }, // Bluish Green { 0.506, 0.407, 30.1 }, // Orange { 0.211, 0.175, 12.0 }, // Purplish Blue { 0.453, 0.306, 19.8 }, // Moderate Red { 0.285, 0.202, 6.6 }, // Purple { 0.380, 0.489, 44.3 }, // Yellow Green { 0.473, 0.438, 43.1 }, // Orange Yellow { 0.187, 0.129, 6.1 }, // Blue { 0.305, 0.478, 23.4 }, // Green { 0.539, 0.313, 12.0 }, // Red { 0.448, 0.470, 59.1 }, // Yellow { 0.364, 0.233, 19.8 }, // Magenta { 0.196, 0.252, 19.8 }, // Cyan { 0.310, 0.316, 90.0 }, // White { 0.310, 0.316, 59.1 }, // Neutral 8 { 0.310, 0.316, 36.2 }, // Neutral 6.5 { 0.310, 0.316, 19.8 }, // Neutral 5 { 0.310, 0.316, 9.0 }, // Neutral 3.5 { 0.310, 0.316, 3.1 } }; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset (gmb_cam, 0, sizeof gmb_cam); for (sq=0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row=cut[sq][3]; row < cut[sq][3]+cut[sq][1]; row++) for (col=cut[sq][2]; col < cut[sq][2]+cut[sq][0]; col++) { c = FC(row,col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row,col); BAYER2(row,col) = black + (BAYER2(row,col)-black)/2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c]/count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse (gmb_xyz, inverse, NSQ); for (pass=0; pass < 2; pass++) { for (raw_color = i=0; i < colors; i++) for (j=0; j < 3; j++) for (cam_xyz[i][j] = k=0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff (rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq=0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf (" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j=0; j < 3; j++) printf ("%c%d", (c | j) ? ',':' ', (int) (cam_xyz[c][j] * num + 0.5)); puts (" } },"); } #undef NSQ } #endif void CLASS hat_transform (float *temp, float *base, int st, int size, int sc) { int i; for (i=0; i < sc; i++) temp[i] = 2*base[st*i] + base[st*(sc-i)] + base[st*(i+sc)]; for (; i+sc < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(i+sc)]; for (; i < size; i++) temp[i] = 2*base[st*i] + base[st*(i-sc)] + base[st*(2*size-2-(i+sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg=0, *temp, thold, mul[2], avg, diff; int scale=1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = { 0.8002,0.2735,0.1202,0.0585,0.0291,0.0152,0.0080,0.0044 }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight*iwidth) < 0x15550000) fimg = (float *) malloc ((size*3 + iheight + iwidth) * sizeof *fimg); merror (fimg, "wavelet_denoise()"); temp = fimg + size*3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i,col,row,thold,lev,lpass,hpass,temp,c) firstprivate(scale,size) #endif { temp = (float*)malloc( (iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass=lev=0; lev < 5; lev++) { lpass = size*((lev & 1)+1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row=0; row < iheight; row++) { hat_transform (temp, fimg+hpass+row*iwidth, 1, iwidth, 1 << lev); for (col=0; col < iwidth; col++) fimg[lpass + row*iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col=0; col < iwidth; col++) { hat_transform (temp, fimg+lpass+col, iwidth, iheight, 1 << lev); for (row=0; row < iheight; row++) fimg[lpass + row*iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) { fimg[hpass+i] -= fimg[lpass+i]; if (fimg[hpass+i] < -thold) fimg[hpass+i] += thold; else if (fimg[hpass+i] > thold) fimg[hpass+i] -= thold; else fimg[hpass+i] = 0; if (hpass) fimg[i] += fimg[hpass+i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i=0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i]+fimg[lpass+i])/0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row=0; row < 2; row++){ mul[row] = 0.125 * pre_mul[FC(row+1,0) | 1] / pre_mul[FC(row,0) | 1]; blk[row] = cblack[FC(row,0) | 1]; } for (i=0; i < 4; i++) window[i] = (ushort *) fimg + width*i; for (wlast=-1, row=1; row < height-1; row++) { while (wlast < row+1) { for (wlast++, i=0; i < 4; i++) window[(i+3) & 3] = window[i]; for (col = FC(wlast,1) & 1; col < width; col+=2) window[2][col] = BAYER(wlast,col); } thold = threshold/512; for (col = (FC(row,0) & 1)+1; col < width-1; col+=2) { avg = ( window[0][col-1] + window[0][col+1] + window[2][col-1] + window[2][col+1] - blk[~row & 1]*4 ) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row,col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row,col) = CLIP(SQR(avg+diff) + 0.5); } } } free (fimg); } #endif // green equilibration void CLASS green_matching() { int i,j; double m1,m2,c1,c2; int o1_1,o1_2,o1_3,o1_4; int o2_1,o2_2,o2_3,o2_4; ushort (*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if(half_size || shrink) return; if(FC(oj, oi) != 3) oj++; if(FC(oj, oi) != 3) oi++; if(FC(oj, oi) != 3) oj--; img = (ushort (*)[4]) calloc (height*width, sizeof *image); merror (img, "green_matching()"); memcpy(img,image,height*width*sizeof *image); for(j=oj;j<height-margin;j+=2) for(i=oi;i<width-margin;i+=2){ o1_1=img[(j-1)*width+i-1][1]; o1_2=img[(j-1)*width+i+1][1]; o1_3=img[(j+1)*width+i-1][1]; o1_4=img[(j+1)*width+i+1][1]; o2_1=img[(j-2)*width+i][3]; o2_2=img[(j+2)*width+i][3]; o2_3=img[j*width+i-2][3]; o2_4=img[j*width+i+2][3]; m1=(o1_1+o1_2+o1_3+o1_4)/4.0; m2=(o2_1+o2_2+o2_3+o2_4)/4.0; c1=(abs(o1_1-o1_2)+abs(o1_1-o1_3)+abs(o1_1-o1_4)+abs(o1_2-o1_3)+abs(o1_3-o1_4)+abs(o1_2-o1_4))/6.0; c2=(abs(o2_1-o2_2)+abs(o2_1-o2_3)+abs(o2_1-o2_4)+abs(o2_2-o2_3)+abs(o2_3-o2_4)+abs(o2_2-o2_4))/6.0; if((img[j*width+i][3]<maximum*0.95)&&(c1<maximum*thr)&&(c2<maximum*thr)) { f = image[j*width+i][3]*m1/m2; image[j*width+i][3]=f>0xffff?0xffff:f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img=0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,0,2); #endif if (user_mul[0]) memcpy (pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset (dsum, 0, sizeof dsum); bottom = MIN (greybox[1]+greybox[3], height); right = MIN (greybox[0]+greybox[2], width); for (row=greybox[1]; row < bottom; row += 8) for (col=greybox[0]; col < right; col += 8) { memset (sum, 0, sizeof sum); for (y=row; y < row+8 && y < bottom; y++) for (x=col; x < col+8 && x < right; x++) FORC4 { if (filters) { c = fcol(y,x); val = BAYER2(y,x); } else val = image[y*width+x][c]; if (val > maximum-25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c+4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block: ; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c+4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset (sum, 0, sizeof sum); for (row=0; row < 8; row++) for (col=0; col < 8; col++) { c = FC(row,col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c+4]++; } #ifdef LIBRAW_LIBRARY_BUILD if(load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0]=pre_mul[1]=pre_mul[2]=pre_mul[3]=1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float) sum[c+4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy (pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f ) { for(c=0;c<3;c++) pre_mul[c]/=cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin=DBL_MAX, dmax=c=0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf (stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf (stderr, " %f", pre_mul[c]); fputc ('\n', stderr); } #endif if (filters > 1000 && (cblack[4]+1)/2 == 1 && (cblack[5]+1)/2 == 1) { FORC4 cblack[FC(c/2,c%2)] += cblack[6 + c/2 % cblack[4] * cblack[5] + c%2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight*iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i=0; i < size*4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i/4 / iwidth % cblack[4] * cblack[5] + i/4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Correcting chromatic aberration...\n")); #endif for (c=0; c < 4; c+=2) { if (aber[c] == 1) continue; img = (ushort *) malloc (size * sizeof *img); merror (img, "scale_colors()"); for (i=0; i < size; i++) img[i] = image[i][c]; for (row=0; row < iheight; row++) { ur = fr = (row - iheight*0.5) * aber[c] + iheight*0.5; if (ur > iheight-2) continue; fr -= ur; for (col=0; col < iwidth; col++) { uc = fc = (col - iwidth*0.5) * aber[c] + iwidth*0.5; if (uc > iwidth-2) continue; fc -= uc; pix = img + ur*iwidth + uc; image[row*iwidth+col][c] = (pix[ 0]*(1-fc) + pix[ 1]*fc) * (1-fr) + (pix[iwidth]*(1-fc) + pix[iwidth+1]*fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS,1,2); #endif } void CLASS pre_interpolate() { ushort (*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,0,2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row=0; row < 3; row++) for (col=1; col < 4; col++) if (!(image[row*width+col][0] | image[row*width+col][2])) goto break2; break2: for ( ; row < height; row+=3) for (col=(col-1)%3+1; col < width-1; col+=3) { img = image + row*width+col; for (c=0; c < 3; c+=2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort (*)[4]) calloc (height, width*sizeof *img); merror (img, "pre_interpolate()"); for (row=0; row < height; row++) for (col=0; col < width; col++) { c = fcol(row,col); img[row*width+col][c] = image[(row >> 1)*iwidth+(col >> 1)][c]; } free (image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1,0) >> 1; row < height; row+=2) for (col = FC(row,1) & 1; col < width; col+=2) image[row*width+col][1] = image[row*width+col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE,1,2); #endif } void CLASS border_interpolate (int border) { unsigned row, col, y, x, f, c, sum[8]; for (row=0; row < height; row++) for (col=0; col < width; col++) { if (col==border && row >= border && row < height-border) col = width-border; memset (sum, 0, sizeof sum); for (y=row-1; y != row+2; y++) for (x=col-1; x != col+2; x++) if (y < height && x < width) { f = fcol(y,x); sum[f] += image[y*width+x][f]; sum[f+4]++; } f = fcol(row,col); FORCC if (c != f && sum[c+4]) image[row*width+col][c] = sum[c] / sum[c+4]; } } void CLASS lin_interpolate_loop(int code[16][16][32],int size) { int row; for (row=1; row < height-1; row++) { int col,*ip; ushort *pix; for (col=1; col < width-1; col++) { int i; int sum[4]; pix = image[row*width+col]; ip = code[row % size][col % size]; memset (sum, 0, sizeof sum); for (i=*ip++; i--; ip+=3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i=colors; --i; ip+=2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size=16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row=0; row < size; row++) for (col=0; col < size; col++) { ip = code[row][col]+1; f = fcol(row,col); memset (sum, 0, sizeof sum); for (y=-1; y <= 1; y++) for (x=-1; x <= 1; x++) { shift = (y==0) + (x==0); color = fcol(row+y,col+x); if (color == f) continue; *ip++ = (width*y + x)*4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c]>0?256 / sum[c]:0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #endif lin_interpolate_loop(code,size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = { -2,-2,+0,-1,0,0x01, -2,-2,+0,+0,1,0x01, -2,-1,-1,+0,0,0x01, -2,-1,+0,-1,0,0x02, -2,-1,+0,+0,0,0x03, -2,-1,+0,+1,1,0x01, -2,+0,+0,-1,0,0x06, -2,+0,+0,+0,1,0x02, -2,+0,+0,+1,0,0x03, -2,+1,-1,+0,0,0x04, -2,+1,+0,-1,1,0x04, -2,+1,+0,+0,0,0x06, -2,+1,+0,+1,0,0x02, -2,+2,+0,+0,1,0x04, -2,+2,+0,+1,0,0x04, -1,-2,-1,+0,0,-128, -1,-2,+0,-1,0,0x01, -1,-2,+1,-1,0,0x01, -1,-2,+1,+0,1,0x01, -1,-1,-1,+1,0,-120, -1,-1,+1,-2,0,0x40, -1,-1,+1,-1,0,0x22, -1,-1,+1,+0,0,0x33, -1,-1,+1,+1,1,0x11, -1,+0,-1,+2,0,0x08, -1,+0,+0,-1,0,0x44, -1,+0,+0,+1,0,0x11, -1,+0,+1,-2,1,0x40, -1,+0,+1,-1,0,0x66, -1,+0,+1,+0,1,0x22, -1,+0,+1,+1,0,0x33, -1,+0,+1,+2,1,0x10, -1,+1,+1,-1,1,0x44, -1,+1,+1,+0,0,0x66, -1,+1,+1,+1,0,0x22, -1,+1,+1,+2,0,0x10, -1,+2,+0,+1,0,0x04, -1,+2,+1,+0,1,0x04, -1,+2,+1,+1,0,0x04, +0,-2,+0,+0,1,-128, +0,-1,+0,+1,1,-120, +0,-1,+1,-2,0,0x40, +0,-1,+1,+0,0,0x11, +0,-1,+2,-2,0,0x40, +0,-1,+2,-1,0,0x20, +0,-1,+2,+0,0,0x30, +0,-1,+2,+1,1,0x10, +0,+0,+0,+2,1,0x08, +0,+0,+2,-2,1,0x40, +0,+0,+2,-1,0,0x60, +0,+0,+2,+0,1,0x20, +0,+0,+2,+1,0,0x30, +0,+0,+2,+2,1,0x10, +0,+1,+1,+0,0,0x44, +0,+1,+1,+2,0,0x10, +0,+1,+2,-1,1,0x40, +0,+1,+2,+0,0,0x60, +0,+1,+2,+1,0,0x20, +0,+1,+2,+2,0,0x10, +1,-2,+1,+0,0,-128, +1,-1,+1,+1,0,-120, +1,+0,+1,+2,0,0x08, +1,+0,+2,-1,0,0x40, +1,+0,+2,+1,0,0x10 }, chood[] = { -1,-1, -1,0, -1,+1, 0,+1, +1,+1, +1,0, +1,-1, 0,-1 }; ushort (*brow[5])[4], *pix; int prow=8, pcol=2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *) calloc (prow*pcol, 1280); merror (ip, "vng_interpolate()"); for (row=0; row < prow; row++) /* Precalculate for VNG */ for (col=0; col < pcol; col++) { code[row][col] = ip; for (cp=terms, t=0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row+y1,col+x1); if (fcol(row+y2,col+x2) != color) continue; diag = (fcol(row,col+1) == color && fcol(row+1,col) == color) ? 2:1; if (abs(y1-y2) == diag && abs(x1-x2) == diag) continue; *ip++ = (y1*width + x1)*4 + color; *ip++ = (y2*width + x2)*4 + color; *ip++ = weight; for (g=0; g < 8; g++) if (grads & 1<<g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp=chood, g=0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y*width + x) * 4; color = fcol(row,col); if (fcol(row+y,col+x) != color && fcol(row+y*2,col+x*2) == color) *ip++ = (y*width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort (*)[4]) calloc (width*3, sizeof **brow); merror (brow[4], "vng_interpolate()"); for (row=0; row < 3; row++) brow[row] = brow[4] + row*width; for (row=2; row < height-2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if(!((row-2)%256))RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,(row-2)/256+1,((height-3)/256)+1); #endif for (col=2; col < width-2; col++) { pix = image[row*width+col]; ip = code[row % prow][col % pcol]; memset (gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g=1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy (brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset (sum, 0, sizeof sum); color = fcol(row,col); for (num=g=0; g < 8; g++,ip+=2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); for (g=0; g < 4; g++) brow[(g-1) & 3] = brow[g]; } memcpy (image[(row-2)*width+2], brow[0]+2, (width-4)*sizeof *image); memcpy (image[(row-1)*width+2], brow[1]+2, (width-4)*sizeof *image); free (brow[4]); free (code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = { 1, width, -1, -width, 1 }; int row, col, diff[2], guess[2], c, d, i; ushort (*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,0,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=3; row < height-3; row++) for (col=3+(FC(row,3) & 1), c=FC(row,col); col < width-3; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2*d][c] - pix[2*d][c]; diff[i] = ( ABS(pix[-2*d][c] - pix[ 0][c]) + ABS(pix[ 2*d][c] - pix[ 0][c]) + ABS(pix[ -d][1] - pix[ d][1]) ) * 3 + ( ABS(pix[ 3*d][1] - pix[ d][1]) + ABS(pix[-3*d][1] - pix[-d][1]) ) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,1,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,2) & 1), c=FC(row,col+1); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]) > 0; c=2-c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE,2,3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row=1; row < height-1; row++) for (col=1+(FC(row,1) & 1), c=2-FC(row,col); col < width-1; col+=2) { pix = image + row*width+col; for (i=0; (d=dir[i]+dir[i+1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[ d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2*pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0]+guess[1]) >> 2); } } void CLASS cielab (ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if(cbrt[0] < -1.0f) #endif for (i=0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r,1.f/3.0f) : 7.787f*r + 16.f/116.0f; } for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (xyz_cam[i][j] = k=0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int) xyz[0])]; xyz[1] = cbrt[CLIP((int) xyz[1])]; xyz[2] = cbrt[CLIP((int) xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row,col) xtrans[(row+6) % 6][(col+6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate (int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = { 1,0,0,1,-1,0,0,-1,1,0,0,1 }, patt[2][16] = { { 0,1,0,-1,2,0,-1,0,1,1,1,-1,0,0,0,0 }, { 0,1,0,-2,1,0,-2,0,1,1,-2,-2,1,-1,-1,1 } }, dir[4] = { 1,TS,TS+1,TS-1 }; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab) [TS][3], (*lix)[3]; float (*drv)[TS][TS], diff[6], tr; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif cielab (0,0); ndir = 4 << (passes > 1); buffer = (char *) malloc (TS*TS*(ndir*11+6)); merror (buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*) [TS][3])(buffer + TS*TS*(ndir*6)); drv = (float (*)[TS][TS]) (buffer + TS*TS*(ndir*6+6)); homo = (char (*)[TS][TS]) (buffer + TS*TS*(ndir*10+6)); /* Map a green hexagon around each non-green pixel and vice versa: */ for (row=0; row < 3; row++) for (col=0; col < 3; col++) for (ng=d=0; d < 10; d+=2) { g = fcol(row,col) == 1; if (fcol(row+orth[d],col+orth[d+2]) == 1) ng=0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g+1) FORC(8) { v = orth[d ]*patt[g][c*2] + orth[d+1]*patt[g][c*2+1]; h = orth[d+2]*patt[g][c*2] + orth[d+3]*patt[g][c*2+1]; allhex[row][col][0][c^(g*2 & d)] = h + v*width; allhex[row][col][1][c^(g*2 & d)] = h + v*TS; } } /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row=2; row < height-2; row++) for (min=~(max=0), col=2; col < width-2; col++) { if (fcol(row,col) == 1 && (min=~(max=0))) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row-sgrow) % 3) { case 1: if (row < height-3) { row++; col--; } break; case 2: if ((min=~(max=0)) && (col+=2) < width-3 && row > 2) row--; } } for (top=3; top < height-19; top += TS-16) for (left=3; left < width-19; left += TS-16) { mrow = MIN (top+TS, height-3); mcol = MIN (left+TS, width-3); for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) memcpy (rgb[0][row-top][col-left], image[row*width+col], 6); FORC3 memcpy (rgb[c+1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row=top; row < mrow; row++) for (col=left; col < mcol; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[ hex[1]][1] + pix[ hex[0]][1]) - 46 * (pix[2*hex[1]][1] + pix[2*hex[0]][1]); color[1][1] = 223 * pix[ hex[3]][1] + pix[ hex[2]][1] * 33 + 92 * (pix[ 0 ][f] - pix[ -hex[2]][f]); FORC(2) color[1][2+c] = 164 * pix[hex[4+c]][1] + 92 * pix[-2*hex[4+c]][1] + 33 * (2*pix[0][f] - pix[3*hex[4+c]][f] - pix[-3*hex[4+c]][f]); FORC4 rgb[c^!((row-sgrow) % 3)][row-top][col-left][1] = LIM(color[1][c] >> 8,pix[0][1],pix[0][3]); } for (pass=0; pass < passes; pass++) { if (pass == 1) memcpy (rgb+=4, buffer, 4*sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row=top+2; row < mrow-2; row++) for (col=left+2; col < mcol-2; col++) { if ((f = fcol(row,col)) == 1) continue; pix = image + row*width + col; hex = allhex[row % 3][col % 3][1]; for (d=3; d < 6; d++) { rix = &rgb[(d-2)^!((row-sgrow) % 3)][row-top][col-left]; val = rix[-2*hex[d]][1] + 2*rix[hex[d]][1] - rix[-2*hex[d]][f] - 2*rix[hex[d]][f] + 3*rix[0][f]; rix[0][1] = LIM(val/3,pix[0][1],pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row=(top-sgrow+4)/3*3+sgrow; row < mrow-2; row+=3) for (col=(left-sgcol+4)/3*3+sgcol; col < mcol-2; col+=3) { rix = &rgb[0][row-top][col-left]; h = fcol(row,col+1); memset (diff, 0, sizeof diff); for (i=1, d=0; d < 6; d++, i^=TS^1, h^=2) { for (c=0; c < 2; c++, h^=2) { g = 2*rix[0][1] - rix[i<<c][1] - rix[-i<<c][1]; color[h][d] = g + rix[i<<c][h] + rix[-i<<c][h]; if (d > 1) diff[d] += SQR (rix[i<<c][1] - rix[-i<<c][1] - rix[i<<c][h] + rix[-i<<c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d-1] < diff[d]) FORC(2) color[c*2][d] = color[c*2][d-1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c*2] = CLIP(color[c*2][d]/2); rix += TS*TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row=top+3; row < mrow-3; row++) for (col=left+3; col < mcol-3; col++) { if ((f = 2-fcol(row,col)) == 1) continue; rix = &rgb[0][row-top][col-left]; c = (row-sgrow) % 3 ? TS:1; h = 3 * (c ^ TS ^ 1); for (d=0; d < 4; d++, rix += TS*TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1]-rix[c][1])+ABS(rix[0][1]-rix[-c][1])) < 2*(ABS(rix[0][1]-rix[h][1])+ABS(rix[0][1]-rix[-h][1]))) ? c:h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2*rix[0][1] - rix[i][1] - rix[-i][1])/2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row=top+2; row < mrow-2; row++) if ((row-sgrow) % 3) for (col=left+2; col < mcol-2; col++) if ((col-sgcol) % 3) { rix = &rgb[0][row-top][col-left]; hex = allhex[row % 3][col % 3][1]; for (d=0; d < ndir; d+=2, rix += TS*TS) if (hex[d] + hex[d+1]) { g = 3*rix[0][1] - 2*rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + 2*rix[hex[d]][c] + rix[hex[d+1]][c])/3); } else { g = 2*rix[0][1] - rix[hex[d]][1] - rix[hex[d+1]][1]; for (c=0; c < 4; c+=2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d+1]][c])/2); } } } rgb = (ushort(*)[TS][TS][3]) buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d=0; d < ndir; d++) { for (row=2; row < mrow-2; row++) for (col=2; col < mcol-2; col++) cielab (rgb[d][row][col], lab[row][col]); for (f=dir[d & 3],row=3; row < mrow-3; row++) for (col=3; col < mcol-3; col++) { lix = &lab[row][col]; g = 2*lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2*lix[0][1] - lix[f][1] - lix[-f][1] + g*500/232)) + SQR((2*lix[0][2] - lix[f][2] - lix[-f][2] - g*500/580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir*TS*TS); for (row=4; row < mrow-4; row++) for (col=4; col < mcol-4; col++) { for (tr=FLT_MAX, d=0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d=0; d < ndir; d++) for (v=-1; v <= 1; v++) for (h=-1; h <= 1; h++) if (drv[d][row+v][col+h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height-top < TS+4) mrow = height-top+2; if (width-left < TS+4) mcol = width-left+2; for (row = MIN(top,8); row < mrow-8; row++) for (col = MIN(left,8); col < mcol-8; col++) { for (d=0; d < ndir; d++) for (hm[d]=0, v=-2; v <= 2; v++) for (h=-2; h <= 2; h++) hm[d] += homo[d][row+v][col+h]; for (d=0; d < ndir-4; d++) if (hm[d] < hm[d+4]) hm[d ] = 0; else if (hm[d] > hm[d+4]) hm[d+4] = 0; for (max=hm[0],d=1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset (avg, 0, sizeof avg); for (d=0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row+top)*width+col+left][c] = avg[c]/avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort (*pix)[4]; const int rowlimit = MIN(top+TS, height-2); const int collimit = MIN(left+TS, width-2); for (row = top; row < rowlimit; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < collimit; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; out_rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort (*pix)[4]; ushort (*rix)[3]; short (*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4*width; const unsigned rowlimit = MIN(top+TS-1, height-3); const unsigned collimit = MIN(left+TS-1, width-3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top+1; row < rowlimit; row++) { pix = image + row*width + left; rix = &inout_rgb[row-top][0]; lix = &out_lab[row-top][0]; for (col = left+1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row+1,col); t1 = 2-c; val = pix[0][1] + (( pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + (( pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else { t1 = -4+c; /* -4+c: pixel of color c to the left */ t2 = 4+c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + (( pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab(rix[0],lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short (*lix)[3]; short (*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = { -1, 1, -TS, TS }; const int rowlimit = MIN(top+TS-2, height-4); const int collimit = MIN(left+TS-2, width-4); int homogeneity; char (*homogeneity_map_p)[2]; memset (out_homogeneity_map, 0, 2*TS*TS); for (row=top+2; row < rowlimit; row++) { tr = row-top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction=0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col=left+2; col < collimit; col++) { tc = col-left; homogeneity_map_p++; for (direction=0; direction < 2; direction++) { lix = ++lixs[direction]; for (i=0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0]-adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1]-adjacent_lix[1]) + SQR(lix[0][2]-adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (direction=0; direction < 2; direction++) { homogeneity = 0; for (i=0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top+TS-3, height-5); const int collimit = MIN(left+TS-3, width-5); ushort (*pix)[4]; ushort (*rix[2])[3]; for (row=top+3; row < rowlimit; row++) { tr = row-top; pix = &image[row*width+left+2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col=left+3; col < collimit; col++) { tc = col-left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction=0; direction < 2; direction++) { hm[direction] = 0; for (i=tr-1; i <= tr+1; i++) { for (j=tc-1; j <= tc+1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4],r; char *buffer; ushort (*rgb)[TS][TS][3]; short (*lab)[TS][TS][3]; char (*homo)[TS][2]; int terminate_flag = 0; cielab(0,0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer,rgb,lab,homo,top,left,i,j,k) shared(xyz_cam,terminate_flag) #endif #endif { buffer = (char *) malloc (26*TS*TS); /* 1664 kB */ merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][2]) (buffer + 24*TS*TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top=2; top < height-5; top += TS-6){ #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if(0== omp_get_thread_num()) #endif if(callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data,LIBRAW_PROGRESS_INTERPOLATE,top-2,height-7); if(rr) terminate_flag = 1; } #endif for (left=2; !terminate_flag && (left < width-5); left += TS-6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free (buffer); } #ifdef LIBRAW_LIBRARY_BUILD if(terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = { -1, 1, -TS, TS }; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort (*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short (*lab)[TS][TS][3], (*lix)[3]; char (*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("AHD interpolation...\n")); #endif cielab (0,0); border_interpolate(5); buffer = (char *) malloc (26*TS*TS); merror (buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3]) buffer; lab = (short (*)[TS][TS][3])(buffer + 12*TS*TS); homo = (char (*)[TS][TS]) (buffer + 24*TS*TS); for (top=2; top < height-5; top += TS-6) for (left=2; left < width-5; left += TS-6) { /* Interpolate green horizontally and vertically: */ for (row=top; row < top+TS && row < height-2; row++) { col = left + (FC(row,left) & 1); for (c = FC(row,col); col < left+TS && col < width-2; col+=2) { pix = image + row*width+col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row-top][col-left][1] = ULIM(val,pix[-1][1],pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2*width][c] - pix[2*width][c]) >> 2; rgb[1][row-top][col-left][1] = ULIM(val,pix[-width][1],pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d=0; d < 2; d++) for (row=top+1; row < top+TS-1 && row < height-3; row++) for (col=left+1; col < left+TS-1 && col < width-3; col++) { pix = image + row*width+col; rix = &rgb[d][row-top][col-left]; lix = &lab[d][row-top][col-left]; if ((c = 2 - FC(row,col)) == 1) { c = FC(row+1,col); val = pix[0][1] + (( pix[-1][2-c] + pix[1][2-c] - rix[-1][1] - rix[1][1] ) >> 1); rix[0][2-c] = CLIP(val); val = pix[0][1] + (( pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1] ) >> 1); } else val = rix[0][1] + (( pix[-width-1][c] + pix[-width+1][c] + pix[+width-1][c] + pix[+width+1][c] - rix[-TS-1][1] - rix[-TS+1][1] - rix[+TS-1][1] - rix[+TS+1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row,col); rix[0][c] = pix[0][c]; cielab (rix[0],lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset (homo, 0, 2*TS*TS); for (row=top+2; row < top+TS-2 && row < height-4; row++) { tr = row-top; for (col=left+2; col < left+TS-2 && col < width-4; col++) { tc = col-left; for (d=0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i=0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0]-lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1]-lix[dir[i]][1]) + SQR(lix[0][2]-lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0],ldiff[0][1]), MAX(ldiff[1][2],ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0],abdiff[0][1]), MAX(abdiff[1][2],abdiff[1][3])); for (d=0; d < 2; d++) for (i=0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row=top+3; row < top+TS-3 && row < height-5; row++) { tr = row-top; for (col=left+3; col < left+TS-3 && col < width-5; col++) { tc = col-left; for (d=0; d < 2; d++) for (hm[d]=0, i=tr-1; i <= tr+1; i++) for (j=tc-1; j <= tc+1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row*width+col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row*width+col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free (buffer); } #endif #undef TS void CLASS median_filter() { ushort (*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ { 1,2, 4,5, 7,8, 0,1, 3,4, 6,7, 1,2, 4,5, 7,8, 0,3, 5,8, 4,7, 3,6, 1,4, 2,5, 4,7, 4,2, 6,4, 4,2 }; for (pass=1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER,pass-1,med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Median filter pass %d...\n"), pass); #endif for (c=0; c < 3; c+=2) { for (pix = image; pix < image+width*height; pix++) pix[0][3] = pix[0][c]; for (pix = image+width; pix < image+width*(height-1); pix++) { if ((pix-image+1) % width < 2) continue; for (k=0, i = -width; i <= width; i += width) for (j = i-1; j <= i+1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i=0; i < sizeof opt; i+=2) if (med[opt[i]] > med[opt[i+1]]) SWAP (med[opt[i]] , med[opt[i+1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip=INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = { { { 1,1,1 }, { 1.7320508,-1.7320508,0 }, { -1,-1,2 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; static const float itrans[2][4][4] = { { { 1,0.8660254,-0.5 }, { 1,-0.8660254,-0.5 }, { 1,0,1 } }, { { 1,1,1,1 }, { 1,-1,1,-1 }, { 1,1,-1,-1 }, { 1,-1,-1,1 } } }; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned) (colors-3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,0,2); #endif FORCC if (clip > (i = 65535*pre_mul[c])) clip = i; for (row=0; row < height; row++) for (col=0; col < width; col++) { FORCC if (image[row*width+col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row*width+col][c]; cam[1][c] = MIN(cam[0][c],clip); } for (i=0; i < 2; i++) { FORCC for (lab[i][c]=j=0; j < colors; j++) lab[i][c] += trans[colors-3][c][j] * cam[i][j]; for (sum[i]=0,c=1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1]/sum[0]); for (c=1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c]=j=0; j < colors; j++) cam[0][c] += itrans[colors-3][c][j] * lab[0][j]; FORCC image[row*width+col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,1,2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = { {-1,-1}, {-1,0}, {-1,1}, {0,1}, {1,1}, {1,0}, {1,-1}, {0,-1} }; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rebuilding highlights...\n")); #endif grow = pow (2.0, 4-highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc=0, c=1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *) calloc (high, wide*sizeof *map); merror (map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS,c-1,colors-1); #endif memset (map, 0, high*wide*sizeof *map); for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE*SCALE) map[mrow*wide+mcol] = sum / wgt; } for (spread = 32/grow; spread--; ) { for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { if (map[mrow*wide+mcol]) continue; sum = count = 0; for (d=0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y*wide+x] > 0) { sum += (1 + (d & 1)) * map[y*wide+x]; count += 1 + (d & 1); } } if (count > 3) map[mrow*wide+mcol] = - (sum+grow) / (count+grow); } for (change=i=0; i < high*wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i=0; i < high*wide; i++) if (map[i] == 0) map[i] = 1; for (mrow=0; mrow < high; mrow++) for (mcol=0; mcol < wide; mcol++) { for (row = mrow*SCALE; row < (mrow+1)*SCALE; row++) for (col = mcol*SCALE; col < (mcol+1)*SCALE; col++) { pixel = image[row*width+col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow*wide+mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free (map); } #undef SCALE void CLASS tiff_get (unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type:0]-'0') > 4) fseek (ifp, get4()+base, SEEK_SET); } void CLASS parse_thumb_note (int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4()+base; if (tag == tlen) thumb_length = get4(); fseek (ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b>limup || b < -limup)?0.f:powf(a,b); } static float powf64(float a, float b) { return powf_lim(a,b,64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in/64.0); } static float _CanonConvertEV (short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float) Frac; return ((float)Sign * ((float)EV + Frac_f))/32.0f; } void CLASS setCanonBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( (id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ( (id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) // M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ( (id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000) ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS processCanonCameraInfo (unsigned id, uchar *CameraInfo, unsigned maxlen) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short, so broken CameraInfo[0] = 0; CameraInfo[1] = 0; switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if(iCanonFocalType>=maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if(iCanonCurFocal>=maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if(iCanonLensID>=maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if(iCanonMinFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if(iCanonMaxFocal>=maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if(iCanonLens+64>=maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings () { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets (int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets (short WBCTversion) { if (WBCTversion == 0) for (int i=0; i<15; i++)// tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f /fMAX(get2(),1.f) ; imgdata.color.WBCT_Coeffs[i][3] = 1024.0f /fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i=0; i<15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(),1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(),1.f); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x03970000))) // G7 X Mark II for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f,get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i=0; i<15; i++) // tint, offset, as shot R, as shot B, CСT { fseek (ifp, 2, SEEK_CUR); fseek (ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData (uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long) LensData[i] << 56 | (unsigned long long) LensData[i + 1] << 48 | (unsigned long long) LensData[i + 2] << 40 | (unsigned long long) LensData[i + 3] << 32 | (unsigned long long) LensData[i + 4] << 24 | (unsigned long long) LensData[i + 5] << 16 | (unsigned long long) LensData[i + 6] << 8 | (unsigned long long) imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures (unsigned long long id) { imgdata.lens.makernotes.CamID = id; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes (unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8-32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); fseek (ifp, save1+(0x5<<1), SEEK_SET); Canon_WBpresets(0,0); fseek (ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(),get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(),get2(),get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek (ifp, save1+(0x23<<1), SEEK_SET); Canon_WBpresets(2,2); fseek (ifp, save1+(0x4b<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek (ifp, save1+(0x27<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa4<<1), SEEK_SET); Canon_WBCTpresets (1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x4e<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0c4<<1), SEEK_SET); // offset 196 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x53<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xa8<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0e7<<1), SEEK_SET); // offset 231 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek (ifp, save1+(0x2b9<<1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek (ifp, save1+(0x2d0<<1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek (ifp, save1+(0x2d4<<1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, EOS M3, EOS M5 { fseek (ifp, save1+(0x56<<1), SEEK_SET); if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x80000394)) // EOS M5 { fseek(ifp, 18, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8,24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets (2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2,12); fseek (ifp, save1+(0xba<<1), SEEK_SET); Canon_WBCTpresets (2); // BCADT fseek (ifp, save1+(0x108<<1), SEEK_SET); // offset 264 short } int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x67<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xbc<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x0fb<<1), SEEK_SET); // offset 251 short int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } fseek (ifp, save1+(0x1e4<<1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x80<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0xd5<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x114<<1), SEEK_SET); // offset 276 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek (ifp, save1+(0x1fd<<1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek (ifp, save1+(0x2dd<<1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 case 1560: case 1592: case 1353: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek (ifp, save1+(0x85<<1), SEEK_SET); Canon_WBpresets(2,12); fseek (ifp, save1+(0x107<<1), SEEK_SET); Canon_WBCTpresets (0); // BCAT fseek (ifp, save1+(0x146<<1), SEEK_SET); // offset 326 shorts int bls=0; FORC4 bls+= (imgdata.makernotes.canon.ChannelBlackLevel[c]=get2()); imgdata.makernotes.canon.AverageBlackLevel = bls/4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek (ifp, save1+(0x231<<1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek (ifp, save1+(0x30f<<1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek (ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO (ushort c) { int code [] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value [] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code)/sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo (unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar*)malloc(MAX(len,128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) <<8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) <<8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) <<8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData+9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10*(table_buf[iLensData+9]>>2) * powf64(4, (table_buf[iLensData+9] & 0x03)-2); if (table_buf[iLensData+10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+10] & 0xf0) >>4)/4.0f); if (table_buf[iLensData+10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+10] & 0x0f) + 10)/4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData+3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData+3] & 0x07); if ((table_buf[iLensData+14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+14] & 0x7f) -1)/32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData+15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData+15] & 0x7f) -1)/32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures (unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333,"Mamiya"}, {329,"Universal"}, {330,"Hasselblad H1/H2"}, {332,"Contax"}, {336,"AFi"}, {327,"Mamiya"}, {324,"Universal"}, {325,"Hasselblad H1/H2"}, {326,"Contax"}, {335,"AFi"}, {340,"Mamiya"}, {337,"Universal"}, {338,"Hasselblad H1/H2"}, {339,"Contax"}, {323,"Mamiya"}, {320,"Universal"}, {322,"Hasselblad H1/H2"}, {321,"Contax"}, {334,"AFi"}, {369,"Universal"}, {370,"Mamiya"}, {371,"Hasselblad H1/H2"}, {372,"Contax"}, {373,"Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i=0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body,p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes (unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0]<<9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures (unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 360) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354) ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) // DSC-RX100M5 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2 (uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a)<<8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf,string) strncat(buf,string,LIM(sizeof(buf)-strbuflen(buf)-1,0,sizeof(buf))) void CLASS parseSonyLensFeatures (uchar a, uchar b) { ushort features; features = (((ushort)a)<<8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA" ); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf+1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf)-1); return; } #undef strnXcat void CLASS process_Sony_0x940c (uchar * buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]])<<8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2 (SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050 (uchar * buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f)*10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2 (SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures (SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if(len > 8 && pos+len > 2* fsize) continue; tag |= uptag << 16; if(len > 100*1024*1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes (tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len,ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp (model, "E-300", 5) && strncmp (model, "E-330", 5) && strncmp (model, "E-400", 5) && strncmp (model, "E-500", 5) && strncmp (model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || ( ((type == 3) || (type == 8)) && (len > 2)) || ( ((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp)<<16 | (unsigned long long)(fgetc(ifp), fgetc(ifp))<<8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens,len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment,len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7])) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 65535) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6])) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote (int base, int uptag) { unsigned offset=0, entries, tag, type, len, save, c; unsigned ver97=0, serial=0, i, wbi=0, wb[4]={0,0,0,0}; uchar buf97[324], ci, cj, ck; short morder, sorder=order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make,"Nokia",5)) return; fread (buf, 1, 10, ifp); if (!strncmp (buf,"KDK" ,3) || /* these aren't TIFF tables */ !strncmp (buf,"VER" ,3) || !strncmp (buf,"IIII",4) || !strncmp (buf,"MMMM",4)) return; if (!strncmp (buf,"KC" ,2) || /* Konica KD-400Z, KD-510Z */ !strncmp (buf,"MLY" ,3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i=ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp (buf,"Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek (ifp, offset-8, SEEK_CUR); } else if (!strcmp (buf,"OLYMPUS") || !strcmp (buf,"PENTAX ")) { base = ftell(ifp)-10; fseek (ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp (buf,"SONY",4) || !strcmp (buf,"Panasonic")) { goto nf; } else if (!strncmp (buf,"FUJIFILM",8)) { base = ftell(ifp)-10; nf: order = 0x4949; fseek (ifp, 2, SEEK_CUR); } else if (!strcmp (buf,"OLYMP") || !strcmp (buf,"LEICA") || !strcmp (buf,"Ricoh") || !strcmp (buf,"EPSON")) fseek (ifp, -2, SEEK_CUR); else if (!strcmp (buf,"AOC") || !strcmp (buf,"QVC")) fseek (ifp, -4, SEEK_CUR); else { fseek (ifp, -10, SEEK_CUR); if (!strncmp(make,"SAMSUNG",7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp)-8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek (ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek (ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp)-8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get (base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if(len > 8 && _pos+len > 2* fsize) continue; if (!strncmp(make, "Canon",5)) { if (tag == 0x000d && len < 256000) // camera info { CanonCameraInfo = (uchar*)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); lenCanonCameraInfo = len; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); if (unique_id == 0x03740000) unique_id = 0x80000374; // M3 if (unique_id == 0x03840000) unique_id = 0x80000384; // M10 if (unique_id == 0x03940000) unique_id = 0x80000394; // M5 setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo,lenCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes (tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1) < 18) if (i == 0) strncpy (imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial)-1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { strncpy (dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-14, 2); strncpy (mm, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-16, 2); strncpy (yy, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18, 2); year = (yy[0]-'0')*10 + (yy[1]-'0'); if (year <70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for ( int j = 0; ynum[j] && ynum[j+1] && sscanf(ynum+j, "%2x", &c); j += 2) ystr[j/2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy (model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf (tbuf,sizeof(tbuf), "%s %s %d:%s:%s", words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12, ystr, year, mm, dd); else snprintf (tbuf,sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0]+strnlen(words[0],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf (tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i]+strnlen(words[i],sizeof(imgdata.shootinginfo.InternalBodySerial)-1)-12); strncpy(imgdata.shootinginfo.InternalBodySerial,tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial)-1); } } } } else parseFujiMakernotes (tag, type); } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e?0:1; for (int j=0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c]= getreal(type); } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID>>2)<<8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp (model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp (model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if ( ((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5)) ) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote (base, 0x3400); } } else if (!strncmp(make, "NIKON",5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a*b)/(float)c; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a*b*(12/c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops /12.0f; } } else if (tag == 0x0093) { i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if(lenNikonLensData>0) { table_buf = (uchar*)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; unsigned long long OlyID; fread (sOlyID, MIN(len,7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type)/2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid [3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count=0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i=0; i<16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf (imgdata.shootinginfo.BodySerial, "%8s", buffer+8); buffer[8] = 0; sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf (imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf (imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf (imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4()+20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch(imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2()/10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4()/100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float) ((signed short) fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if(len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if (tag == 0x020d) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); } else if (tag == 0x020e) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); } else if (tag == 0x020f) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); } else if (tag == 0x0210) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); } else if (tag == 0x0211) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); } else if (tag == 0x0212) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); } else if (tag == 0x0213) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); } else if (tag == 0x0214) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if(nWB<=sizeof(imgdata.color.WBCT_Coeffs)/sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek (ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { fseek (ifp,2,SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); getc(ifp); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ (c >> 1)] = get2(); } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo [20]; fseek (ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if(get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV",2)))) { ushort lid; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free (table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free (table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360)) ) { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); break; default: // CameraInfo2 & 3 if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } free(table_buf); } else if ((tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp,0x49dc,SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2])<<8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid/8.0f-1.0f)/2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar*)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free (table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x940c && len <256000) { table_buf_0x940c = (uchar*)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar*)malloc(len); fread(table_buf, len, 1, ifp); if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); free(table_buf); } } fseek(ifp,_pos,SEEK_SET); #endif if (tag == 2 && strstr(make,"NIKON") && !iso_speed) iso_speed = (get2(),get2()); if (tag == 37 && strstr(make,"NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc,1,1,ifp); iso_speed = int(100.0 * powf64(2.0f,float(cc)/12.0-5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i=(get4(),get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i/32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i=(get2(),get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i/64.0); #endif if ((i=get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short) i/-32.0); wbi = (get2(),get2()); shot_order = (get2(),get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make,"KONICA",6)) { fseek (ifp, tag == 4 ? 140:160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets (model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make,"Canon",5)) fread (artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { for (c=i=2; (ushort) c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i+=4) < len-5) if (get4() == 257 && (i=len) && (c = (get4(),fgetc(ifp))) < 3) flip = "065"[c]-'0'; } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make,"Olympus",7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400102) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i=0; i<64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i=64; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400102) && (tag <= 0x2040010d)) { ushort CT; nWB = tag-0x20400102; switch (nWB) { case 0 : CT = 3000; tWB = LIBRAW_WBI_Tungsten; break; case 1 : CT = 3300; tWB = 0x100; break; case 2 : CT = 3600; tWB = 0x100; break; case 3 : CT = 3900; tWB = 0x100; break; case 4 : CT = 4000; tWB = LIBRAW_WBI_FL_W; break; case 5 : CT = 4300; tWB = 0x100; break; case 6 : CT = 4500; tWB = LIBRAW_WBI_FL_D; break; case 7 : CT = 4800; tWB = 0x100; break; case 8 : CT = 5300; tWB = LIBRAW_WBI_FineWeather; break; case 9 : CT = 6000; tWB = LIBRAW_WBI_Cloudy; break; case 10: CT = 6600; tWB = LIBRAW_WBI_FL_N; break; case 11: CT = 7500; tWB = LIBRAW_WBI_Shade; break; default: CT = 0; tWB = 0x100; } if (CT) { imgdata.color.WBCT_Coeffs[nWB][0] = CT; imgdata.color.WBCT_Coeffs[nWB][1] = get2(); imgdata.color.WBCT_Coeffs[nWB][3] = get2(); if (len == 4) { imgdata.color.WBCT_Coeffs[nWB][2] = get2(); imgdata.color.WBCT_Coeffs[nWB][4] = get2(); } } if (tWB != 0x100) FORC4 imgdata.color.WB_Coeffs[tWB][c] = imgdata.color.WBCT_Coeffs[nWB][c+1]; } if ((tag >= 0x20400113) && (tag <= 0x2040011e)) { nWB = tag-0x20400113; imgdata.color.WBCT_Coeffs[nWB][2] = imgdata.color.WBCT_Coeffs[nWB][4] = get2(); switch (nWB) { case 0: tWB = LIBRAW_WBI_Tungsten; break; case 4: tWB = LIBRAW_WBI_FL_W; break; case 6: tWB = LIBRAW_WBI_FL_D; break; case 8: tWB = LIBRAW_WBI_FineWeather; break; case 9: tWB = LIBRAW_WBI_Cloudy; break; case 10: tWB = LIBRAW_WBI_FL_N; break; case 11: tWB = LIBRAW_WBI_Shade; break; default: tWB = 0x100; } if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = imgdata.color.WBCT_Coeffs[nWB][2]; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } if (tag == 0x30000120) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); if (len == 2) { for (int i=0; i<256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if (tag == 0x30000121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); } if (tag == 0x30000122) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = get2(); } if (tag == 0x30000123) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); } if (tag == 0x30000124) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Sunset][2] = get2(); } if (tag == 0x30000130) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); } if (tag == 0x30000131) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); } if (tag == 0x30000132) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); } if (tag == 0x30000133) { imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); } if((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0]=getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1]=getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp,_pos2,SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make,"NIKON",5)) { fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek (ifp, 1248, SEEK_CUR); goto get2_256; } fread (buf, 1, 10, ifp); if (!strncmp(buf,"NRW ",4)) { fseek (ifp, strcmp(buf+4,"0100") ? 46:1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread (model, 64, 1, ifp); if (strstr(make,"PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model,"D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial*10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi]-'0' : 0; fseek (ifp, 8 + c*32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14-tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek (ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i=0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp)-'0'; switch (ver97) { case 100: fseek (ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek (ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek (ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek (ifp, 280, SEEK_CUR); fread (buf97, 324, 1, ifp); } } if (tag == 0xa1 && type == 7) { order = 0x4949; fseek (ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek (ifp, wbi*48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp)^fgetc(ifp)^fgetc(ifp)^fgetc(ifp); if ( (unsigned) (ver97-200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i=0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97-200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2 (buf97 + (i & -2) + c*2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if(tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(),get4()); if (tag == 0x200 && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make,"NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek (ifp, 22, SEEK_CUR); for (offset=22; offset+22 < len; offset += 22+i) { #ifdef LIBRAW_LIBRARY_BUILD if(loopc++>1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek (ifp, 14, SEEK_CUR); i = get4()-4; if (tag == 0x76a43207) flip = get2(); else fseek (ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek (ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek (ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek (ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if ((tag == 0x1011 && len == 9) || tag == 0x20400200) for (i=0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short) get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short) get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek (ifp, get4()+base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp,_pos3,SEEK_SET); } if ( ((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031)) && ((type == 7) || (type == 13)) && !strncasecmp(make,"Olympus",7) ) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp,_pos3,SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf,"OLYMP",5)) parse_thumb_note (base, 257, 258); if (tag == 0x2040) parse_makernote (base, 0x2040); if (tag == 0xb028) { fseek (ifp, get4()+base, SEEK_SET); parse_thumb_note (base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek (ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i+=18; i <= len; i+=10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if(!strncasecmp(make,"Samsung",7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i=0; i<11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c+1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1]>>1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } if (tag == 0xa025) imgdata.color.linear_max[0]= imgdata.color.linear_max[1]= imgdata.color.linear_max[2]= imgdata.color.linear_max[3]= get4() - SamsungKey[0]; if (tag == 0xa030 && len == 9) for (i=0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i=0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i*3+c])))/256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; next: fseek (ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp (int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i=19; i--; ) str[i] = fgetc(ifp); else fread (str, 19, 1, ifp); memset (&t, 0, sizeof t); if (sscanf (str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif (int base) { unsigned kodak, entries, tag, type, len, save, c; double expo,ape; kodak = !strncmp(make,"EASTMAN",7) && tiff_nifds < 3; entries = get2(); if(!strncmp(make,"Hasselblad",10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && savepos + len > fsize*2) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds-1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY",4) || !strncasecmp(make, "CANON",5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds-1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type))<256.0) && (!aperture)) aperture = powf64(2.0, ape/2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647",6))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_OV5647",9))) || ((!strncmp(make, "RaspberryPi",11)) && (!strncmp(model, "RP_imx219",9)))) { char mn_text[512]; char* pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos+7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos+7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy (ccms, pos, l); ccms[l] = '\0'; pos = strtok (ccms, ","); for (l=0; l<4; l++) { num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok (NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote (base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa=c=0; c < 8; c+=2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek (ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps (int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); if(len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29+tag/2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag/3*6+c] = get4(); break; case 6: FORC(2) gpsdata[18+c] = get4(); break; case 18: case 29: fgets ((char *) (gpsdata+14+tag/3), MIN(len,12), ifp); } fseek (ifp, save, SEEK_SET); } } void CLASS romm_coeff (float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ { { 2.034193, -0.727420, -0.306766 }, { -0.228811, 1.231729, -0.002922 }, { -0.008565, -0.153273, 1.161839 } }; int i, j, k; for (i=0; i < 3; i++) for (j=0; j < 3; j++) for (cmatrix[i][j] = k=0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos (int offset) { char data[40]; int skip, from, i, c, neut[4], planes=0, frot=0; static const char *mod[] = { "","DCB2","Volare","Cantare","CMost","Valeo 6","Valeo 11","Valeo 22", "Valeo 11p","Valeo 17","","Aptus 17","Aptus 22","Aptus 75","Aptus 65", "Aptus 54S","Aptus 65S","Aptus 75S","AFi 5","AFi 6","AFi 7", "AFi-II 7","Aptus-II 7","","Aptus-II 6","","","Aptus-II 10","Aptus-II 5", "","","","","Aptus-II 10R","Aptus-II 8","","Aptus-II 12","","AFi-II 12" }; float romm_cam[3][3]; fseek (ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread (data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data,"CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data,"back_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.BodySerial)); strcpy (imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data,"CaptProf_serial_number")) { char buffer [sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4,sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy (imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data,"JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data,"icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data,"ShootObj_back_type")) { fscanf (ifp, "%d", &i); if ((unsigned) i < sizeof mod / sizeof (*mod)) strcpy (model, mod[i]); } if (!strcmp(data,"icc_camera_to_tone_matrix")) { for (i=0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_color_matrix")) { for (i=0; i < 9; i++) fscanf (ifp, "%f", (float *)romm_cam + i); romm_coeff (romm_cam); } if (!strcmp(data,"CaptProf_number_of_planes")) fscanf (ifp, "%d", &planes); if (!strcmp(data,"CaptProf_raw_data_rotation")) fscanf (ifp, "%d", &flip); if (!strcmp(data,"CaptProf_mosaic_pattern")) FORC4 { fscanf (ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data,"ImgProf_rotation_angle")) { fscanf (ifp, "%d", &i); flip = i - flip; } if (!strcmp(data,"NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf (ifp, "%d", neut+c); FORC3 cam_mul[c] = (float) neut[0] / neut[c+1]; } if (!strcmp(data,"Rows_data")) load_flags = get4(); parse_mos (from); fseek (ifp, skip+from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip/90 + frot) & 3]; } void CLASS linear_table (unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts (curve, len); for (i=len; i < 0x10000; i++) curve[i] = curve[i-1]; maximum = curve[len<0x1000?0xfff:len-1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags (int wb, unsigned type) { float mul[3]={1,1,1}, num, mul2; int c; FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get (base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > 2*fsize) continue; if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag | 0x20000,type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f,get2()); wbi = -2; } if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial,len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } if (tag == 2120 + wbi || (wbi<0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num=getreal(type))==0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table (len); if (tag == 0x903) iso_speed = getreal(type); //if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd (int base) { unsigned entries, tag, type, len, save; int i, c, wbi=-2, wbtemp=6500; float mul[3]={1,1,1}, num; static const int wbtag[] = { 64037,64040,64039,64041,-1,-1,64042 }; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get (base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek (ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0,getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num=i=0; i < 4; i++) num += getreal(type) * pow (wbtemp/100.0, i); cam_mul[c] = 2048 / fMAX(1.0,(num * mul[c])); } if (tag == 2317) linear_table (len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned) wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type)+1) & -2; fseek (ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd (int base) { unsigned entries, tag, type, len, plen=16, save; int ifd, use_cm=0, cfa, i, j, c, ima_len=0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = { 0,1,2,3 }, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[]={ 1,1,1,1 }, asn[] = { 0,0,0,0 }, xyz[] = { 1,1,1 }; unsigned sony_curve[] = { 0,0,0,0,0,4095 }; unsigned *buf, sony_offset=0, sony_length=0, sony_key=0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j=0; j < 4; j++) for (i=0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get (base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if(len > 8 && len + savepos > fsize*2) continue; // skip tag pointing out of 2xfile if(callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data,tag|(pana_raw?0x30000:0),type,len,order,ifp); fseek(ifp,savepos,SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV",2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c+1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c+1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c+1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c+1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c+1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if(len==4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) pana_black[3]+=get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { imgdata.color.linear_max[tag-14] = get2(); if (tag == 15 ) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag-17)*2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw && len == 1 && type ==3) { pana_black[tag-28] = get2(); } else #endif { cblack[tag-28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag-36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if(pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt=0; cnt<nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek (ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24:80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread (desc, 512, 1, ifp); break; case 271: /* Make */ fgets (make, 64, ifp); break; case 272: /* Model */ fgets (model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_offsets[i]=get4()+base; fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4()+base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek (ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4*tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff (tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7]-'0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if(len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int*)calloc(len,sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for(int i=0; i< len; i++) tiff_ifd[ifd].strip_byte_counts[i]=get4(); fseek(ifp,sav,SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: FORC3 cam_mul[(4-c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets (software, 64, ifp); if (!strncmp(software,"Adobe",5) || !strncmp(software,"dcraw",5) || !strncmp(software,"UFRaw",5) || !strncmp(software,"Bibble",6) || !strcmp (software,"Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread (artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp): get4(); break; case 330: /* SubIFDs */ if (!strcmp(model,"DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4()+base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make,"Hasselblad",10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek (ifp, ftell(ifp)+4, SEEK_SET); fseek (ifp, get4()+base, SEEK_SET); parse_tiff_ifd (base); break; } #endif if(len > 1000) len=1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek (ifp, get4()+base, SEEK_SET); if (parse_tiff_ifd (base)) break; fseek (ifp, i+4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy (make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char*)malloc(xmplen = len+1); fread(xmpdata,len,1,ifp); xmpdata[len]=0; } break; #endif case 28688: FORC4 sony_curve[c+1] = get2() >> 2 & 0xfff; for (i=0; i < 5; i++) for (j = sony_curve[i]+1; j <= sony_curve[i+1]; j++) curve[j] = curve[j-1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta (ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP (cam_mul[i],cam_mul[i+1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i=0; i < 3; i++) { float num = 0.0; for (c=0; c<3; c++) { imgdata.color.ccm[i][c] = (float) ((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if(i>cblack[c]) i = cblack[c]; FORC4 cblack[c]-=i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, _("...Sony black: %u cblack: %u %u %u %u\n"),black, cblack[0],cblack[1],cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets (model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36) ((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if(len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if(len > 0) { if ((plen=len) > 16) plen = 16; fread (cfa_pat, 1, plen, ifp); for (colors=cfa=i=0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy (cfa_pc,"\003\004\005",3); /* CMY */ if (cfa == 072) memcpy (cfa_pc,"\005\003\004\001",4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek (ifp, get4()+base, SEEK_SET); parse_kodak_ifd (base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread (software, 1, 7, ifp); if (strncmp(software,"MATRIX",6)) break; colors = 4; for (raw_color = i=0; i < 3; i++) { FORC4 fscanf (ifp, "%f", &rgb_cam[i][c^1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1,num); } break; case 34310: /* Leaf metadata */ parse_mos (ftell(ifp)); case 34303: strcpy (make, "Leaf"); break; case 34665: /* EXIF tag */ fseek (ifp, get4()+base, SEEK_SET); parse_exif (base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i=0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy (make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek (ifp, 38, SEEK_CUR); case 46274: fseek (ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952 ) { height = 5412; width = 7216; left_margin = 7; filters=0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek (ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek (ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width,height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf (model, "Ixpress %d-Mp", height*width/1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *) malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread (cbuf, 1, len, ifp); #else if(fread (cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len-1] = 0; for (cp = cbuf-1; cp && cp < cbuf+len; cp = strchr(cp,'\n')) if (!strncmp (++cp,"Neutral ",8)) sscanf (cp+8, "%f %f %f", cam_mul, cam_mul+1, cam_mul+2); free (cbuf); break; case 50458: if (!make[0]) strcpy (make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag=1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek (ifp, j+(get2(),get4()), SEEK_SET); parse_tiff_ifd (j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy (make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel)-1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets (make, 64, ifp); #else strncpy (make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make,' '))) { strcpy(model,cp+1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread (cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i=16; i--; ) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ linear_table (len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof (cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_cblack[4]= imgdata.color.dng_levels.dng_cblack[5]= #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00c: { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && libraw_internal_data.unpacker_data.lenRAFData>3 && libraw_internal_data.unpacker_data.lenRAFData < 10240000) { long long f_save = ftell(ifp); int fj, found = 0; ushort *rafdata = (ushort*) malloc (sizeof(ushort)*libraw_internal_data.unpacker_data.lenRAFData); fseek (ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread (rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); for (int fi=0; fi<(libraw_internal_data.unpacker_data.lenRAFData-3); fi++) { if ((fwb[0]==rafdata[fi]) && (fwb[1]==rafdata[fi+1]) && (fwb[2]==rafdata[fi+2])) { if (rafdata[fi-15] != fwb[0]) continue; fi = fi - 15; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][3] = rafdata[fi]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][0] = rafdata[fi+1]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][2] = rafdata[fi+2]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = rafdata[fi+3]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = rafdata[fi+4]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = rafdata[fi+5]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = rafdata[fi+6]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = rafdata[fi+7]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = rafdata[fi+8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = rafdata[fi+9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][0] = rafdata[fi+10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][2] = rafdata[fi+11]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = rafdata[fi+12]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = rafdata[fi+13]; imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = rafdata[fi+14]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = rafdata[fi+15]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = rafdata[fi+16]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = rafdata[fi+17]; fi += 111; for (fj = fi; fj<(fi+15); fj+=3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { int FujiCCT_K [31] = {2500,2550,2650,2700,2800,2850,2950,3000,3100,3200,3300,3400,3600,3700,3800,4000,4200,4300,4500,4800,5000,5300,5600,5900,6300,6700,7100,7700,8300,9100,10000}; fj = fj - 93; for (int iCCT=0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT*3+1+fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT*3+fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT*3+2+fj]; } } free (rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel,len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len),64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { for(i=0; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_cblack[i]= cblack[i]= getreal(type)+0.5; imgdata.color.dng_levels.dng_black= black = 0; } else #endif if((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black= #endif black = getreal(type); } else if(cblack[4] * cblack[5] <= len) { FORC (cblack[4] * cblack[5]) cblack[6+c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if(tag == 50714) { FORC (cblack[4] * cblack[5]) imgdata.color.dng_levels.dng_cblack[6+c]= cblack[6+c]; imgdata.color.dng_levels.dng_black=0; FORC4 imgdata.color.dng_levels.dng_cblack[c]= 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num=i=0; i < len && i < 65536; i++) num += getreal(type); black += num/len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_black += num/len + 0.5; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.dng_whitelevel[0]= #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if(tiff_ifd[ifd].samples > 1 ) // Linear DNG case for(i=1; i < colors && i < 4 && i < len; i++) imgdata.color.dng_levels.dng_whitelevel[i]=getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if(pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50778: imgdata.color.dng_color[0].illuminant = get2(); break; case 50779: imgdata.color.dng_color[1].illuminant = get2(); break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721?0:1; #endif FORCC for (j=0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].colormatrix[c][j]= #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714?0:1; #endif for (j=0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[i].forwardmatrix[j][c]= #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723?0:1; #endif for (i=0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_color[j].calibration[i][c]= #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ FORCC{ #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.dng_levels.analogbalance[c]= #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta (j = get4()+base); fseek (ifp, j, SEEK_SET); parse_tiff_ifd (base); break; case 50752: read_shorts (cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i=0; i < len && i < 32; i++) ((int*)mask)[i] = getint(type); black = 0; break; case 51009: /* OpcodeList2 */ meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek (ifp, 16, SEEK_CUR); data_offset = get4(); fseek (ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets (model2, 64, ifp); } fseek (ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *) malloc(sony_length))) { fseek (ifp, sony_offset, SEEK_SET); fread (buf, sony_length, 1, ifp); sony_decrypt (buf, sony_length/4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite (buf, sony_length, 1, ifp); fseek (ifp, 0, SEEK_SET); parse_tiff_ifd (-sony_offset); fclose (ifp); } ifp = sfp; #else if( !ifp->tempbuffer_open(buf,sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free (buf); } for (i=0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i=0; i < 3; i++) for (cam_xyz[c][i]=j=0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff (cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff (int base) { int doff; fseek (ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek (ifp, doff+base, SEEK_SET); if (parse_tiff_ifd (base)) break; } return 1; } void CLASS apply_tiff() { int max_samp=0, ties=0, os, ns, raw=-1, thm=-1, i; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { if((unsigned)jh.bits<17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i=tiff_nifds; i--; ) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i=0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width*raw_height; ns = tiff_ifd[i].t_width*tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width ) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i=tiff_nifds; i--; ) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width*raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes*8 != raw_width*raw_height*tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if(!strncasecmp(make,"Sony",4) && tiff_ifd[raw].bytes == raw_width*raw_height*2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if(!strncasecmp(make,"Nikon",5) && !strncmp(software,"Nikon Scan",10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*2 == raw_width*raw_height*3) load_flags = 24; if (tiff_ifd[raw].bytes*5 == raw_width*raw_height*8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make,"OLYMPUS",7) && tiff_ifd[raw].bytes*7 > raw_width*raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width+9)/10*16*raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width*raw_height*3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); memset (cblack, 0, sizeof cblack); filters = 0; } else if (raw_width*raw_height*2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if(raw_width*raw_height*3 == tiff_ifd[raw].bytes*2) { load_raw = &CLASS packed_load_raw; load_flags=80; } else if(tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for(int i = 0; i < tiff_ifd[raw].strip_byte_counts_count-1; i++) // all but last if(tiff_ifd[raw].strip_byte_counts[i]*2 != tiff_ifd[raw].rows_per_strip*raw_width*3) { fit = 0; break; } if(fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if ( ((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make,"Phase",5) && !strcasestr(make,"Kodak") && !strstr(model2,"DEBUG RAW"))) && strncmp(software,"Nikon Scan",10)) is_raw = 0; for (i=0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps>0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps)+1) > thumb_width * thumb_height / (SQR(thumb_misc)+1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make,"Imacon",6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta (int base) { int save, tag, len, offset, high=0, wide=0, i, c; short sorder=order; fseek (ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp)-'M' || fgetc(ifp)-'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save=ftell(ifp)) < offset) { for (tag=i=0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek (ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model,"DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model,"DiMAGE A200") ? 0:3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff (ftell(ifp)); data_offset = offset; } fseek (ifp, save+len+8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save=ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if(ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length()-3,3,L"JPG"); if(!ifp->subfile_open(rawfile.c_str())) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif if(!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; return; } #endif ext = strrchr (ifname, '.'); file = strrchr (ifname, '/'); if (!file) file = strrchr (ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname-1; #else if (!file) file = (char*)ifname-1; #endif file++; if (!ext || strlen(ext) != 4 || ext-file != 8) return; jname = (char *) malloc (strlen(ifname) + 1); merror (jname, "parse_external_jpeg()"); strcpy (jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp (ext, ".jpg")) { strcpy (jext, isupper(ext[1]) ? ".JPG":".jpg"); if (isdigit(*file)) { memcpy (jfile, file+4, 4); memcpy (jfile+4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp (jname, ifname)) { if ((ifp = fopen (jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Reading metadata from %s ...\n"), jname); #endif parse_tiff (12); thumb_offset = 0; is_raw = 1; fclose (ifp); } } #else if (strcmp (jname, ifname)) { if(!ifp->subfile_open(jname)) { parse_tiff (12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA ; #endif #ifdef DCRAW_VERBOSE fprintf (stderr,_("Failed to read metadata from %s\n"), jname); #endif } free (jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = { 0x410, 0x45f3 }; int i, bpp, row, col, vbits=0; unsigned long bitbuf=0; if ((get2(),get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i=row=0; row < 8; row++) for (col=0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff (int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi=-1; ushort key[] = { 0x410, 0x45f3 }; fseek (ifp, offset+length-4, SEEK_SET); tboff = get4() + offset; fseek (ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek (ifp, offset+get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff (ftell(ifp), len, depth+1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff (ftell(ifp), len, depth+1); #endif if (type == 0x0810) fread (artist, 64, 1, ifp); if (type == 0x080a) { fread (make, 64, 1, ifp); fseek (ifp, strbuflen(make) - 63, SEEK_CUR); fread (model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(),get4()))); aperture = powf64(2.0f, int_to_float(get4())/2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(),get2()) + get2())/32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(),get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(),(short)get2())/64.0); #endif shutter = powf64(2.0,-((short)get2())/32.0); wbi = (get2(),get2()); if (wbi > 17) wbi = 0; fseek (ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2()/10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek (ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek (ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek (ifp, (0x5<<1), SEEK_CUR); Canon_WBpresets(0,0); fseek(ifp,o,SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp,o,SEEK_SET); } if (type == 0x580b) { if (strcmp(model,"Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len>>16, len&0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek (ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model,"Pro1") ? "012346000000000000":"01345:000000006008")[LIM(0,wbi,17)]-'0'+ 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0,wbi,17)]-'0'; key[0] = key[1] = 0; } fseek (ifp, 78 + c*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0,wbi,9)]-'0'; fseek (ifp, 2 + wbi*8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi>=0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(),get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if(imgdata.lens.makernotes.CanonFocalUnits>1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime (gmtime (&timestamp)); #endif fseek (ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek (ifp, 0, SEEK_SET); memset (&t, 0, sizeof t); do { fgets (line, 128, ifp); if ((val = strchr(line,'='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line,"DAT")) sscanf (val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line,"TIM")) sscanf (val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line,"HDR")) thumb_offset = atoi(val); if (!strcmp(line,"X ")) raw_width = atoi(val); if (!strcmp(line,"Y ")) raw_height = atoi(val); if (!strcmp(line,"TX ")) thumb_width = atoi(val); if (!strcmp(line,"TY ")) thumb_height = atoi(val); } while (strncmp(line,"EOHD",4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy (make, "Rollei"); strcpy (model,"d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek (ifp, 4, SEEK_SET); entries = get4(); fseek (ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread (str, 8, 1, ifp); if (!strcmp(str,"META")) meta_offset = off; if (!strcmp(str,"THUMB")) thumb_offset = off; if (!strcmp(str,"RAW0")) data_offset = off; } fseek (ifp, meta_offset+20, SEEK_SET); fread (make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make,' '))) { strcpy (model, cp+1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(),get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one (int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset (&ph1, 0, sizeof ph1); fseek (ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek (ifp, get4()+base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, base+data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data)/2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type)/2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data)/2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3]-'0'; break; case 0x106: for (i=0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i]= #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff (romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data+base; break; case 0x110: meta_offset = data+base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data+base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data+base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data+base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i=0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread (model, 1, 63, ifp); if ((cp = strstr(model," camera"))) *cp = 0; } fseek (ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek (ifp, meta_offset, SEEK_SET); order = get2(); fseek (ifp, 6, SEEK_CUR); fseek (ifp, meta_offset+get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek (ifp, meta_offset+data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek (ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy (make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy (model,"LightPhase"); break; case 2682: strcpy (model,"H 10"); break; case 4128: strcpy (model,"H 20"); break; case 5488: strcpy (model,"H 25"); break; } } void CLASS parse_fuji (int offset) { unsigned entries, tag, len, save, c; fseek (ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); } // IB start #ifdef LIBRAW_LIBRARY_BUILD else if (tag == 0x9650) { short a = (short)get2(); float b =fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } #endif // IB end else if (tag == 0xc000) { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len>>1); #endif order = c; } fseek (ifp, save+len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg (int offset) { int len, save, hlen, mark; fseek (ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save+hlen) >= 0 && (save+hlen)<=ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (save+hlen, len-hlen, 0); } if (parse_tiff (save+6)) apply_tiff(); fseek (ifp, save+len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = { "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec" }; struct tm t; order = 0x4949; fread (tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag,"RIFF",4) || !memcmp(tag,"LIST",4)) { int maxloop = 1000; get4(); while (ftell(ifp)+7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag,"nctg",4)) { while (ftell(ifp)+7 < end) { i = get2(); size = get2(); if ((i+1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek (ifp, size, SEEK_CUR); } } else if (!memcmp(tag,"IDIT",4) && size < 64) { fread (date, 64, 1, ifp); date[size] = 0; memset (&t, 0, sizeof t); if (sscanf (date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i=0; i < 12 && strcasecmp(mon[i],month); i++); t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek (ifp, size, SEEK_CUR); } void CLASS parse_qt (int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp)+7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread (tag, 4, 1, ifp); if (!memcmp(tag,"moov",4) || !memcmp(tag,"udta",4) || !memcmp(tag,"CNTH",4)) parse_qt (save+size); if (!memcmp(tag,"CNDA",4)) parse_jpeg (ftell(ifp)); fseek (ifp, save+size, SEEK_SET); } } void CLASS parse_smal (int offset, int fsize) { int ver; fseek (ifp, offset+2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek (ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy (make, "SMaL"); sprintf (model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek (ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek (ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek (ifp, off_head+4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(),get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek (ifp, off_setup+792, SEEK_SET); strcpy (make, "CINE"); sprintf (model, "%d", get4()); fseek (ifp, 12, SEEK_CUR); switch ((i=get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek (ifp, 72, SEEK_CUR); switch ((get4()+3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek (ifp, 668, SEEK_CUR); shutter = get4()/1000000000.0; fseek (ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek (ifp, shot_select*8, SEEK_CUR); data_offset = (INT64) get4() + 8; data_offset += (INT64) get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek (ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek (ifp, 0, SEEK_END); fseek (ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek (ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek (ifp, len-8, SEEK_CUR); } } else { rdvo = get4(); fseek (ifp, 12, SEEK_CUR); is_raw = get4(); fseeko (ifp, rdvo+8 + shot_select*4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff (const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD ,int internal_only #endif ) { static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, { 9805,-2689,-1312,-5803,13064,3068,-2438,3075,8775 } }, { "Canon EOS D60", 0, 0xfa0, { 6188,-1341,-890,-7168,14489,2937,-2640,3228,8483 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446, -366, -864, -4436, 12204, 2513, -952, 2496, 6348 }}, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D", 0, 0x3c82, { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, { 8197,-2000,-1118,-6714,14335,2592,-2536,3178,8266 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939, -1016, -866, -4428, 12473, 2177, -1175, 2178, 6162 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M5", 0, 0, /* Adobe */ { 8532, -701, -1167, -4095, 11879, 2508, -797, 2424, 7010 }}, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, { 4374,3631,-1743,-7520,15212,2472,-2892,3632,8161 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, { 7596,-978,967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, { 14130,-8071,127,2199,6528,1551,3402,-1721,4960 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, { -4778,9467,2172,4743,-1141,4344,-5146,9908,6077,-1566,11051,557 } }, { "Canon PowerShot G2", 0, 0, { 9087,-2693,-1049,-6715,14382,2537,-2291,2819,7790 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, { 9212,-2781,-1073,-6573,14189,2605,-2300,2844,7664 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, { 9757,-2872,-933,-5972,13861,2301,-1622,2328,7212 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, { -4155,9818,1529,3939,-25,4522,-5521,9870,6610,-2238,10873,1342 } }, { "Canon PowerShot Pro90", 0, 0, { -4963,9896,2235,4642,-987,4294,-5162,10011,5859,-1770,11230,577 } }, { "Canon PowerShot S30", 0, 0, { 10566,-3652,-1129,-6552,14662,2006,-2197,2581,7670 } }, { "Canon PowerShot S40", 0, 0, { 8510,-2487,-940,-6869,14231,2900,-2318,2829,9013 } }, { "Canon PowerShot S45", 0, 0, { 8163,-2333,-955,-6682,14174,2751,-2077,2597,8041 } }, { "Canon PowerShot S50", 0, 0, { 8882,-2571,-863,-6348,14234,2288,-1516,2172,6569 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, { 11044,-3888,-1120,-7248,15168,2208,-1531,2277,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, { 12492,-4690,-1402,-7033,15423,1647,-1507,2111,7697 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 12066,-5927,-367,-1969,9878,1503,-721,2034,5453 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 13193,-6685,-425,-2229,10458,1534,-878,1763,5217 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T10", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "GITUP GIT2", 3200, 0, {8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354}}, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad CFV", 0, 0, /* Adobe */ { 8519, -3260, -280, -5081, 13459, 1738, -1449, 2960, 7809, } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad H-39MP",0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H3D-50", 0, 0, /* Adobe */ { 3857,452, -46, -6008, 14477, 1596, -2627, 4481, 5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, /* Adobe */ { 9662, -684, -279, -4903, 12293, 2950, -344, 1669, 6024 } }, { "Hasselblad H5D-50c",0, 0, /* Adobe */ { 4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 } }, { "Hasselblad H5D-50",0, 0, /* Adobe */ { 5656, -659, -346, -3923, 12306, 1791, -1602, 3509, 5442 } }, { "Hasselblad X1D",0, 0, /* Adobe */ {4932, -835, 141, -4878, 11868, 3437, -1138, 1961, 7067 }}, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf CMost", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035, 435, -962, -6001, 13872, 2320, -1159, 3065, 5434 } }, { "Leaf Credo 50", 0, 0, { 3984, 0, 0, 0, 10000, 0, 0, 0, 7666 } }, { "Leaf Credo 60", 0, 0, { 8035, 435, -962, -6001, 13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294, 686, -712, -5435, 13417, 2211, -1006, 2435, 5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, { 8983,-2942,-963,-6556,14476,2237,-2426,2887,8014 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, { 11368,-3894,-1242,-6521,14358,2339,-2475,3056,7285 } }, { "Minolta DiMAGE 7", 0, 0xf7d, { 9144,-2777,-998,-6676,14556,2281,-2470,3019,7744 } }, { "Minolta DiMAGE A1", 0, 0xf8b, { 9274,-2547,-1167,-8220,16323,1943,-2273,2720,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, { 7577,-2166,-926,-7454,15592,1934,-2377,2808,8606 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5710,-901,-615,-8594,16617,2024,-2975,4120,6830 } }, { "Nikon D2X", 0, 0, { 10231,-2769,-1255,-8301,15900,2552,-797,680,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, { 10426,-4005,-444,-3565,11764,1403,-1206,2266,6549 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D810A", 0, 0, { 11973, -5685, -888, -1965, 10326, 1901, -115, 1123, 7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5400", 0, 0, { 9349,-2987,-1001,-7919,15766,2266,-2098,2680,6839 } }, { "Nikon E5700", 0, 0, { -5368,11478,2368,5537,-113,3148,-4969,10021,5782,778,9028,211 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835} }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, { 8144,-2671,-473,-1740,9834,1601,-58,1971,4296 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, { 10508,-3124,-1273,-6079,14294,1901,-1653,2306,6237 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, { 12745,-4500,-1416,-6062,14542,1580,-1934,2256,6603 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, { 13173,-4732,-1499,-5807,14036,1895,-2045,2452,7142 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, /* Adobe */ { 8380, -2630, -639, -2887, 10725, 2496, -627, 1427, 5438 }}, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, { 11976,-5518,-545,-1419,10472,846,-475,1766,4524 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax K10D", 0, 0, { 9566,-2863,-803,-7170,15172,2112,-818,803,9705 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-m", 0, 0, { 11057,-3604,-1155,-5152,13046,2329,-282,375,8104 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, { 8566,-2746,-1201,-3612,12204,1550,-893,1680,6264 } }, { "Pentax K-30", 0, 0, { 8710,-2632,-1167,-3995,12301,1881,-981,1719,6535 } }, { "Pentax K-3 II", 0, 0, { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, {8766, -3149, -747, -3976, 11943, 2292, -517, 1259, 5552 }}, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax MX-1", 0, 0, { 8804,-2523,-1238,-2423,11627,860,-682,1774,4753 } }, { "Pentax Q10", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* Adobe */ { 9702, -3060, -1254, -3685, 12133, 1721, -1086, 2010, 6971}}, { "Panasonic DMC-CM10", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770, -3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, // same as FZ300 { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790, -2736, -755, -3452, 11870, 1769, -628, 1647, 4898 }}, /* Adobe*/ { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000,DMC-FZ2500,FZH1 */ { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ2500", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZH1", -15, 0, { 7386, -2443, -743, -3437, 11864, 1757, -608, 1660, 4766 }}, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica X", 0, 0, /* X and X-U, both (Typ 113) */ { 7712,-2059,-653,-3882,11494,2726,-710,1332,5958 } }, { "Leica Q (Typ 116)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830 } }, { "Leica M (Typ 262)", 0, 0, { 6653,-1486,-611,-4221,13303,929,-881,2416,7226 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ250",0, 0, { 4396,-153,-249,-5267,12249,2657,-1397,2323,6014 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P 30", 0, 0, { 4516,-245,-37,-7020,14976,2173,-3206,4671,7087 } }, { "Phase One P 45", 0, 0, { 5053,-24,-117,-5684,14076,1702,-2619,4492,5849 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Samsung EK-GN120", 0, 0, /* Adobe; Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, /* same as NX3000 */ { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* NX30, NX300, NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* NX20, NX200, NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* also NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX-1", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp, same as sd Quattro */ { "Sigma sd Quattro", 2047, 0, {1295,108,-311, 256,828,-65,-28,750,254}}, /* temp */ { "Sigma SD9", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD10", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD14", 15, 16383, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, { "Sigma SD15", 15, 4095, /* LibRaw */ { 14082,-2201,-1056,-5243,14788,167,-121,196,8881 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, /* Adobe */ {6596, -2079, -562, -4782, 13016, 1933, -970, 1581, 5181 }}, { "Sony DSC-RX100M", -800, 0, /* M2 and M3 and M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Sony DSC-RX10",0, 0, /* And M2/M3 too */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, { 8195,-2800,-422,-4261,12273,1709,-1505,2400,5624 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, /* Adobe */ { 6660, -1918, -471, -4613, 12398, 2485, -649, 1433, 6447}}, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, /* Adobe */ { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, /* Adobe */ { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; double cam_xyz[4][3]; char name[130]; int i, j; if(colors>4 || colors < 1) return; int bl4=(cblack[0]+cblack[1]+cblack[2]+cblack[3])/4,bl64=0; if(cblack[4]*cblack[5]>0) { for (unsigned c = 0; c < 4096 && c < cblack[4]*cblack[5]; c++) bl64+=cblack[c+6]; bl64 /= cblack[4]*cblack[5]; } int rblack = black+bl4+bl64; sprintf (name, "%s %s", t_make, t_model); for (i=0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if(!dng_version) { if (table[i].t_black>0) { black = (ushort) table[i].t_black; memset(cblack,0,sizeof(cblack)); } else if(table[i].t_black <0 && rblack == 0 ) { black = (ushort) (-table[i].t_black); memset(cblack,0,sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort) table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j=0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if(internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double*)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if(!internal_only) #endif cam_xyz_coeff (rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff (int index) { static const float table[][12] = { /* index 0 -- all Foveon cameras */ { 1.4032,-0.2231,-0.1016,-0.5263,1.4816,0.017,-0.0112,0.0183,0.9113 }, /* index 1 -- Kodak DC20 and DC25 */ { 2.25,0.75,-1.75,-0.25,-0.25,0.75,0.75,-0.25,-0.25,-1.75,0.75,2.25 }, /* index 2 -- Logitech Fotoman Pixtura */ { 1.893,-0.418,-0.476,-0.495,1.773,-0.278,-1.017,-0.655,2.672 }, /* index 3 -- Nikon E880, E900, and E990 */ { -1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705 } }; int i, c; for (raw_color = i=0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i*colors+c]; } short CLASS guess_byte_order (int words) { uchar test[4][2]; int t=2, msb; double diff, sum[2] = {0,0}; fread (test[0], 2, 2, ifp); for (words-=2; words--; ) { fread (test[t], 2, 1, ifp); for (msb=0; msb < 2; msb++) { diff = (test[t^2][msb] << 8 | test[t^2][!msb]) - (test[t ][msb] << 8 | test[t ][!msb]); sum[msb] += diff*diff; } t = (t+1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green (int bps, int bite, int off0, int off1) { UINT64 bitbuf=0; int vbits, col, i, c; ushort img[2][2064]; double sum[]={0,0}; FORC(2) { fseek (ifp, c ? off1:off0, SEEK_SET); for (vbits=col=0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i=0; i < bite; i+=8) bitbuf |= (unsigned) (fgetc(ifp) << i); } img[c][col] = bitbuf << (64-bps-vbits) >> (64-bps); } } FORC(width-1) { sum[ c & 1] += ABS(img[0][c]-img[1][c+1]); sum[~c & 1] += ABS(img[1][c]-img[0][c+1]); } return 100 * log(sum[0]/sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if(len<1) return; // not needed, b/c sizeof of make/model is 64 string[len-1]=0; if(len<3) return; // also not needed len = strnlen(string,len-1); for(int i=len-1; i>=0; i--) { if(isspace(string[i])) string[i]=0; else break; } } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { { 3130, 1743, 4, 0, -6, 0 }, { 3130, 2055, 4, 0, -6, 0 }, { 3130, 2319, 4, 0, -6, 0 }, { 3170, 2103, 18, 0,-42, 20 }, { 3170, 2367, 18, 13,-42,-21 }, { 3177, 2367, 0, 0, -1, 0 }, { 3304, 2458, 0, 0, -1, 0 }, { 3330, 2463, 9, 0, -5, 0 }, { 3330, 2479, 9, 0,-17, 4 }, { 3370, 1899, 15, 0,-44, 20 }, { 3370, 2235, 15, 0,-44, 20 }, { 3370, 2511, 15, 10,-44,-21 }, { 3690, 2751, 3, 0, -8, -3 }, { 3710, 2751, 0, 0, -3, 0 }, { 3724, 2450, 0, 0, 0, -2 }, { 3770, 2487, 17, 0,-44, 19 }, { 3770, 2799, 17, 15,-44,-19 }, { 3880, 2170, 6, 0, -6, 0 }, { 4060, 3018, 0, 0, 0, -2 }, { 4290, 2391, 3, 0, -8, -1 }, { 4330, 2439, 17, 15,-44,-19 }, { 4508, 2962, 0, 0, -3, -4 }, { 4508, 3330, 0, 0, -3, -6 }, }; static const ushort canon[][11] = { { 1944, 1416, 0, 0, 48, 0 }, { 2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25 }, { 2224, 1456, 48, 6, 0, 2 }, { 2376, 1728, 12, 6, 52, 2 }, { 2672, 1968, 12, 6, 44, 2 }, { 3152, 2068, 64, 12, 0, 0, 16 }, { 3160, 2344, 44, 12, 4, 4 }, { 3344, 2484, 4, 6, 52, 6 }, { 3516, 2328, 42, 14, 0, 0 }, { 3596, 2360, 74, 12, 0, 0 }, { 3744, 2784, 52, 12, 8, 12 }, { 3944, 2622, 30, 18, 6, 2 }, { 3948, 2622, 42, 18, 0, 2 }, { 3984, 2622, 76, 20, 0, 2, 14 }, { 4104, 3048, 48, 12, 24, 12 }, { 4116, 2178, 4, 2, 0, 0 }, { 4152, 2772, 192, 12, 0, 0 }, { 4160, 3124, 104, 11, 8, 65 }, { 4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49 }, { 4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49 }, { 4312, 2876, 22, 18, 0, 2 }, { 4352, 2874, 62, 18, 0, 0 }, { 4476, 2954, 90, 34, 0, 0 }, { 4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49 }, { 4480, 3366, 80, 50, 0, 0 }, { 4496, 3366, 80, 50, 12, 0 }, { 4768, 3516, 96, 16, 0, 0, 0, 16 }, { 4832, 3204, 62, 26, 0, 0 }, { 4832, 3228, 62, 51, 0, 0 }, { 5108, 3349, 98, 13, 0, 0 }, { 5120, 3318, 142, 45, 62, 0 }, { 5280, 3528, 72, 52, 0, 0 }, /* EOS M */ { 5344, 3516, 142, 51, 0, 0 }, { 5344, 3584, 126,100, 0, 2 }, { 5360, 3516, 158, 51, 0, 0 }, { 5568, 3708, 72, 38, 0, 0 }, { 5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49 }, { 5712, 3774, 62, 20, 10, 2 }, { 5792, 3804, 158, 51, 0, 0 }, { 5920, 3950, 122, 80, 2, 0 }, { 6096, 4056, 72, 34, 0, 0 }, /* EOS M3 */ { 6288, 4056, 266, 36, 0, 0 }, /* EOS 80D */ { 6880, 4544, 136, 42, 0, 0 }, /* EOS 5D4 */ { 8896, 5920, 160, 64, 0, 0 }, }; static const struct { ushort id; char t_model[20]; } unique[] = { { 0x001, "EOS-1D" }, { 0x167, "EOS-1DS" }, { 0x168, "EOS 10D" }, { 0x169, "EOS-1D Mark III" }, { 0x170, "EOS 300D" }, { 0x174, "EOS-1D Mark II" }, { 0x175, "EOS 20D" }, { 0x176, "EOS 450D" }, { 0x188, "EOS-1Ds Mark II" }, { 0x189, "EOS 350D" }, { 0x190, "EOS 40D" }, { 0x213, "EOS 5D" }, { 0x215, "EOS-1Ds Mark III" }, { 0x218, "EOS 5D Mark II" }, { 0x232, "EOS-1D Mark II N" }, { 0x234, "EOS 30D" }, { 0x236, "EOS 400D" }, { 0x250, "EOS 7D" }, { 0x252, "EOS 500D" }, { 0x254, "EOS 1000D" }, { 0x261, "EOS 50D" }, { 0x269, "EOS-1D X" }, { 0x270, "EOS 550D" }, { 0x281, "EOS-1D Mark IV" }, { 0x285, "EOS 5D Mark III" }, { 0x286, "EOS 600D" }, { 0x287, "EOS 60D" }, { 0x288, "EOS 1100D" }, { 0x289, "EOS 7D Mark II" }, { 0x301, "EOS 650D" }, { 0x302, "EOS 6D" }, { 0x324, "EOS-1D C" }, { 0x325, "EOS 70D" }, { 0x326, "EOS 700D" }, { 0x327, "EOS 1200D" }, { 0x328, "EOS-1D X Mark II" }, { 0x331, "EOS M" }, { 0x335, "EOS M2" }, { 0x374, "EOS M3"}, /* temp */ { 0x384, "EOS M10"}, /* temp */ { 0x394, "EOS M5"}, /* temp */ { 0x346, "EOS 100D" }, { 0x347, "EOS 760D" }, { 0x349, "EOS 5D Mark IV" }, { 0x350, "EOS 80D"}, { 0x382, "EOS 5DS" }, { 0x393, "EOS 750D" }, { 0x401, "EOS 5DS R" }, { 0x404, "EOS 1300D" }, }, sonique[] = { { 0x002, "DSC-R1" }, { 0x100, "DSLR-A100" }, { 0x101, "DSLR-A900" }, { 0x102, "DSLR-A700" }, { 0x103, "DSLR-A200" }, { 0x104, "DSLR-A350" }, { 0x105, "DSLR-A300" }, { 0x106, "DSLR-A900" }, { 0x107, "DSLR-A380" }, { 0x108, "DSLR-A330" }, { 0x109, "DSLR-A230" }, { 0x10a, "DSLR-A290" }, { 0x10d, "DSLR-A850" }, { 0x10e, "DSLR-A850" }, { 0x111, "DSLR-A550" }, { 0x112, "DSLR-A500" }, { 0x113, "DSLR-A450" }, { 0x116, "NEX-5" }, { 0x117, "NEX-3" }, { 0x118, "SLT-A33" }, { 0x119, "SLT-A55V" }, { 0x11a, "DSLR-A560" }, { 0x11b, "DSLR-A580" }, { 0x11c, "NEX-C3" }, { 0x11d, "SLT-A35" }, { 0x11e, "SLT-A65V" }, { 0x11f, "SLT-A77V" }, { 0x120, "NEX-5N" }, { 0x121, "NEX-7" }, { 0x122, "NEX-VG20E"}, { 0x123, "SLT-A37" }, { 0x124, "SLT-A57" }, { 0x125, "NEX-F3" }, { 0x126, "SLT-A99V" }, { 0x127, "NEX-6" }, { 0x128, "NEX-5R" }, { 0x129, "DSC-RX100" }, { 0x12a, "DSC-RX1" }, { 0x12b, "NEX-VG900" }, { 0x12c, "NEX-VG30E" }, { 0x12e, "ILCE-3000" }, { 0x12f, "SLT-A58" }, { 0x131, "NEX-3N" }, { 0x132, "ILCE-7" }, { 0x133, "NEX-5T" }, { 0x134, "DSC-RX100M2" }, { 0x135, "DSC-RX10" }, { 0x136, "DSC-RX1R" }, { 0x137, "ILCE-7R" }, { 0x138, "ILCE-6000" }, { 0x139, "ILCE-5000" }, { 0x13d, "DSC-RX100M3" }, { 0x13e, "ILCE-7S" }, { 0x13f, "ILCA-77M2" }, { 0x153, "ILCE-5100" }, { 0x154, "ILCE-7M2" }, { 0x155, "DSC-RX100M4" }, { 0x156, "DSC-RX10M2" }, { 0x158, "DSC-RX1RM2" }, { 0x15a, "ILCE-QX1" }, { 0x15b, "ILCE-7RM2" }, { 0x15e, "ILCE-7SM2" }, { 0x161, "ILCA-68" }, { 0x162, "ILCA-99M2" }, { 0x163, "DSC-RX10M3" }, { 0x164, "DSC-RX100M5"}, { 0x165, "ILCE-6300" }, { 0x168, "ILCE-6500"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { { 786432,1024, 768, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-080C" }, { 1447680,1392,1040, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-145C" }, { 1920000,1600,1200, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-201C" }, { 5067304,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C" }, { 5067316,2588,1958, 0, 0, 0, 0, 0,0x94,0,0,"AVT","F-510C",12 }, { 10134608,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C" }, { 10134620,2588,1958, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-510C",12 }, { 16157136,3272,2469, 0, 0, 0, 0, 9,0x94,0,0,"AVT","F-810C" }, { 15980544,3264,2448, 0, 0, 0, 0, 8,0x61,0,1,"AgfaPhoto","DC-833m" }, { 9631728,2532,1902, 0, 0, 0, 0,96,0x61,0,0,"Alcatel","5035D" }, { 31850496,4608,3456, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 4:3" }, { 23887872,4608,2592, 0, 0, 0, 0,0,0x94,0,0,"GITUP","GIT2 16:9" }, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb { 1540857,2688,1520, 0, 0, 0, 0, 1,0x61,0,0,"Samsung","S3" }, { 2658304,1212,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontMipi" }, { 2842624,1296,1096, 0, 0, 0, 0, 1 ,0x16,0,0,"LG","G3FrontQCOM" }, { 2969600,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wMipi" }, { 3170304,1976,1200, 0, 0, 0, 0, 1 ,0x16,0,0,"Xiaomi","MI3wQCOM" }, { 3763584,1584,1184, 0, 0, 0, 0, 96,0x61,0,0,"I_Mobile","I_StyleQ6" }, { 5107712,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel1" }, { 5382640,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","UltraPixel2" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5664912,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 5364240,2688,1520, 0, 0, 0, 0, 1 ,0x61,0,0,"OmniVisi","4688" }, { 6299648,2592,1944, 0, 0, 0, 0, 1 ,0x16,0,0,"OmniVisi","OV5648" }, { 6721536,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"OmniVisi","OV56482" }, { 6746112,2592,1944, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","OneSV" }, { 9631728,2532,1902, 0, 0, 0, 0, 96,0x61,0,0,"Sony","5mp" }, { 9830400,2560,1920, 0, 0, 0, 0, 96,0x61,0,0,"NGM","ForwardArt" }, { 10186752,3264,2448, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX219-mipi 8mp" }, { 10223360,2608,1944, 0, 0, 0, 0, 96,0x16,0,0,"Sony","IMX" }, { 10782464,3282,2448, 0, 0, 0, 0, 0 ,0x16,0,0,"HTC","MyTouch4GSlide" }, { 10788864,3282,2448, 0, 0, 0, 0, 0, 0x16,0,0,"Xperia","L" }, { 15967488,3264,2446, 0, 0, 0, 0, 96,0x16,0,0,"OmniVison","OV8850" }, { 16224256,4208,3082, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3MipiL" }, { 16424960,4208,3120, 0, 0, 0, 0, 1, 0x16,0,0,"IMX135","MipiL" }, { 17326080,4164,3120, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G3LQCom" }, { 17522688,4212,3120, 0, 0, 0, 0, 0,0x16,0,0,"Sony","IMX135-QCOM" }, { 19906560,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7mipi" }, { 19976192,5312,2988, 0, 0, 0, 0, 1, 0x16,0,0,"LG","G4" }, { 20389888,4632,3480, 0, 0, 0, 0, 1, 0x16,0,0,"Xiaomi","RedmiNote3Pro" }, { 20500480,4656,3496, 0, 0, 0, 0, 1,0x94,0,0,"Sony","IMX298-mipi 16mp" }, { 21233664,4608,3456, 0, 0, 0, 0, 1, 0x16,0,0,"Gione","E7qcom" }, { 26023936,4192,3104, 0, 0, 0, 0, 96,0x94,0,0,"THL","5000" }, { 26257920,4208,3120, 0, 0, 0, 0, 96,0x94,0,0,"Sony","IMX214" }, { 26357760,4224,3120, 0, 0, 0, 0, 96,0x61,0,0,"OV","13860" }, { 41312256,5248,3936, 0, 0, 0, 0, 96,0x61,0,0,"Meizu","MX4" }, { 42923008,5344,4016, 0, 0, 0, 0, 96,0x61,0,0,"Sony","IMX230" }, // Android Raw dumps id end { 20137344,3664,2748,0, 0, 0, 0,0x40,0x49,0,0,"Aptina","MT9J003",0xffff }, { 2868726,1384,1036, 0, 0, 0, 0,64,0x49,0,8,"Baumer","TXG14",1078 }, { 5298000,2400,1766,12,12,44, 2,40,0x94,0,2,"Canon","PowerShot SD300" }, { 6553440,2664,1968, 4, 4,44, 4,40,0x94,0,2,"Canon","PowerShot A460" }, { 6573120,2672,1968,12, 8,44, 0,40,0x94,0,2,"Canon","PowerShot A610" }, { 6653280,2672,1992,10, 6,42, 2,40,0x94,0,2,"Canon","PowerShot A530" }, { 7710960,2888,2136,44, 8, 4, 0,40,0x94,0,2,"Canon","PowerShot S3 IS" }, { 9219600,3152,2340,36,12, 4, 0,40,0x94,0,2,"Canon","PowerShot A620" }, { 9243240,3152,2346,12, 7,44,13,40,0x49,0,2,"Canon","PowerShot A470" }, { 10341600,3336,2480, 6, 5,32, 3,40,0x94,0,2,"Canon","PowerShot A720 IS" }, { 10383120,3344,2484,12, 6,44, 6,40,0x94,0,2,"Canon","PowerShot A630" }, { 12945240,3736,2772,12, 6,52, 6,40,0x94,0,2,"Canon","PowerShot A640" }, { 15636240,4104,3048,48,12,24,12,40,0x94,0,2,"Canon","PowerShot A650" }, { 15467760,3720,2772, 6,12,30, 0,40,0x94,0,2,"Canon","PowerShot SX110 IS" }, { 15534576,3728,2778,12, 9,44, 9,40,0x94,0,2,"Canon","PowerShot SX120 IS" }, { 18653760,4080,3048,24,12,24,12,40,0x94,0,2,"Canon","PowerShot SX20 IS" }, { 19131120,4168,3060,92,16, 4, 1,40,0x94,0,2,"Canon","PowerShot SX220 HS" }, { 21936096,4464,3276,25,10,73,12,40,0x16,0,2,"Canon","PowerShot SX30 IS" }, { 24724224,4704,3504, 8,16,56, 8,40,0x49,0,2,"Canon","PowerShot A3300 IS" }, { 30858240,5248,3920, 8,16,56,16,40,0x94,0,2,"Canon","IXUS 160" }, { 1976352,1632,1211, 0, 2, 0, 1, 0,0x94,0,1,"Casio","QV-2000UX" }, { 3217760,2080,1547, 0, 0,10, 1, 0,0x94,0,1,"Casio","QV-3*00EX" }, { 6218368,2585,1924, 0, 0, 9, 0, 0,0x94,0,1,"Casio","QV-5700" }, { 7816704,2867,2181, 0, 0,34,36, 0,0x16,0,1,"Casio","EX-Z60" }, { 2937856,1621,1208, 0, 0, 1, 0, 0,0x94,7,13,"Casio","EX-S20" }, { 4948608,2090,1578, 0, 0,32,34, 0,0x94,7,1,"Casio","EX-S100" }, { 6054400,2346,1720, 2, 0,32, 0, 0,0x94,7,1,"Casio","QV-R41" }, { 7426656,2568,1928, 0, 0, 0, 0, 0,0x94,0,1,"Casio","EX-P505" }, { 7530816,2602,1929, 0, 0,22, 0, 0,0x94,7,1,"Casio","QV-R51" }, { 7542528,2602,1932, 0, 0,32, 0, 0,0x94,7,1,"Casio","EX-Z50" }, { 7562048,2602,1937, 0, 0,25, 0, 0,0x16,7,1,"Casio","EX-Z500" }, { 7753344,2602,1986, 0, 0,32,26, 0,0x94,7,1,"Casio","EX-Z55" }, { 9313536,2858,2172, 0, 0,14,30, 0,0x94,7,1,"Casio","EX-P600" }, { 10834368,3114,2319, 0, 0,27, 0, 0,0x94,0,1,"Casio","EX-Z750" }, { 10843712,3114,2321, 0, 0,25, 0, 0,0x94,0,1,"Casio","EX-Z75" }, { 10979200,3114,2350, 0, 0,32,32, 0,0x94,7,1,"Casio","EX-P700" }, { 12310144,3285,2498, 0, 0, 6,30, 0,0x94,0,1,"Casio","EX-Z850" }, { 12489984,3328,2502, 0, 0,47,35, 0,0x94,0,1,"Casio","EX-Z8" }, { 15499264,3754,2752, 0, 0,82, 0, 0,0x94,0,1,"Casio","EX-Z1050" }, { 18702336,4096,3044, 0, 0,24, 0,80,0x94,7,1,"Casio","EX-ZR100" }, { 7684000,2260,1700, 0, 0, 0, 0,13,0x94,0,1,"Casio","QV-4000" }, { 787456,1024, 769, 0, 1, 0, 0, 0,0x49,0,0,"Creative","PC-CAM 600" }, { 28829184,4384,3288, 0, 0, 0, 0,36,0x61,0,0,"DJI" }, { 15151104,4608,3288, 0, 0, 0, 0, 0,0x94,0,0,"Matrix" }, { 3840000,1600,1200, 0, 0, 0, 0,65,0x49,0,0,"Foculus","531C" }, { 307200, 640, 480, 0, 0, 0, 0, 0,0x94,0,0,"Generic" }, { 62464, 256, 244, 1, 1, 6, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 124928, 512, 244, 1, 1,10, 1, 0,0x8d,0,0,"Kodak","DC20" }, { 1652736,1536,1076, 0,52, 0, 0, 0,0x61,0,0,"Kodak","DCS200" }, { 4159302,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330" }, { 4162462,2338,1779, 1,33, 1, 2, 0,0x94,0,0,"Kodak","C330",3160 }, { 2247168,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 3370752,1232, 912, 0, 0,16, 0, 0,0x00,0,0,"Kodak","C330" }, { 6163328,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603" }, { 6166488,2864,2152, 0, 0, 0, 0, 0,0x94,0,0,"Kodak","C603",3160 }, { 460800, 640, 480, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 9116448,2848,2134, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","C603" }, { 12241200,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP" }, { 12272756,4040,3030, 2, 0, 0,13, 0,0x49,0,0,"Kodak","12MP",31556 }, { 18000000,4000,3000, 0, 0, 0, 0, 0,0x00,0,0,"Kodak","12MP" }, { 614400, 640, 480, 0, 3, 0, 0,64,0x94,0,0,"Kodak","KAI-0340" }, { 15360000,3200,2400, 0, 0, 0, 0,96,0x16,0,0,"Lenovo","A820" }, { 3884928,1608,1207, 0, 0, 0, 0,96,0x16,0,0,"Micron","2010",3212 }, { 1138688,1534, 986, 0, 0, 0, 0, 0,0x61,0,0,"Minolta","RD175",513 }, { 1581060,1305, 969, 0, 0,18, 6, 6,0x1e,4,1,"Nikon","E900" }, { 2465792,1638,1204, 0, 0,22, 1, 6,0x4b,5,1,"Nikon","E950" }, { 2940928,1616,1213, 0, 0, 0, 7,30,0x94,0,1,"Nikon","E2100" }, { 4771840,2064,1541, 0, 0, 0, 1, 6,0xe1,0,1,"Nikon","E990" }, { 4775936,2064,1542, 0, 0, 0, 0,30,0x94,0,1,"Nikon","E3700" }, { 5865472,2288,1709, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E4500" }, { 5869568,2288,1710, 0, 0, 0, 0, 6,0x16,0,1,"Nikon","E4300" }, { 7438336,2576,1925, 0, 0, 0, 1, 6,0xb4,0,1,"Nikon","E5000" }, { 8998912,2832,2118, 0, 0, 0, 0,30,0x94,7,1,"Nikon","COOLPIX S6" }, { 5939200,2304,1718, 0, 0, 0, 0,30,0x16,0,0,"Olympus","C770UZ" }, { 3178560,2064,1540, 0, 0, 0, 0, 0,0x94,0,1,"Pentax","Optio S" }, { 4841984,2090,1544, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S" }, { 6114240,2346,1737, 0, 0,22, 0, 0,0x94,7,1,"Pentax","Optio S4" }, { 10702848,3072,2322, 0, 0, 0,21,30,0x94,0,1,"Pentax","Optio 750Z" }, { 4147200,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD" }, { 4151666,1920,1080, 0, 0, 0, 0, 0,0x49,0,0,"Photron","BC2-HD",8 }, { 13248000,2208,3000, 0, 0, 0, 0,13,0x61,0,0,"Pixelink","A782" }, { 6291456,2048,1536, 0, 0, 0, 0,96,0x61,0,0,"RoverShot","3320AF" }, { 311696, 644, 484, 0, 0, 0, 0, 0,0x16,0,8,"ST Micro","STV680 VGA" }, { 16098048,3288,2448, 0, 0,24, 0, 9,0x94,0,1,"Samsung","S85" }, { 16215552,3312,2448, 0, 0,48, 0, 9,0x94,0,1,"Samsung","S85" }, { 20487168,3648,2808, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 24000000,4000,3000, 0, 0, 0, 0,13,0x94,5,1,"Samsung","WB550" }, { 12582980,3072,2048, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 33292868,4080,4080, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 44390468,4080,5440, 0, 0, 0, 0,33,0x61,0,0,"Sinar","",68 }, { 1409024,1376,1024, 0, 0, 1, 0, 0,0x49,0,0,"Sony","XCD-SX910CR" }, { 2818048,1376,1024, 0, 0, 1, 0,97,0x49,0,0,"Sony","XCD-SX910CR" }, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table)/sizeof(const_table[0])]; #endif static const char *corp[] = { "AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony" }; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize=1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64,table,imgdata.params.custom_camera_strings); for(int q = 0; q < sizeof(const_table)/sizeof(const_table[0]); q++) memmove(&table[q+camera_count],&const_table[q],sizeof(const_table[0])); camera_count += sizeof(const_table)/sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset (tiff_ifd, 0, sizeof tiff_ifd); memset (gpsdata, 0, sizeof gpsdata); memset (cblack, 0, sizeof cblack); memset (white, 0, sizeof white); memset (mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i=0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i=0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek (ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread (head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread (head, 1, 32, ifp); #endif fseek (ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *) memmem (head, 32, (char*)"MMMM", 4)) || (cp = (char *) memmem (head, 32, (char*)"IIII", 4))) { parse_phase_one (cp-head); if (cp-head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp (head+6,"HEAPCCDR",8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff (hlen, flen-hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp (head,"\xff\xd8\xff\xe1",4) && !memcmp (head+6,"Exif",4)) { fseek (ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek (ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp (head+25,"ARECOYK",7)) { strcpy (make, "Contax"); strcpy (model,"N Digital"); fseek (ifp, 33, SEEK_SET); get_timestamp(1); fseek (ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4())/8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek (ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek (ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4())/16.0f); fseek (ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp (head, "PXN")) { strcpy (make, "Logitech"); strcpy (model,"Fotoman Pixtura"); } else if (!strcmp (head, "qktk")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp (head, "qktn")) { strcpy (make, "Apple"); strcpy (model,"QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp (head,"FUJIFILM",8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head+0x1c); memcpy(model2, head+0x3c, 4); model2[4]=0; #endif fseek (ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek (ifp, 92, SEEK_SET); parse_fuji (get4()); if (thumb_offset > 120) { fseek (ifp, 120, SEEK_SET); is_raw += (i = get4())?1:0; if (is_raw == 2 && shot_select) parse_fuji (i); } load_raw = &CLASS unpacked_load_raw; fseek (ifp, 100+28*(shot_select > 0), SEEK_SET); parse_tiff (data_offset = get4()); parse_tiff (thumb_offset+12); apply_tiff(); } else if (!memcmp (head,"RIFF",4)) { fseek (ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp (head+4,"ftypqt ",9)) { fseek (ifp, 0, SEEK_SET); parse_qt (fsize); is_raw = 0; } else if (!memcmp (head,"\0\001\0\001\0@",6)) { fseek (ifp, 6, SEEK_SET); fread (make, 1, 8, ifp); fread (model, 1, 8, ifp); fread (model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp (head,"NOKIARAW",8)) { strcpy (make, "NOKIA"); order = 0x4949; fseek (ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); width = get2(); height = get2(); switch (tiff_bps = i*8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps/8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp (head,"ARRI",4)) { order = 0x4949; fseek (ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy (make, "ARRI"); fseek (ifp, 668, SEEK_SET); fread (model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp (head,"XPDS",4)) { order = 0x4949; fseek (ifp, 0x800, SEEK_SET); fread (make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek (ifp, 56, SEEK_CUR); fread (model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve (0, 12.25, 1, 1023); } else if (!memcmp (head+4,"RED1",4)) { strcpy (make, "Red"); strcpy (model,"One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve (1/2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp (head,"DSC-Image",9)) parse_rollei(); else if (!memcmp (head,"PWAD",4)) parse_sinar_ia(); else if (!memcmp (head,"\0MRM",4)) parse_minolta(0); else if (!memcmp (head,"FOVb",4)) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) parse_foveon(); else #endif parse_x3f(); #else #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 parse_foveon(); #endif #endif } else if (!memcmp (head,"CI",2)) parse_cine(); if(make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize=i=0; i < camera_count; i++) #else for (zero_fsize=i=0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy (make, table[i].t_make ); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon",5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy (model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff?0:table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize-data_offset)*8 / (raw_width*raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize-data_offset)/raw_height*3 >= raw_width*4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal (0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp,0,SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model,"RP_imx219",9) && sz >= 0x9cb600 && !fseek (ifp, -0x9cb600, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); strcpy (model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model,"ov5647",6) && strncmp(model,"RP_OV5647",9)) && sz >= 0x61b800 && !fseek (ifp, -0x61b800, SEEK_END) && fread (head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy (make, "Broadcom"); if (!strncmp(model,"ov5647",6)) strcpy (model, "RPi OV5647 v.1"); else strcpy (model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model,"ov",2) && strncmp(model,"RP_OV",5)) && sz>=6404096 && !fseek (ifp, -6404096, SEEK_END) && fread (head, 1, 32, ifp) && !strcmp(head,"BRCMn")) { strcpy (make, "OmniVision"); data_offset = ftell(ifp) + 0x8000-32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i=0; i < sizeof corp / sizeof *corp; i++) if (strcasestr (make, corp[i])) /* Simplify company names */ strcpy (make, corp[i]); if ((!strncmp(make,"Kodak",5) || !strncmp(make,"Leica",5)) && ((cp = strcasestr(model," DIGITAL CAMERA")) || (cp = strstr(model,"FILE VERSION")))) *cp = 0; if (!strncasecmp(model,"PENTAX",6)) strcpy (make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make,sizeof(make)); remove_trailing_spaces(model,sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp (model, make, i) && model[i++] == ' ') memmove (model, model+i, 64-i); if (!strncmp (model,"FinePix ",8)) strcpy (model, model+8); if (!strncmp (model,"Digital Camera ",15)) strcpy (model, model+15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model,"K-r") || !strcmp(model,"K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model,"K-5",3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model,"K-70")) { height = 4016; top_margin=32; width=6020; left_margin = 60; } if (width == 4736 && !strcmp(model,"K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model,"K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6080 && !strcmp(model,"K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model,"645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon",5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony",4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make,"Canon",5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i=0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make,"Canon",5) && unique_id) { for (i=0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff ("Canon", unique[i].t_model); strcpy(model,unique[i].t_model); } } if (!strncasecmp(make,"Sony",4) && unique_id) { for (i=0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff ("Sony", sonique[i].t_model); strcpy(model,sonique[i].t_model); } } if (!strncmp(make,"Nikon",5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model,"KAI-0340") && find_green (16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy (model,"C603"); } if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); if (is_foveon) { if (height*2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; #ifdef LIBRAW_DEMOSAIC_PACK_GPL2 if(!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_FORCE_FOVEON_X3F)) simple_coeff(0); #endif } else if(!strncmp(make,"Pentax",6)) { if(!strncmp(model,"K-1",3)) { top_margin = 18; height = raw_height - top_margin; if(raw_width == 7392) { left_margin = 6; width = 7376; } } } else if (!strncmp(make,"Canon",5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height,width); SWAP(raw_height,raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model,"PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model,"PowerShot A5") || !strcmp(model,"PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256/235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model,"PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model,"PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model,"PowerShot Pro90 IS") || !strcmp(model,"PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model,"PowerShot A610")) { if (canon_s2is()) strcpy (model+10, "S2 IS"); } else if (!strcmp(model,"PowerShot SX220 HS")) { mask[1][3] = -4; top_margin=16; left_margin = 92; } else if (!strcmp(model,"PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model,"PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width-left_margin-48; height = raw_height-top_margin-14; } else if (!strcmp(model,"PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model,"EOS D2000C")) { filters = 0x61616161; black = curve[200]; } else if (!strcmp(model,"D1")) { cam_mul[0] *= 256/527.0; cam_mul[2] *= 256/317.0; } else if (!strcmp(model,"D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model,"D40X") || !strcmp(model,"D60") || !strcmp(model,"D80") || !strcmp(model,"D3000")) { height -= 3; width -= 4; } else if (!strcmp(model,"D3") || !strcmp(model,"D3S") || !strcmp(model,"D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model,"D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model,"D5000") || !strcmp(model,"D90")) { width -= 42; } else if (!strcmp(model,"D5100") || !strcmp(model,"D7000") || !strcmp(model,"COOLPIX A")) { width -= 44; } else if (!strcmp(model,"D3200") || !strncmp(model,"D6",2) || !strncmp(model,"D800",4)) { width -= 46; } else if (!strcmp(model,"D4") || !strcmp(model,"Df")) { width -= 52; left_margin = 2; } else if (!strncmp(model,"D40",3) || !strncmp(model,"D50",3) || !strncmp(model,"D70",3)) { width--; } else if (!strcmp(model,"D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model,"D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model,"D2H",3)) { left_margin = 6; width -= 14; } else if (!strncmp(model,"D2X",3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model,"D300",4)) { width -= 32; } else if (!strncmp(make,"Nikon",5) && raw_width == 4032) { if(!strcmp(model,"COOLPIX P7700")) { adobe_coeff ("Nikon","COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P7800")) { adobe_coeff ("Nikon","COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if(!strcmp(model,"COOLPIX P340")) load_flags=0; } else if (!strncmp(model,"COOLPIX P",9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed==0) && !strstr(software,"V1.2") ) black = 255; } else if (!strncmp(model,"1 ",2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy (model, "E995"); if (strcmp(model,"E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy (model,"E2500"); if (!strcmp(model,"E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model+1) < 3700) filters = 0x49494949; if (!strcmp(model,"Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green (12, 32, 1188864, 3576832); c = find_green (12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i,c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy (make, "Minolta"); strcpy (model,"DiMAGE Z2"); } load_flags = 6 + 24*(make[0] == 'M'); } else if (fsize == 6291456) { fseek (ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy (make, "ISG"); model[0] = 0; } } else if (!strncmp(make,"Fujifilm",8)) { if (!strcmp(model+7,"S2Pro")) { strcpy (model,"S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width ) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model,"HS50EXR") || !strcmp(model,"F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if(!strcmp(model,"S5500")) { height -= (top_margin=6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36) ((char *)xtrans)[c] = xtrans_abs[(c/6+top_margin) % 6][(c+left_margin) % 6]; } else if (!strcmp(model,"KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model,"KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make,"Minolta",7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model,"DiMAGE A",8)) { if (!strcmp(model,"DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"ALPHA",5) || !strncmp(model,"DYNAX",5) || !strncmp(model,"MAXXUM",6)) { sprintf (model+20, "DYNAX %-10s", model+6+(model[0]=='M')); adobe_coeff (make, model+20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model,"DiMAGE G",8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model,"*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model,"*ist DS")) { height -= 2; } else if (!strncmp(make,"Samsung",7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make,"Samsung",7) && !strcmp(model,"NX3000")) { top_margin = 24; left_margin = 64; width = 5472; height = 3648; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make,"Samsung",7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make,"Samsung",7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make,"Samsung",7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if(!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model,"EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model,"WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model,"WB550")) { strcpy (model, "WB550"); } else if (!strcmp(model,"EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin=24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model,"STV680 VGA")) { black = 16; } else if (!strcmp(model,"N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model,"640x480")) { gamma_curve (0.45, 4.5, 1, 255); } else if (!strncmp(make,"Hasselblad",10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if(!strncasecmp(model,"H3D",3)) { adobe_coeff("Hasselblad","H3DII-39"); strcpy(model,"H3DII-39"); } } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad","H4D-40"); strcpy(model,"H4D-40"); } else if( raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad","X1D"); } else if (raw_width == 9044) { if(black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H4D-60"); strcpy(model,"H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model,"H3DII-60"); } } else if (raw_width == 4090) { strcpy (model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if(!strncasecmp(model,"H5D",3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model,"H5D-50"); } else if(!strncasecmp(model,"H3D",3)) { black=0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack,0,sizeof(cblack)); adobe_coeff("Hasselblad","H3D-50"); strcpy(model,"H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model,"H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples+1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make,"Sinar",5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make,"Leaf",4)) { maximum = 0x3fff; fseek (ifp, data_offset, SEEK_SET); if (ljpeg_start (&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy (cdesc, "RBTG"); strcpy (model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy (model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width+height == 3144+2060) { if (!model[0]) strcpy (model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy (model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make,"Leica",5) || !strncmp(make,"Panasonic",9) || !strncasecmp(make,"YUNEEC",6)) { if (raw_width > 0&& ((flen - data_offset) / (raw_width*8/7) == raw_height) ) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i=0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16" [((filters-1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model,"C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make,"Olympus",7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model,"E-300") || !strcmp(model,"E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset (cblack, 0, sizeof cblack); } } else if (!strcmp(model,"STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model,"E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model,"SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model,"TG-4")) { width -= 16; } } else if (!strcmp(model,"N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model,"DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy (cdesc, "RGBE"); } else if (!strcmp(model,"DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make,"Sony",4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make,"Sony",4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make,"Sony",4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make,"Sony",4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make,"Sony",4) && raw_width == 6048) { width -= 24; if (strstr(model,"RX1") || strstr(model,"A99")) width -= 6; } else if (!strncmp(make,"Sony",4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make,"Sony",4) && raw_width == 8000) { width -= 32; if (!strncmp(model, "DSC", 3)) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; } } else if (!strcmp(model,"DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model,"PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve (0, 7, 1, 255); } else if (!strcmp(model,"C603") || !strcmp(model,"C330") || !strcmp(model,"12MP")) { order = 0x4949; if (filters && data_offset) { fseek (ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts (curve, 256); } else gamma_curve (0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model,"C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model,"EasyShare",9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make,"Kodak",5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model,"NC2000",6) || !strncmp(model,"EOSDCS",6) || !strncmp(model,"DCS4",4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model,"DCS460A")) goto bw; } else if (!strcmp(model,"DCS660M")) { black = 214; goto bw; } else if (!strcmp(model,"DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model+4,"20X")) strcpy (cdesc, "MYCY"); if (strstr(model,"DC25")) { strcpy (model, "DC25"); data_offset = 15424; } if (!strncmp(model,"DC2",3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0*height) / (3.0*width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0*height) / (373.0*width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model,"40")) { strcpy (model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model,"DC50")) { strcpy (model, "DC50"); height = 512; width = 768; iso_speed=84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model,"DC120")) { strcpy (model, "DC120"); height = 976; width = 848; iso_speed=160; pixel_aspect = height/0.75/width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model,"DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed=140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model,"Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model,"QuickTake",9)) { if (head[5]) strcpy (model+10, "200"); fseek (ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(),get2()) == 30 ? 738:736; if (height > width) { SWAP(height,width); fseek (ifp, data_offset-6, SEEK_SET); flip = ~get2() & 3 ? 5:6; } filters = 0x61616161; } else if (!strncmp(make,"Rollei",6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model,"GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model,"BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model,"SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if (!model[0]) sprintf (model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek (ifp, thumb_offset, SEEK_SET); if (ljpeg_start (&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if(dng_version) /* Override black level by DNG tags */ { black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack)/sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack)/sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for(int i=0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2) ) && cmatrix[0][0] > 0.125) { memcpy (rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff (make, model); #ifdef LIBRAW_LIBRARY_BUILD else if(imgdata.color.cam_xyz[0][0]<0.01) adobe_coeff (make, model,1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff ("Apple","Quicktake"); if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width ) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if(maximum < 0x10000 && curve[maximum]>0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if(raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_width > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf (stderr,_("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy (cdesc, colors == 3 ? "RGBG":"GMCY"); if (!raw_height) raw_height = height; if (!raw_width ) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if(flip > 89 || flip < -89) { switch ((flip+3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY,1,2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { { 0.436083, 0.385083, 0.143055 }, { 0.222507, 0.716888, 0.060608 }, { 0.013930, 0.097097, 0.714022 } }; static const double rgb_rgb[3][3] = { { 1,0,0 }, { 0,1,0 }, { 0,0,1 } }; static const double adobe_rgb[3][3] = { { 0.715146, 0.284856, 0.000000 }, { 0.000000, 1.000000, 0.000000 }, { 0.000000, 0.041166, 0.958839 } }; static const double wide_rgb[3][3] = { { 0.593087, 0.404710, 0.002206 }, { 0.095413, 0.843149, 0.061439 }, { 0.011621, 0.069091, 0.919288 } }; static const double prophoto_rgb[3][3] = { { 0.529317, 0.330092, 0.140588 }, { 0.098368, 0.873465, 0.028169 }, { 0.016879, 0.117663, 0.865457 } }; static const double aces_rgb[3][3] = { { 0.432996, 0.375380, 0.189317 }, { 0.089427, 0.816523, 0.102989 }, { 0.019165, 0.118150, 0.941914 } }; static const double (*out_rgb[])[3] = { rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb }; static const char *name[] = { "sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES" }; static const unsigned phead[] = { 1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d }; unsigned pbody[] = { 10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20 }; /* bXYZ */ static const unsigned pwhite[] = { 0xf351, 0x10000, 0x116cc }; unsigned pcurve[] = { 0x63757276, 0, 1, 0x1000000 }; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,0,2); #endif gamma_curve (gamm[0], gamm[1], 0, 0); memcpy (out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *) calloc (phead[0], 1); merror (oprof, "convert_to_rgb()"); memcpy (oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12*pbody[0]; for (i=0; i < pbody[0]; i++) { oprof[oprof[0]/4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i*3+2] = oprof[0]; oprof[0] += (pbody[i*3+3] + 3) & -4; } memcpy (oprof+32, pbody, sizeof pbody); oprof[pbody[5]/4+2] = strlen(name[output_color-1]) + 1; memcpy ((char *)oprof+pbody[8]+8, pwhite, sizeof pwhite); pcurve[3] = (short)(256/gamm[5]+0.5) << 16; for (i=4; i < 7; i++) memcpy ((char *)oprof+pbody[i*3+2], pcurve, sizeof pcurve); pseudoinverse ((double (*)[3]) out_rgb[output_color-1], inverse, 3); for (i=0; i < 3; i++) for (j=0; j < 3; j++) { for (num = k=0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j*3+23]/4+i+2] = num * 0x10000 + 0.5; } for (i=0; i < phead[0]/4; i++) oprof[i] = htonl(oprof[i]); strcpy ((char *)oprof+pbody[2]+8, "auto-generated by dcraw"); strcpy ((char *)oprof+pbody[5]+12, name[output_color-1]); for (i=0; i < 3; i++) for (j=0; j < colors; j++) for (out_cam[i][j] = k=0; k < 3; k++) out_cam[i][j] += out_rgb[output_color-1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color-1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset (histogram, 0, sizeof histogram); for (img=image[0], row=0; row < height; row++) for (col=0; col < width; col++, img+=4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int) out[c]); } else if (document_mode) img[0] = img[fcol(row,col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB,1,2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort (*)[4]) calloc (high, wide*sizeof *img); merror (img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,0,2); #endif for (row=0; row < high; row++) for (col=0; col < wide; col++) { ur = r = fuji_width + (row-col)*step; uc = c = (row+col)*step; if (ur > height-2 || uc > width-2) continue; fr = r - ur; fc = c - uc; pix = image + ur*width + uc; for (i=0; i < colors; i++) img[row*wide+col][i] = (pix[ 0][i]*(1-fc) + pix[ 1][i]*fc) * (1-fr) + (pix[width][i]*(1-fc) + pix[width+1][i]*fc) * fr; } free (image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE,1,2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,0,2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf (stderr,_("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (width, newdim*sizeof *img); merror (img, "stretch()"); for (rc=row=0; row < newdim; row++, rc+=pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c*width]; if (c+1 < height) pix1 += width*4; for (col=0; col < width; col++, pix0+=4, pix1+=4) FORCC img[row*width+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort (*)[4]) calloc (height, newdim*sizeof *img); merror (img, "stretch()"); for (rc=col=0; col < newdim; col++, rc+=1/pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c+1 < width) pix1 += 4; for (row=0; row < height; row++, pix0+=width*4, pix1+=width*4) FORCC img[row*newdim+col][c] = pix0[c]*(1-frac) + pix1[c]*frac + 0.5; } width = newdim; } free (image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH,1,2); #endif } int CLASS flip_index (int row, int col) { if (flip & 4) SWAP(row,col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set (struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag+1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count-1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val+c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head (struct tiff_hdr *th, int full) { int c, psize=0; struct tm *t; memset (th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4+c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy (th->t_desc, desc, 512); strncpy (th->t_make, make, 64); strncpy (th->t_model, model, 64); strcpy (th->soft, "dcraw v" DCRAW_VERSION); t = localtime (&timestamp); sprintf (th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year+1900,t->tm_mon+1,t->tm_mday,t->tm_hour,t->tm_min,t->tm_sec); strncpy (th->t_artist, artist, 64); if (full) { tiff_set (th, &th->ntag, 254, 4, 1, 0); tiff_set (th, &th->ntag, 256, 4, 1, width); tiff_set (th, &th->ntag, 257, 4, 1, height); tiff_set (th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag-1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set (th, &th->ntag, 259, 3, 1, 1); tiff_set (th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set (th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set (th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set (th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set (th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set (th, &th->ntag, 277, 3, 1, colors); tiff_set (th, &th->ntag, 278, 4, 1, height); tiff_set (th, &th->ntag, 279, 4, 1, height*width*colors*output_bps/8); } else tiff_set (th, &th->ntag, 274, 3, 1, "12435867"[flip]-'0'); tiff_set (th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set (th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set (th, &th->ntag, 284, 3, 1, 1); tiff_set (th, &th->ntag, 296, 3, 1, 2); tiff_set (th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set (th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set (th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set (th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set (th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set (th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set (th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set (th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set (th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set (th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set (th, &th->ngps, 0, 1, 4, 0x202); tiff_set (th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set (th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set (th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set (th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set (th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set (th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set (th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set (th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set (th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy (th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer (FILE *tfp,char *t_humb,int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc (0xff, tfp); fputc (0xd8, tfp); if (strcmp (t_humb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, tfp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, tfp); } fwrite (t_humb+2, 1, t_humb_length-2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp,thumb,thumb_length); free (thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *) malloc (thumb_length); merror (thumb, "jpeg_thumb()"); fread (thumb, 1, thumb_length, ifp); fputc (0xff, ofp); fputc (0xd8, ofp); if (strcmp (thumb+6, "Exif")) { memcpy (exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons (8 + sizeof th); fwrite (exif, 1, sizeof exif, ofp); tiff_head (&th, 0); fwrite (&th, 1, sizeof th, ofp); } fwrite (thumb+2, 1, thumb_length-2, ofp); free (thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white=0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white=c=0; c < colors; c++) { for (val=0x2000, total=0; --val > 32; ) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve (gamm[0], gamm[1], 2, (t_white << 3)/bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height,width); ppm = (uchar *) calloc (width, colors*output_bps/8); ppm2 = (ushort *) ppm; merror (ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head (&th, 1); fwrite (&th, sizeof th, 1, ofp); if (oprof) fwrite (oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf (ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps)-1, cdesc); else fprintf (ofp, "P%d\n%d %d\n%d\n", colors/2+5, width, height, (1 << output_bps)-1); soff = flip_index (0, 0); cstep = flip_index (0, 1) - soff; rstep = flip_index (1, 0) - flip_index (0, width); for (row=0; row < height; row++, soff += rstep) { for (col=0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm [col*colors+c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col*colors+c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab ((char*)ppm2, (char*)ppm2, width*colors*2); fwrite (ppm, colors*output_bps/8, width, ofp); } free (ppm); }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_2804_2
crossvul-cpp_data_bad_4253_0
/* JSON_parser.c */ /* 2005-12-30 */ /* Copyright (c) 2005 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // If we have json-c then don't use this library since that one has a more // permissive licence #ifndef HAVE_JSONC #include "hphp/runtime/ext/json/JSON_parser.h" #include <folly/FBVector.h> #include "hphp/runtime/base/array-provenance.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/collections.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-info.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/base/init-fini-node.h" #include "hphp/runtime/base/utf8-decode.h" #include "hphp/runtime/ext/json/ext_json.h" #include "hphp/runtime/ext/collections/ext_collections-map.h" #include "hphp/runtime/ext/collections/ext_collections-vector.h" #include "hphp/system/systemlib.h" #include "hphp/util/fast_strtoll_base10.h" #include "hphp/zend/zend-strtod.h" #define MAX_LENGTH_OF_LONG 20 static const char long_min_digits[] = "9223372036854775808"; namespace HPHP { /* Characters are mapped into these 32 symbol classes. This allows for significant reductions in the size of the state transition table. */ /* error */ #define S_ERR -1 /* space */ #define S_SPA 0 /* other whitespace */ #define S_WSP 1 /* { */ #define S_LBE 2 /* } */ #define S_RBE 3 /* [ */ #define S_LBT 4 /* ] */ #define S_RBT 5 /* : */ #define S_COL 6 /* , */ #define S_COM 7 /* " */ #define S_QUO 8 /* \ */ #define S_BAC 9 /* / */ #define S_SLA 10 /* + */ #define S_PLU 11 /* - */ #define S_MIN 12 /* . */ #define S_DOT 13 /* 0 */ #define S_ZER 14 /* 123456789 */ #define S_DIG 15 /* a */ #define S__A_ 16 /* b */ #define S__B_ 17 /* c */ #define S__C_ 18 /* d */ #define S__D_ 19 /* e */ #define S__E_ 20 /* f */ #define S__F_ 21 /* l */ #define S__L_ 22 /* n */ #define S__N_ 23 /* r */ #define S__R_ 24 /* s */ #define S__S_ 25 /* t */ #define S__T_ 26 /* u */ #define S__U_ 27 /* ABCDF */ #define S_A_F 28 /* E */ #define S_E 29 /* everything else */ #define S_ETC 30 /* This table maps the 128 ASCII characters into the 32 character classes. The remaining Unicode characters should be mapped to S_ETC. */ alignas(64) static const int8_t ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*<fb>*/ alignas(64) static const int8_t loose_ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*</fb>*/ /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. A new state is a number between 0 and 29. An action is a negative number between -1 and -9. A JSON text is accepted if the end of the text is in state 9 and mode is Mode::DONE. */ alignas(64) static const int8_t state_transition_table[30][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} }; /*<fb>*/ /* Alternate "loose" transition table to support unquoted keys. Note: State 3 has same outgoing transitions in both transition tables. This is used below in the fast-case for appending simple characters (3 -> 3). */ alignas(64) static const int8_t loose_state_transition_table[31][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-7,-1,-1,-1,-7, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /*30*/ {30,-1,30,30,30,30,-10,30,-4,4,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30} }; /*</fb>*/ /** * These modes can be pushed on the PDA stack. */ enum class Mode { INVALID = 0, DONE = 1, KEY = 2, OBJECT = 3, ARRAY = 4 }; namespace { int dehexchar(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - ('A' - 10); if (c >= 'a' && c <= 'f') return c - ('a' - 10); return -1; } NEVER_INLINE static void tvDecRefRange(TypedValue* begin, TypedValue* end) { assertx(begin <= end); for (auto tv = begin; tv != end; ++tv) { tvDecRefGen(tv); } } /* * Parses a subset of JSON. Currently unsupported: * - Non-ASCII * - Character escape sequences * - Non-string array keys * - Arrays nested > 255 levels */ struct SimpleParser { static constexpr int kMaxArrayDepth = 255; /* * Returns buffer size in bytes needed to handle any input up to given length. */ static size_t BufferBytesForLength(int length) { return (length + 1) * sizeof(TypedValue) / 2; // Worst case: "[0,0,...,0]" } /* * Returns false for unsupported or malformed input (does not distinguish). */ static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); parser.skipSpace(); if (!ok || parser.p != inp + length) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; } private: SimpleParser(const char* input, int length, TypedValue* buffer, JSONContainerType container_type, bool is_tsimplejson) : p(input) , top(buffer) , array_depth(-kMaxArrayDepth) /* Start negative to simplify check. */ , container_type(container_type) , is_tsimplejson(is_tsimplejson) { assertx(input[length] == 0); // Parser relies on sentinel to avoid checks. } /* * Skip whitespace, then if next char is 'ch', consume it and return true, * otherwise let it be and return false. */ bool matchSeparator(char ch) { if (LIKELY(*p++ == ch)) return true; return matchSeparatorSlow(ch); } NEVER_INLINE bool matchSeparatorSlow(char ch) { --p; skipSpace(); if (LIKELY(*p++ == ch)) return true; --p; return false; } NEVER_INLINE void skipSpace() { while (isSpace(*p)) p++; } bool isSpace(char ch) const { return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\f'; } /* * Variant parser. * * JSON arrays don't permit leading 0's in numbers, so we have to thread that * context through here to parseNumber(). */ bool parseValue(bool array_elem = false) { auto const ch = *p++; if (ch == '{') return parseMixed(); else if (ch == '[') return parsePacked(); else if (ch == '\"') return parseString(); else if ((ch >= '0' && ch <= '9') || ch == '-') return parseNumber(ch, array_elem); else if (ch == 't') return parseRue(); else if (ch == 'f') return parseAlse(); else if (ch == 'n') return parseUll(); else if (isSpace(ch)) { skipSpace(); return parseValue(array_elem); } else return false; } bool parseRue() { if (*p++ != 'r') return false; if (*p++ != 'u') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = true; return true; } bool parseAlse() { if (*p++ != 'a') return false; if (*p++ != 'l') return false; if (*p++ != 's') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = false; return true; } bool parseUll() { if (*p++ != 'u') return false; if (*p++ != 'l') return false; if (*p++ != 'l') return false; top++->m_type = KindOfNull; return true; } bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } } bool parseRawString(int* len) { assertx(p[-1] == '"'); // SimpleParser only handles "-quoted strings *len = 0; auto const charTop = reinterpret_cast<signed char*>(top); for (signed char ch = *p++; ch != '\"'; ch = *p++) { charTop[(*len)++] = ch; // overwritten later if `ch == '\\'` if (ch < ' ') { // `ch < ' '` catches null and also non-ASCII (since signed char) return false; } else if (ch == '\\') { if (!handleBackslash(charTop[*len - 1])) return false; } } return true; } bool parseString() { int len; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); pushStringData(StringData::Make(start, len, CopyString)); return true; } bool parseMixedKey() { int len; int64_t num; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); auto const slice = folly::StringPiece(start, len); start[len] = '\0'; if (container_type != JSONContainerType::HACK_ARRAYS && container_type != JSONContainerType::LEGACY_HACK_ARRAYS && is_strictly_integer(start, len, num)) { pushInt64(num); } else if (auto const str = lookupStaticString(slice)) { auto const tv = top++; tv->m_type = KindOfPersistentString; tv->m_data.pstr = str; } else { pushStringData(StringData::Make(start, len, CopyString)); } return true; } bool parsePacked() { auto const fp = top; if (!matchSeparator(']')) { if (++array_depth >= 0) return false; do { if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator(']')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateVec() : PackedArray::MakeVecNatural(top - fp, fp); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyVecArray()->copy() : PackedArray::MakeVecNatural(top - fp, fp); ret->setLegacyArray(true); return ret; } if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { return top == fp ? ArrayData::CreateVArray() : PackedArray::MakeVArrayNatural(top - fp, fp); } assertx(container_type == JSONContainerType::DARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArrayNatural(top - fp, fp); }(); top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } bool parseMixed() { auto const fp = top; if (!matchSeparator('}')) { if (++array_depth >= 0) return false; do { if (!matchSeparator('\"')) return false; // Only support string keys. if (!parseMixedKey()) return false; // TODO(14491721): Precompute and save hash to avoid deref in MakeMixed. if (!matchSeparator(':')) return false; if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator('}')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateDict() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyDictArray()->copy() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); ret->setLegacyArray(true); return ret; } assertx(container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArray((top - fp) >> 1, fp)->asArrayData(); }(); // MixedArray::MakeMixed can return nullptr if there are duplicate keys if (!arr) return false; top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } /* * Parse remainder of number after initial character firstChar (maybe '-'). */ bool parseNumber(char firstChar, bool array_elem = false) { uint64_t x = 0; bool neg = false; const char* begin = p - 1; if (firstChar == '-') { neg = true; } else { x = firstChar - '0'; // first digit } // Parse maximal digit sequence into x (non-negative). while (*p >= '0' && *p <= '9') { x = (x * 10) + (*p - '0'); ++p; } if (*p == '.' || *p == 'e' || *p == 'E') { pushDouble(zend_strtod(begin, &p)); return true; } auto len = p - begin; // JSON arrays don't permit leading 0's in numbers. if (UNLIKELY(len > 1 && firstChar == '0' && array_elem)) { return false; } // Now 'x' is the usigned absolute value of a naively parsed integer, but // potentially overflowed mod 2^64. if (LIKELY(len < 19) || (len == 19 && firstChar <= '8')) { int64_t sx = x; pushInt64(neg ? -sx : sx); } else { parseBigInt(len); } return true; } /* * Assuming 'len' characters ('0'-'9', maybe prefix '-') have been read, * re-parse and push as an int64_t if possible, otherwise as a double. */ void parseBigInt(int len) { assertx(*p > '9' || *p < '0'); // Aleady read maximal digit sequence. errno = 0; const int64_t sx = strtoll(p - len, nullptr, 10); if (errno == ERANGE) { const double dval = zend_strtod(p - len, nullptr); assertx(dval == floor(dval)); pushDouble(dval); } else { pushInt64(sx); } } void pushDouble(double data) { auto const tv = top++; tv->m_type = KindOfDouble; tv->m_data.dbl = data; } void pushInt64(int64_t data) { auto const tv = top++; tv->m_type = KindOfInt64; tv->m_data.num = data; } void pushStringData(StringData* data) { auto const tv = top++; tv->m_type = KindOfString; tv->m_data.pstr = data; } void pushArrayData(ArrayData* data) { auto const tv = top++; tv->m_type = data->toDataType(); tv->m_data.parr = data; assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } const char* p; TypedValue* top; int array_depth; JSONContainerType container_type; bool is_tsimplejson; }; /* * String buffer wrapper that does NOT check its capacity in release mode. User * supplies the allocation and must ensure to never append past the end. */ struct UncheckedBuffer { void clear() { p = begin; } // Use given buffer with space for 'cap' chars, including '\0'. void setBuf(char* buf, size_t cap) { begin = p = buf; #ifndef NDEBUG end = begin + cap; #endif } void append(char c) { assertx(p < end); *p++ = c; } void shrinkBy(int decrease) { p -= decrease; assertx(p >= begin); } int size() { return p - begin; } // NUL-terminates the output before returning it, for backward-compatibility. char* data() { assertx(p < end); *p = 0; return begin; } String copy() { return String(data(), size(), CopyString); } char* p{nullptr}; char* begin{nullptr}; #ifndef NDEBUG char* end{nullptr}; #endif }; } /** * A stack maintains the states of nested structures. */ struct json_parser { struct json_state { Mode mode; String key; Variant val; }; folly::fbvector<json_state> stack; // check_non_safepoint_surprise() above will not trigger gc TYPE_SCAN_IGNORE_FIELD(stack); int top; int mark; // the watermark int depth; json_error_codes error_code; // Thread-local buffer; reused on each call. JSON parsing cannot lead to code // execution and is not re-entrant. SimpleParser assumes no surprise checks. union { TypedValue* tv{nullptr}; // SimpleParser's stack. char* raw; // sb_buf/key } tl_buffer; TYPE_SCAN_IGNORE_FIELD(tv); UncheckedBuffer sb_buf; UncheckedBuffer sb_key; int sb_cap{0}; // Capacity of each of sb_buf/key. void initSb(int length) { if (UNLIKELY(length >= sb_cap)) { // No decoded string in the output can use more bytes than input size. const auto new_cap = length + 1; size_t bufSize = length <= RuntimeOption::EvalSimpleJsonMaxLength ? SimpleParser::BufferBytesForLength(length) : new_cap * 2; if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; if (!tl_heap->preAllocOOM(bufSize)) { tl_buffer.raw = (char*)json_malloc(bufSize); if (!tl_buffer.raw) tl_heap->forceOOM(); } check_non_safepoint_surprise(); always_assert(tl_buffer.raw); sb_buf.setBuf(tl_buffer.raw, new_cap); sb_key.setBuf(tl_buffer.raw + new_cap, new_cap); // Set new capacity if and ony if allocations succeed. sb_cap = new_cap; } else { sb_buf.clear(); sb_key.clear(); } } void flushSb() { if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; sb_buf.setBuf(nullptr, 0); sb_key.setBuf(nullptr, 0); } private: static void* json_malloc(size_t size) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_malloc(size); } else { return malloc(size); } } static void json_free(void* ptr) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_free(ptr); } else { return free(ptr); } } }; RDS_LOCAL(json_parser, s_json_parser); // In Zend, the json_parser struct is publicly // accessible. Thus the fields could be accessed // directly. Just using setter/accessor functions // to get around that. json_error_codes json_get_last_error_code() { return s_json_parser->error_code; } void json_set_last_error_code(json_error_codes ec) { s_json_parser->error_code = ec; } const char *json_get_last_error_msg() { switch (s_json_parser->error_code) { case JSON_ERROR_NONE: return "No error"; case JSON_ERROR_DEPTH: return "Maximum stack depth exceeded"; case JSON_ERROR_STATE_MISMATCH: return "State mismatch (invalid or malformed JSON)"; case JSON_ERROR_CTRL_CHAR: return "Control character error, possibly incorrectly encoded"; case JSON_ERROR_SYNTAX: return "Syntax error"; case JSON_ERROR_UTF8: return "Malformed UTF-8 characters, possibly incorrectly encoded"; case json_error_codes::JSON_ERROR_RECURSION: return "Recursion detected"; case json_error_codes::JSON_ERROR_INF_OR_NAN: return "Inf and NaN cannot be JSON encoded"; case json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE: return "Type is not supported"; default: return "Unknown error"; } } // For each request, make sure we start with the default error code. void json_parser_init() { s_json_parser->error_code = JSON_ERROR_NONE; } void json_parser_flush_caches() { s_json_parser->flushSb(); } /** * Push a mode onto the stack. Return false if there is overflow. */ static int push(json_parser *json, Mode mode) { if (json->top + 1 >= json->depth) { return false; } json->top += 1; json->stack[json->top].mode = mode; if (json->top > json->mark) { json->mark = json->top; } return true; } /** * Pop the stack, assuring that the current mode matches the expectation. * Return false if there is underflow or if the modes mismatch. */ static int pop(json_parser *json, Mode mode) { if (json->top < 0 || json->stack[json->top].mode != mode) { return false; } json->stack[json->top].mode = Mode::INVALID; json->top -= 1; return true; } static String copy_and_clear(UncheckedBuffer &buf) { auto ret = buf.size() > 0 ? buf.copy() : empty_string(); buf.clear(); return ret; } static Variant to_double(UncheckedBuffer &buf) { auto data = buf.data(); auto ret = data ? zend_strtod(data, nullptr) : 0.0; buf.clear(); return ret; } static void json_create_zval(Variant &z, UncheckedBuffer &buf, DataType type, int64_t options) { switch (type) { case KindOfBoolean: z = (buf.data() && (*buf.data() == 't')); return; case KindOfInt64: { bool bigint = false; const char *p = buf.data(); assertx(p); if (p == NULL) { z = int64_t(0); return; } bool neg = *buf.data() == '-'; int len = buf.size(); if (neg) len--; if (len >= MAX_LENGTH_OF_LONG - 1) { if (len == MAX_LENGTH_OF_LONG - 1) { int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits); if (!(cmp < 0 || (cmp == 0 && neg))) { bigint = true; } } else { bigint = true; } } if (bigint) { if (!(options & k_JSON_BIGINT_AS_STRING)) { // See KindOfDouble (below) z = to_double(buf); } else { z = copy_and_clear(buf); } } else { z = fast_strtoll_base10(buf.data()); } return; } case KindOfDouble: // Use zend_strtod() instead of strtod() here since JSON specifies using // a '.' for decimal separators regardless of locale. z = to_double(buf); return; case KindOfString: z = copy_and_clear(buf); return; case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfPersistentArray: case KindOfArray: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfObject: case KindOfResource: case KindOfFunc: case KindOfClass: case KindOfClsMeth: case KindOfRecord: z = uninit_null(); return; } not_reached(); } NEVER_INLINE void utf16_to_utf8_tail(UncheckedBuffer &buf, unsigned short utf16) { if (utf16 < 0x800) { buf.append((char)(0xc0 | (utf16 >> 6))); buf.append((char)(0x80 | (utf16 & 0x3f))); } else if ((utf16 & 0xfc00) == 0xdc00 && buf.size() >= 3 && ((unsigned char)buf.data()[buf.size() - 3]) == 0xed && ((unsigned char)buf.data()[buf.size() - 2] & 0xf0) == 0xa0 && ((unsigned char)buf.data()[buf.size() - 1] & 0xc0) == 0x80) { /* found surrogate pair */ unsigned long utf32; utf32 = (((buf.data()[buf.size() - 2] & 0xf) << 16) | ((buf.data()[buf.size() - 1] & 0x3f) << 10) | (utf16 & 0x3ff)) + 0x10000; buf.shrinkBy(3); buf.append((char)(0xf0 | (utf32 >> 18))); buf.append((char)(0x80 | ((utf32 >> 12) & 0x3f))); buf.append((char)(0x80 | ((utf32 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf32 & 0x3f))); } else { buf.append((char)(0xe0 | (utf16 >> 12))); buf.append((char)(0x80 | ((utf16 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf16 & 0x3f))); } } ALWAYS_INLINE void utf16_to_utf8(UncheckedBuffer &buf, unsigned short utf16) { if (LIKELY(utf16 < 0x80)) { buf.append((char)utf16); return; } return utf16_to_utf8_tail(buf, utf16); } StaticString s__empty_("_empty_"); static void object_set(const json_parser* json, Variant &var, const String& key, const Variant& value, int assoc, JSONContainerType container_type) { if (!assoc) { // We know it is stdClass, and everything is public (and dynamic). if (key.empty()) { var.getObjectData()->setProp(nullptr, s__empty_.get(), *value.asTypedValue()); } else { var.getObjectData()->o_set(key, value); } } else { if (container_type == JSONContainerType::COLLECTIONS) { auto keyTV = make_tv<KindOfString>(key.get()); collections::set(var.getObjectData(), &keyTV, value.asTypedValue()); } else if (container_type == JSONContainerType::HACK_ARRAYS || container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { forceToDict(var).set(key, value); } else { int64_t i; if (key.get()->isStrictlyInteger(i)) { forceToDArray(var).set(i, value); } else { forceToDArray(var).set(key, value); } } if (var.isArray()) { DEBUG_ONLY auto const data = var.getArrayData(); assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } } } static void attach_zval(json_parser *json, const String& key, int assoc, JSONContainerType container_type) { if (json->top < 1) { return; } auto& root = json->stack[json->top - 1].val; auto& child = json->stack[json->top].val; auto up_mode = json->stack[json->top - 1].mode; if (up_mode == Mode::ARRAY) { if (container_type == JSONContainerType::COLLECTIONS) { collections::append(root.getObjectData(), child.asTypedValue()); } else { root.asArrRef().append(child); } } else if (up_mode == Mode::OBJECT) { object_set(json, root, key, child, assoc, container_type); } } JSONContainerType get_container_type_from_options(int64_t options) { if ((options & k_JSON_FB_STABLE_MAPS) || (options & k_JSON_FB_COLLECTIONS)) { return JSONContainerType::COLLECTIONS; } if (options & k_JSON_FB_HACK_ARRAYS) { return JSONContainerType::HACK_ARRAYS; } if (options & k_JSON_FB_DARRAYS) { return JSONContainerType::DARRAYS; } if (options & k_JSON_FB_DARRAYS_AND_VARRAYS) { return JSONContainerType::DARRAYS_AND_VARRAYS; } if (options & k_JSON_FB_LEGACY_HACK_ARRAYS) { return JSONContainerType::LEGACY_HACK_ARRAYS; } return JSONContainerType::DARRAYS; } /** * The JSON_parser takes a UTF-8 encoded string and determines if it is a * syntactically correct JSON text. Along the way, it creates a PHP variable. * * It is implemented as a Pushdown Automaton; that means it is a finite state * machine with a stack. * * The behavior is as follows: * Container Type | is_assoc | JSON input => output type * * COLLECTIONS | true | "{}" => c_Map * COLLECTIONS | false | "{}" => c_Map * COLLECTIONS | true | "[]" => c_Vector * COLLECTIONS | false | "[]" => c_Vector * * HACK_ARRAYS | true | "{}" => dict * HACK_ARRAYS | false | "{}" => stdClass * HACK_ARRAYS | true | "[]" => vec * HACK_ARRAYS | false | "[]" => stdClass * * DARRAYS | true | "{}" => darray * DARRAYS | false | "{}" => stdClass * DARRAYS | true | "[]" => darray * DARRAYS | false | "[]" => stdClass * * DARRAYS_AND_VARRAYS | true | "{}" => darray * DARRAYS_AND_VARRAYS | false | "{}" => stdClass * DARRAYS_AND_VARRAYS | true | "[]" => varray * DARRAYS_AND_VARRAYS | false | "[]" => stdClass */ bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } #endif /* HAVE_JSONC */
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_4253_0
crossvul-cpp_data_bad_1183_2
// This file is part of The New Aspell // Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #include <string.h> #include "getdata.hpp" #include "string.hpp" #include "asc_ctype.hpp" #include "iostream.hpp" namespace acommon { unsigned int linenumber = 0 ; bool getdata_pair(IStream & in, DataPair & d, String & buf) { char * p; // get first non blank line and count all read ones do { buf.clear(); buf.append('\0'); // to avoid some special cases if (!in.append_line(buf)) return false; d.line_num++; p = buf.mstr() + 1; while (*p == ' ' || *p == '\t') ++p; } while (*p == '#' || *p == '\0'); // get key d.key.str = p; while (*p != '\0' && ((*p != ' ' && *p != '\t' && *p != '#') || *(p-1) == '\\')) ++p; d.key.size = p - d.key.str; // figure out if there is a value and add terminate key d.value.str = p; // in case there is no value d.value.size = 0; if (*p == '#' || *p == '\0') {*p = '\0'; return true;} *p = '\0'; // skip any whitespace ++p; while (*p == ' ' || *p == '\t') ++p; if (*p == '\0' || *p == '#') {return true;} // get value d.value.str = p; while (*p != '\0' && (*p != '#' || *(p-1) == '\\')) ++p; // remove trailing white space and terminate value --p; while (*p == ' ' || *p == '\t') --p; if (*p == '\\' && *(p + 1) != '\0') ++p; ++p; d.value.size = p - d.value.str; *p = '\0'; return true; } char * unescape(char * dest, const char * src) { while (*src) { if (*src == '\\') { ++src; switch (*src) { case 'n': *dest = '\n'; break; case 'r': *dest = '\r'; break; case 't': *dest = '\t'; break; case 'f': *dest = '\f'; break; case 'v': *dest = '\v'; break; default: *dest = *src; } } else { *dest = *src; } ++src; ++dest; } *dest = '\0'; return dest; } bool escape(char * dest, const char * src, size_t limit, const char * others) { const char * begin = src; const char * end = dest + limit; if (asc_isspace(*src)) { if (dest == end) return false; *dest++ = '\\'; if (dest == end) return false; *dest++ = *src++; } while (*src) { if (dest == end) return false; switch (*src) { case '\n': *dest++ = '\\'; *dest = 'n'; break; case '\r': *dest++ = '\\'; *dest = 'r'; break; case '\t': *dest++ = '\\'; *dest = 't'; break; case '\f': *dest++ = '\\'; *dest = 'f'; break; case '\v': *dest++ = '\\'; *dest = 'v'; break; case '\\': *dest++ = '\\'; *dest = '\\'; break; case '#' : *dest++ = '\\'; *dest = '#'; break; default: if (others && strchr(others, *src)) *dest++ = '\\'; *dest = *src; } ++src; ++dest; } if (src > begin + 1 && asc_isspace(src[-1])) { --dest; *dest++ = '\\'; if (dest == end) return false; *dest++ = src[-1]; } *dest = '\0'; return true; } void to_lower(char * str) { for (; *str; str++) *str = asc_tolower(*str); } void to_lower(String & res, const char * str) { for (; *str; str++) res += asc_tolower(*str); } bool split(DataPair & d) { char * p = d.value; char * end = p + d.value.size; d.key.str = p; while (p != end) { ++p; if ((*p == ' ' || *p == '\t') && *(p-1) != '\\') break; } d.key.size = p - d.key.str; *p = 0; if (p != end) { ++p; while (p != end && (*p == ' ' || *p == '\t')) ++p; } d.value.str = p; d.value.size = end - p; return d.key.size != 0; } void init(ParmString str, DataPair & d, String & buf) { const char * s = str; while (*s == ' ' || *s == '\t') ++s; size_t l = str.size() - (s - str); buf.assign(s, l); d.value.str = buf.mstr(); d.value.size = l; } bool getline(IStream & in, DataPair & d, String & buf) { if (!in.getline(buf)) return false; d.value.str = buf.mstr(); d.value.size = buf.size(); return true; } char * get_nb_line(IStream & in, String & buf) { char * p; // get first non blank line do { if (!in.getline(buf)) return 0; p = buf.mstr(); while (*p == ' ' || *p == '\t') ++p; } while (*p == '#' || *p == '\0'); return p; } void remove_comments(String & buf) { char * p = buf.mstr(); char * b = p; while (*p && *p != '#') ++p; if (*p == '#') {--p; while (p >= b && asc_isspace(*p)) --p; ++p;} buf.resize(p - b); } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_1183_2
crossvul-cpp_data_good_94_0
/* Copyright 2008-2018 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol(int row, int col) { static const char filter[16][16] = { {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2}, {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1}, {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1}, {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3}, {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2}, {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0}, {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1}, {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}}; if (filters == 1) return filter[(row + top_margin) & 15][(col + left_margin) & 15]; if (filters == 9) return xtrans[(row + 6) % 6][(col + 6) % 6]; return FC(row, col); } #if !defined(__FreeBSD__) static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return (p ? p - s : n); } /* add OS X version check here ?? */ #define strnlen(a, b) local_strnlen(a, b) #endif #ifdef LIBRAW_LIBRARY_BUILD static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten}; static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int); static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300, 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300, 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000}; static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1, LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11, LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35, LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83}; static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int); static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather, LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW}; static int Oly_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Tungsten, 3000, 0x100, 3300, 0x100, 3600, 0x100, 3900, LIBRAW_WBI_FL_W, 4000, 0x100, 4300, LIBRAW_WBI_FL_D, 4500, 0x100, 4800, LIBRAW_WBI_FineWeather, 5300, LIBRAW_WBI_Cloudy, 6000, LIBRAW_WBI_FL_N, 6600, LIBRAW_WBI_Shade, 7500, LIBRAW_WBI_Custom1, 0, LIBRAW_WBI_Custom2, 0, LIBRAW_WBI_Custom3, 0, LIBRAW_WBI_Custom4, 0}; static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash}; static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L}; static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int); static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf, len, 1); buf[len - 1] = 0; return r; } #define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp) #endif #if !defined(__GLIBC__) && !defined(__FreeBSD__) char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp(c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr(char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf, sizeof(buf) - 1) ushort CLASS sget2(uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define nonDNG 0 #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords, int maxlen) { line[maxlen - 1] = 0; char *p = line; int nwords = 0; while (1) { while (isspace(*p)) p++; if (*p == '\0') return nwords; words[nwords++] = p; while (!isspace(*p) && *p != '\0') p++; if (*p == '\0') return nwords; *p++ = '\0'; if (nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f) { if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data) { if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03" "\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5" "\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53" "\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea" "\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3" "\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7" "\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63" "\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd" "\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = {0xff, 0xff}; fread(str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4(uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = {0xff, 0xff, 0xff, 0xff}; fread(str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float(int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal(int type) { union { char c[8]; double d; } u, v; int i, rev; switch (type) { case 3: return (unsigned short)get2(); case 4: return (unsigned int)get4(); case 5: u.d = (unsigned int)get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short)get2(); case 9: return (signed int)get4(); case 10: u.d = (signed int)get4(); v.d = (signed int)get4(); return u.d / (v.d ? v.d : 1); case 11: return int_to_float(get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i = 0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts(ushort *pixel, unsigned count) { if (fread(pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)pixel, (char *)pixel, count * 2); } void CLASS cubic_spline(const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len); if (!A) return; A[0] = (float *)(A + 2 * len); for (i = 1; i < 2 * len; i++) A[i] = A[0] + 2 * len * i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len - 1; i > 0; i--) { b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); d[i - 1] = x[i] - x[i - 1]; } for (i = 1; i < len - 1; i++) { A[i][i] = 2 * (d[i - 1] + d[i]); if (i > 1) { A[i][i - 1] = d[i - 1]; A[i - 1][i] = d[i - 1]; } A[i][len - 1] = 6 * (b[i + 1] - b[i]); } for (i = 1; i < len - 2; i++) { float v = A[i + 1][i] / A[i][i]; for (j = 1; j <= len - 1; j++) A[i + 1][j] -= v * A[i][j]; } for (i = len - 2; i > 0; i--) { float acc = 0; for (j = i; j <= len - 2; j++) acc += A[i][j] * c[j]; c[i] = (A[i][len - 1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len - 1; j++) { if (x[j] <= x_out && x_out <= x[j + 1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v + ((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free(A); } void CLASS canon_600_fixed_wb(int temp) { static const short mul[4][5] = { {667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}}; int lo, hi, i; float frac = 0; for (lo = 4; --lo;) if (*mul[lo] <= temp) break; for (hi = 0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i = 1; i < 5; i++) pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color(int ratio[2], int mar) { int clipped = 0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar * 4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = {0, 0}; int test[8], total[2][8], ratio[2][2], stat[2]; memset(&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row = 14; row < height - 14; row += 4) for (col = 10; col < width; col += 2) { for (i = 0; i < 8; i++) test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1)); for (i = 0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i = 0; i < 4; i++) if (abs(test[i] - test[i + 4]) > 50) goto next; for (i = 0; i < 2; i++) { for (j = 0; j < 4; j += 2) ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j]; stat[i] = canon_600_color(ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i = 0; i < 2; i++) if (stat[i]) for (j = 0; j < 2; j++) test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10; for (i = 0; i < 8; i++) total[st][i] += test[i]; count[st]++; next:; } if (count[0] | count[1]) { st = count[0] * 200 < count[1]; for (i = 0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409}, {-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007}, {-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528}, {-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}}; int t = 0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t = 1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t = 3; else if (yc <= 2) t = 4; } if (flash_used) t = 5; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow = row = 0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row * raw_width; for (dp = data; dp < data + 1120; dp += 10, pix += 8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6); } if ((row += 2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}}; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { if ((val = BAYER(row, col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row, col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row = 0; row < 100; row++) { fseek(ifp, row * 3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff(int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf = 0; static int vbits = 0, reset = 0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar)c; vbits += 8; } c = bitbuf << (32 - vbits) >> (32 - nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar)huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n, 0) #define gethuff(h) getbithuff(*h, h + 1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort *CLASS make_decoder_ref(const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max = 16; max && !count[max]; max--) ; huff = (ushort *)calloc(1 + (1 << max), sizeof *huff); merror(huff, "make_decoder()"); huff[0] = max; for (h = len = 1; len <= max; len++) for (i = 0; i < count[len]; i++, ++*source) for (j = 0; j < 1 << (max - len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); } void CLASS crw_init_tables(unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff}, {0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff}, {0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff}, }; static const uchar second_tree[3][180] = { {0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04, 0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0, 0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29, 0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9, 0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91, 0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4, 0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7, 0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64, 0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3, 0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff}, {0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03, 0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32, 0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61, 0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59, 0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56, 0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85, 0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82, 0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9, 0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64, 0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff}, {0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05, 0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22, 0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58, 0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48, 0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88, 0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94, 0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a, 0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62, 0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1, 0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}}; if (table > 2) table = 2; huff[0] = make_decoder(first_tree[table]); huff[1] = make_decoder(second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret = 1, i; fseek(ifp, 0, SEEK_SET); fread(test, 1, sizeof test, ifp); for (i = 540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i + 1]) return 1; ret = 0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2]; crw_init_tables(tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; nblocks = MIN(8, raw_height - row) * raw_width >> 6; for (block = 0; block < nblocks; block++) { memset(diffbuf, 0, sizeof diffbuf); for (i = 0; i < 64; i++) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i = 0; i < 64; i++) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek(ifp, 26 + row * raw_width / 4, SEEK_SET); for (prow = pixel, i = 0; i < raw_width * 2; i++) { c = fgetc(ifp); for (r = 0; r < 8; r += 2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free(huff[c]); throw; } #endif FORC(2) free(huff[c]); } int CLASS ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end(struct jhead *jh) { int c; FORC4 if (jh->free[c]) free(jh->free[c]); free(jh->row); } int CLASS ljpeg_diff(ushort *huff) { int len, diff; if (!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; return diff; } ushort *CLASS ljpeg_row(int jrow, struct jhead *jh) { int col, c, diff, pred, spred = 0; ushort mark = 0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits - 1); if (jrow) { fseek(ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1); for (col = 0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff(jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0; struct jhead jh; ushort *rp; if (!ljpeg_start(&jh, 0)) return; if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if (jh.clrs == 4 && jwide >= raw_width * 2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2; for (jcol = 0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow * jwide + jcol; i = jidx / (cr2_slice[1] * raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1] * raw_height); row = jidx / cr2_slice[1 + j]; col = jidx % cr2_slice[1 + j] + i * cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--, raw_width); if (row > raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 3); #endif if ((unsigned)row < raw_height) RAW(row, col) = val; if (++col >= raw_width) col = (row++, 0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif ljpeg_end(&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp = 0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c; int v[3] = {0, 0, 0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start(&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if (load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol = slice = 0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width - 1) ecol = raw_width & -2; for (row = 0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short(*)[4])image + row * width; for (col = scol; col < ecol; col += 2, jcol += jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *)ljpeg_row(jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC(jh.clrs - 2) { ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else #endif { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 16384; ip[col][2] = rp[jcol + jh.clrs - 1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end(&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp = model2; *cp && !isdigit(*cp); cp++) ; sscanf(cp, "%d.%d.%d", v, v + 1, v + 2); ver = (v[0] * 1000 + v[1]) * 1000 + v[2]; hue = (jh.sraw + 1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short(*)[4])image; rp = ip[0]; for (row = 0; row < height; row++, ip += width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col = 0; col < width; col += 2) for (c = 1; c < 3; c++) if (row == height - 1) { ip[col][c] = ip[col - width][c]; } else { ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1; } } for (col = 1; col < width; col += 2) for (c = 1; c < 3; c++) if (col == width - 1) ip[col][c] = ip[col - 1][c]; else ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)) #endif for (; rp < ip[0]; rp += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14); pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14); pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } height = saved_h; width = saved_w; #endif ljpeg_end(&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row, col) = curve[**rp]; *rp += tiff_samples; } else { #ifdef LIBRAW_LIBRARY_BUILD if (row < raw_height && col < raw_width) FORC(tiff_samples) image[row * raw_width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #else if (row < height && col < width) FORC(tiff_samples) image[row * width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #endif } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct(struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = {0}; static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; if (!cs[0]) FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2; memset(work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0]; for (i = 1; i < 64; i++) { len = gethuff(jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len - 1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c]; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); if (!ljpeg_start(&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN(is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow = 0; jrow + 7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol = 0; jcol + 7 < jh.wide; jcol += 8) { ljpeg_idct(&jh); rp = jh.idct; row = trow + jcol / tile_width + jrow * 2; col = tcol + jcol % tile_width; for (i = 0; i < 16; i += 2) for (j = 0; j < 8; j++) adobe_copy_pixel(row + i, col + j, &rp); } } break; case 0xc3: for (row = col = jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); for (jcol = 0; jcol < jwide; jcol++) { adobe_copy_pixel(trow + row, tcol + col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif fseek(ifp, save + 4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end(&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel); merror(pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts(pixel, raw_width * tiff_samples); else { getbits(-1); for (col = 0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp = pixel, col = 0; col < raw_width; col++) adobe_copy_pixel(row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek(ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek(ifp, data_offset, SEEK_SET); getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for (int row = 0; row < raw_height; row++) { int red = fread(buf, 1, bufsize, ifp); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (tiff_bps <= 8) for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } else for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */ 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */ 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}, {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */ 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}, {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */ 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */ 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}, {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */ 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff; fseek(ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek(ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts(vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize - 1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i = 0; i < csize; i++) curve[i * step] = get2(); for (i = 0; i < max; i++) curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; fseek(ifp, meta_offset + 562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts(curve, max = csize); while (curve[max - 2] == curve[max - 1]) max--; huff = make_decoder(nikon_tree[tree]); fseek(ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min = row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free(huff); huff = make_decoder(nikon_tree[tree + 1]); max += (min = 16) << 1; } for (col = 0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len - shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(huff); throw; } #endif free(huff); } void CLASS nikon_yuv_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf = 0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; } for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8; FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705 * yuv[3]; rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3]; rgb[2] = yuv[b] + 1.732446 * yuv[2]; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = {0x00, 0x55, 0xaa, 0xff}; memset(histo, 0, sizeof histo); fseek(ifp, -2000, SEEK_END); for (i = 0; i < 2000; i++) histo[fgetc(ifp)]++; for (i = 0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek(ifp, 0, SEEK_SET); for (i = 0; i < 1024; i++) { fread(t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { {0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}}; fseek(ifp, 3072, SEEK_SET); fread(dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i = 0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy(make, table[i].t_make); strcpy(model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek(ifp, -sizeof tail, SEEK_END); fread(tail, 1, sizeof tail, ifp); for (nz = i = 0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)malloc(thumb_length); merror(thumb, "ppm_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread(thumb, 1, thumb_length, ifp); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)calloc(thumb_length, 2); merror(thumb, "ppm16_thumb()"); read_shorts((ushort *)thumb, thumb_length); for (i = 0; i < thumb_length; i++) thumb[i] = ((ushort *)thumb)[i] >> 8; fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = {"012", "102"}; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width * thumb_height; thumb = (char *)calloc(colors, thumb_length); merror(thumb, "layer_thumb()"); fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread(thumb, thumb_length, colors, ifp); for (i = 0; i < thumb_length; i++) FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp); free(thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *)calloc(thumb_length, 2); merror(thumb, "rollei_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts(thumb, thumb_length); for (i = 0; i < thumb_length; i++) { putc(thumb[i] << 3, ofp); putc(thumb[i] >> 5 << 2, ofp); putc(thumb[i] >> 11 << 3, ofp); } free(thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width > 32767 || raw_height > 32767) throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixel = raw_width*(raw_height+7); isix = raw_width * raw_height * 5 / 8; while (fread(pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i = 0; i < 10; i += 2) { todo[i] = iten++; todo[i + 1] = pixel[i] << 8 | pixel[i + 1]; buffer = pixel[i] >> 2 | buffer << 6; } for (; i < 16; i += 2) { todo[i] = isix++; todo[i + 1] = buffer >> (14 - i) * 5; } for (i = 0; i < 16; i += 2) if(todo[i] < maxpixel) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); else derror(); } maximum = 0x3ff; } int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; } void CLASS phase_one_flat_field(int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts(head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *)calloc(nc * wide, sizeof *mrow); merror(mrow, "phase_one_flat_field()"); for (y = 0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) { num = is_float ? getreal(11) : get2() / 32768.0; if (y == 0) mrow[c * wide + x] = num; else mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5]; } if (y == 0) continue; rend = head[1] + y * head[5]; for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++) { for (x = 1; x < wide; x++) { for (c = 0; c < nc; c += 2) { mult[c] = mrow[c * wide + x - 1]; mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4]; } cend = head[0] + x * head[4]; for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++) { c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0; if (!(c & 1)) { c = RAW(row, col) * mult[c]; RAW(row, col) = LIM(c, 0, 65535); } for (c = 0; c < nc; c += 2) mult[c] += mult[c + 1]; } } for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) mrow[c * wide + x] += mrow[(c + 1) * wide + x]; } } free(mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff = INT_MAX, off_412 = 0; /* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2}, {0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Phase One correction...\n")); #endif fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i = 0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i = 0; i < 0x10000; i++) { num = (poly[5] * i + poly[3]) * i + poly[1]; curve[i] = LIM(num, 0, 65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i = 0; i < 4; i++) poly[i] = getreal(11); for (i = 0; i < 0x10000; i++) { for (num = 0, j = 4; j--;) num = num * i + poly[j]; curve[i] = LIM(num + i, 0, 65535); } apply: /* apply to whole image */ for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1) * ph1.split_col; col < raw_width; col++) RAW(row, col) = curve[RAW(row, col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row = 0; row < raw_height; row++) if (FC(row - top_margin, col - left_margin) == 1) { for (sum = i = 0; i < 4; i++) sum += val[i] = raw(row + dir[i][0], col + dir[i][1]); for (max = i = 0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row, col) = (sum - val[max]) / 3.0 + 0.5; } else { for (sum = 0, i = 8; i < 12; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row - top_margin, col - left_margin) != 1) * 4; for (sum = 0, i = j; i < j + 8; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field(1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field(0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field(0, 4); } else if (tag == 0x412) { fseek(ifp, 36, SEEK_CUR); diff = abs(get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1 + i] = lc[qr][qc][i]; cf[1 + i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = {{1, 1}, {1, 1}}; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col); RAW(row, col) = LIM(i, 0, 65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1 + i] = ref[i]; cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek(ifp, save, SEEK_SET); } if (off_412) { fseek(ifp, off_412, SEEK_SET); for (i = 0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6); merror(yval[0], "phase_one_correct()"); yval[1] = (float *)(yval[0] + head[1] * head[3]); xval[0] = (ushort *)(yval[1] + head[2] * head[4]); xval[1] = (ushort *)(xval[0] + head[1] * head[3]); get2(); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) yval[i][j] = getreal(11); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) xval[i][j] = get2(); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { cfrac = (float)col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row, col) * 0.5; for (i = cip; i < cip + 2; i++) { for (k = j = 0; j < head[1]; j++) if (num < xval[0][k = head[1] * i + j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]); mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac); } i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row, col) = LIM(i, 0, 65535); } } free(yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek(ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555 : 0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()"); if (ph1.black_col) { fseek(ifp, ph1.black_col, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2); } if (ph1.black_row) { fseek(ifp, ph1.black_row, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2); } } #endif fseek(ifp, data_offset, SEEK_SET); read_shorts(raw_image, raw_width * raw_height); if (ph1.format) for (i = 0; i < raw_width * raw_height; i += 2) { a = raw_image[i + 0] ^ akey; b = raw_image[i + 1] ^ bkey; raw_image[i + 0] = (a & t_mask) | (b & ~t_mask); raw_image[i + 1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff(int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf = 0; static int vbits = 0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64 - vbits) >> (64 - nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar)huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n, 0) #define ph1_huff(h) ph1_bithuff(*h, h + 1) void CLASS phase_one_load_raw_c() { static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13}; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short(*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2); merror(pixel, "phase_one_load_raw_c()"); offset = (int *)(pixel + raw_width); fseek(ifp, strip_offset, SEEK_SET); for (row = 0; row < raw_height; row++) offset[row] = get4(); c_black = (short(*)[2])(offset + raw_height); fseek(ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts((ushort *)c_black[0], raw_height * 2); r_black = c_black + raw_height; fseek(ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts((ushort *)r_black[0], raw_width * 2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort)); } #endif for (i = 0; i < 256; i++) curve[i] = i * i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col = 0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i = 0; i < 2; i++) { for (j = 0; j < 5 && !ph1_bits(1); j++) ; if (j--) len[i] = length[j * 2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col = 0; col < raw_width; col++) { int shift = ph1.format == 8 ? 0 : 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row, col) = i; } #else if (ph1.format == 8) memmove(&RAW(row, 0), &pixel[0], raw_width * 2); else for (col = 0; col < raw_width; col++) RAW(row, col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start(&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *)calloc(raw_width, 3 * sizeof **back); merror(back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c * raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c + 3) & 3] = back[c]; for (col = 0; col < raw_width; col += 2) { for (s = 0; s < tiff_samples * 2; s += 2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s + c] = ph1_bits(len[c]); if ((diff[s + c] & (1 << (len[c] - 1))) == 0) diff[s + c] -= (1 << len[c]) - 1; if (diff[s + c] == 65535) diff[s + c] = -32768; } } for (s = col; s < col + 2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s - 2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s] / 2 - back[0][s - 2] / 2; break; } f = (row & 1) * 3 ^ ((col + s) & 1); FORC(tiff_samples) { pred += diff[(s & 1) * tiff_samples + c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row, s) = upix; if (image) { urow = row - top_margin + (c & 1); ucol = col - left_margin - ((c >> 1) & 1); ip = &image[urow * width + ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(back[4]); ljpeg_end(&jh); throw; } #endif free(back[4]); ljpeg_end(&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel = 0; unsigned tile = 0, r, c, row, col; if (!filters || !raw_image) { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r = 0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek(ifp, data_offset + 4 * tile++, SEEK_SET); fseek(ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters && raw_image) pixel = raw_image + r * raw_width; read_shorts(pixel, raw_width); if (!filters && image && (row = r - top_margin) < height) for (col = 0; col < width; col++) image[row * width + col][c] = pixel[col + left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free(pixel); } } void CLASS unpacked_load_raw() { int row, col, bits = 0; while (1 << ++bits < maximum) ; read_shorts(raw_image, raw_width * raw_height); if (maximum < 0xffff || load_flags) for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < maximum) ; for (row = raw_height - 1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM(shot_select, 1, 4) - 1; fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot = 0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); for (row = 0; row < raw_height; row++) { read_shorts(pixel, raw_width); if ((r = row - top_margin - (shot >> 1 & 1)) >= height) continue; for (col = 0; col < raw_width; col++) { if ((c = col - left_margin - (shot & 1)) >= width) continue; image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short)); merror(buf, "imacon_full_load_raw"); #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf, width * 3); unsigned short(*rowp)[4] = &image[row * width]; for (col = 0; col < width; col++) { rowp[col][0] = buf[col * 3]; rowp[col][1] = buf[col * 3 + 1]; rowp[col][2] = buf[col * 3 + 2]; rowp[col][3] = 0; } #else for (col = 0; col < width; col++) read_shorts(image[row * width + col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf = 0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height + 1) >> 1; for (irow = 0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits = 0, tiff_compress) fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET); else { fseek(ifp, 0, SEEK_END); fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col = 0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); RAW(row, col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom() { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek(ifp, 0xb0 - 0x20, SEEK_CUR); fread(&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = {0, 0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *)malloc(dwide * 2); merror(data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } #endif free(data); maximum = 0x3ff; if (strncmp(make, "OmniVision", 10)) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1)); merror(words, "canon_rmf_load_raw"); #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words, sizeof(int), raw_width / 3, ifp); for (col = 0; col < raw_width - 2; col += 3) { bits = words[col / 3]; FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #else for (col = 0; col < raw_width - 2; col += 3) { bits = get4(); FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits(int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4002]; static int vbits; #endif int byte; if (!nbits) return vbits = 0; if (!vbits) { fread(buf + load_flags, 1, 0x4000 - load_flags, ifp); fread(buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n = 0] = 0xc0c; for (i = 12; i--;) FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i; fseek(ifp, 7, SEEK_CUR); getbits(-1); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(acarry, 0, sizeof acarry); for (col = 0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++) ; low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12, huff)) == 12) high = getbits(16 - nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row, col - 2); else if (col < 2) pred = RAW(row - 2, col); else { w = RAW(row, col - 2); n = RAW(row - 2, col); nw = RAW(row - 2, col - 2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w - nw) > 32 || ABS(n - nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w - nw) > ABS(n - nw) ? w : n; } if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow = 0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col = 0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1; RAW(row, 1) = pixel[1] << 1; RAW(row, 1533) = pixel[765] << 1; } else for (col = row & 1; col < 1534; col += 2) RAW(row, col) = pixel[col / 2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89}; static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8}, {-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}}; static const short t_curve[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99, 101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261, 265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357, 361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453, 457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620, 631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866, 878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023}; int rb, row, col, sharp, val = 0; #ifdef LIBRAW_LIBRARY_BUILD if(width>640 || height > 480) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif getbits(-1); memset(pixel, 0x80, sizeof pixel); for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 2 + (row & 1); col < width + 2; col += 2) { val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val, 0, 255); if (col < 4) pixel[row][col - 2] = pixel[row + 1][~row & 1] = val; if (row == 2) pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val; } pixel[row][col] = val; } for (rb = 0; rb < 2; rb++) for (row = 2 + rb; row < height + 2; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) + ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val, 0, 255); if (row < 4) pixel[row - 2][col + 2] = val; if (col < 4) pixel[row + 2][col - 2] = val; } } for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100; pixel[row][col] = LIM(val, 0, 255); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = t_curve[pixel[row + 2][col + 2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char)getbithuff(8, huff[tree])) #define FORYX \ for (y = 1; y < 3; y++) \ for (x = col + 1; x >= col; x--) #define PREDICTOR \ (c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4) #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC optimize("no-aggressive-loop-optimizations") #endif #endif void CLASS kodak_radc_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD // All kodak radc images are 768x512 if (width > 768 || raw_width > 768 || height > 512 || raw_height > 512) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif static const signed char src[] = { 1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6, 8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2, 4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3, 3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7, 5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5, 3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0, 2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2, 2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55, 6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37}; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = {16, 16, 16}, mul[3], buf[3][3][386]; static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383}; for (i = 2; i < 12; i += 2) for (c = pt[i - 2]; c <= pt[i]; c++) curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5; for (s = i = 0; i < sizeof src; i += 2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1); getbits(-1); for (i = 0; i < sizeof(buf) / sizeof(short); i++) ((short *)buf)[i] = 2048; for (row = 0; row < height; row += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if (!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10 : 12; x = ~((~0u) << (s - 1)); val <<= 12 - s; for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r = 0; r <= !c; r++) { buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7; for (tree = 1, col = width / 2; col > 0;) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y = 0; y < 2; y++) for (x = 0; x < width / 2; x++) { val = (buf[c][y + 1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val; else RAW(row + r * 2 + y, x * 2 + y) = val; } memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c); } } for (y = row; y < row + 4; y++) for (x = 0; x < width; x++) if ((x + y) & 1) { r = x ? x - 1 : x + 1; s = x + 1 < width ? x + 1 : x - 1; val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2; if (val < 0) val = 0; RAW(y, x) = val; } } for (i = 0; i < height * width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread(jpeg_buffer, 1, 4096, ifp); swab(jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; int row, col; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress(&cinfo); longjmp(failure, 3); } buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if (data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf, "kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char *)malloc(width * 3); jpeg_create_decompress(&cinfo); merror(pixel_buf, "kodak_jpeg_load_raw"); fread(jpg_buf, data_size, 1, ifp); swab((char *)jpg_buf, (char *)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } } catch (...) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve(double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; unsigned sorder = order, ntags, opcode, deg, i, j, c; unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek(ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek(ifp, get4(), SEEK_CUR); continue; } fseek(ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek(ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i = 0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i = 0; i < 256; i++) { for (tot = j = 0; j <= deg; j++) tot += coeff[j] * pow(i / 255.0, (int)j); cur[c][i] = tot * 0xffff; } } order = sorder; } else { gamma_curve(1 / 2.4, 12.92, 1, 255); FORC3 memcpy(cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); while (trow < raw_height) { fseek(ifp, save += 4, SEEK_SET); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src(&cinfo, ifp); #endif jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < cinfo.output_width && tcol + col < width; col++) { FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { jpeg_destroy_decompress(&cinfo); throw; } #endif jpeg_abort_decompress(&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress(&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = {162, 192, 187, 92}; static const int add[4] = {0, 636, 424, 212}; uchar pixel[848]; int row, shift, col; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col = 0; col < width; col++) RAW(row, col) = (ushort)pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *)calloc(raw_width, sizeof *pixel); merror(pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, raw_width, ifp) < raw_width) derror(); for (col = 0; col < raw_width; col++) RAW(row, col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel); merror(pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek(ifp, raw_width * 32, SEEK_CUR); for (col = 0; col < width; col++) { y = pixel[col * 2]; cb = pixel[(col * 2 & -4) | 1] - 128; cr = pixel[(col * 2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel); merror(pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread(pixel, raw_width, 3, ifp) < 3) derror(); for (col = 0; col < width; col++) { y = pixel[width * 2 * (row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2) + 1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { {0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder(kodak_tree[c]); ns = (raw_height + 63) >> 5; pixel = (uchar *)malloc(raw_width * 32 + ns * 4); merror(pixel, "kodak_262_load_raw()"); strip = (int *)(pixel + raw_width * 32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek(ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col = 0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi - 2 : pi - raw_width - 1; pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi - 2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff(huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row, col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); FORC(2) free(huff[c]); } int CLASS kodak_65000_decode(short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf = 0; int save, bits = 0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i = 0; i < bsize; i += 2) { c = fgetc(ifp); if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12) { fseek(ifp, save, SEEK_SET); for (i = 0; i < bsize; i += 8) { read_shorts(raw, 6); out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j = 0; j < 6; j++) out[i + 2 + j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i = 0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j = 0; j < 32; j += 8) bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8)); bits += 32; } diff = bitbuf & (0xffff >> (16 - len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* 264 looks enough */ int row, col, len, pred[2], ret, i; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { pred[0] = pred[1] = 0; len = MIN(256, width - col); ret = kodak_65000_decode(buf, len); for (i = 0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if (idx >= 0 && idx < 0xffff) { if ((RAW(row, col + i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10; for (row = 0; row < height; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 128) { len = MIN(128, width - col); kodak_65000_decode(buf, len * 3); y[0][1] = y[1][1] = cb = cr = 0; for (bp = buf, i = 0; i < len; i += 2, bp += 2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) { if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits) derror(); ip = image[(row + j) * width + col + i + k]; FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[768], *bp; int row, col, len, c, i, rgb[3], ret; ushort *ip = image[0]; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { len = MIN(256, width - col); ret = kodak_65000_decode(buf, len * 3); memset(rgb, 0, sizeof rgb); for (bp = buf, i = 0; i < len; i++, ip += 4) #ifdef LIBRAW_LIBRARY_BUILD if (load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; colors = thumb_misc >> 5; for (row = 0; row < height; row++) for (col = 0; col < width; col++) read_shorts(image[row * width + col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt(unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p = 0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31; for (p = 4; p < 127; p++) pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31; for (p = 0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek(ifp, 200896, SEEK_SET); fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek(ifp, 164600, SEEK_SET); fread(head, 1, 40, ifp); sony_decrypt((unsigned *)head, 10, 1, key); for (i = 26; i-- > 22;) key = key << 8 | head[i]; fseek(ifp, data_offset, SEEK_SET); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; if (fread(pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key); for (col = 0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809, 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201}; int i, c, n, col, row, sum = 0; huff[0] = 15; for (n = i = 0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--;) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row = 0; row < raw_height + 1; row += 2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row, col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *)malloc(raw_width + 1); merror(data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread(data, 1, raw_width, ifp); for (dp = data, col = 0; col < raw_width - 30; dp += 16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++) ; #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i] = 0; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i = 0; i < 16; i++, col += 2) { unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2]; unsigned step = 1 << sh; RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr ? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000) : 0; } } else { for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1]; } #else for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1 : 31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum = 10000; #endif free(data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixels = raw_width*(raw_height+7); order = 0x4949; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, strip_offset + row * 4, SEEK_SET); fseek(ifp, data_offset + get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7 : 4; for (col = 0; col < raw_width; col += 16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; unsigned idest = RAWINDEX(row, col + c); unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0); if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); else derror(); if (c == 14) c = -1; } } } for (row = 0; row < raw_height - 1; row += 2) for (col = 0; col < raw_width - 1; col += 2) SWAP(RAW(row, col + 1), RAW(row + 1, col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709, 0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402}; ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n = i = 0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek(ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(), get2()); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4; prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green prow[~row & 1] = &RAW(row - 2, 0); // red and blue for (tab = 0; tab + 15 < raw_width; tab += 16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4 * ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row, tab - 2 + (col & 1)) : init) : (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1; diff = ph1_bits(i = len[c >> 2]); if (diff >> (i - 1)) diff -= 1 << i; diff = diff * (mag * 2 + 1) + mag; RAW(row, col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment(unsigned seg[2][2], int holes) { uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {3, 3, 0, 0, 63, 47, 31, 15, 0}}; int low, high = 0xff, carry = 0, nbits = 8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[] = {0, 0}; ushort data = 0, range = 0; fseek(ifp, seg[0][1] + 1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width * raw_height) seg[1][0] = raw_width * raw_height; for (pix = seg[0][0]; pix < seg[1][0]; pix++) { for (s = 0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits - 1)) - 1)) << 1) | ((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4); for (bin = 0; hist[s][bin + 5] > count; bin++) ; low = hist[s][bin + 5] * (high >> 4) >> 2; if (bin) high = hist[s][bin + 4] * (high >> 4) >> 2; high -= low; for (nbits = 0; high << nbits < 128; nbits++) ; range = (range + low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next + 1) & hist[s][0]; hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1) { if (bin < hist[s][1]) for (i = bin; i < hist[s][1]; i++) hist[s][i + 5]--; else if (next <= bin) for (i = hist[s][1]; i < bin; i++) hist[s][i + 5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if (pix >= raw_width * raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek(ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment(seg, 0); } int CLASS median4(int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i = 1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes(int holes) { int row, col, val[4]; for (row = 2; row < height - 2; row++) { if (!HOLE(row)) continue; for (col = 1; col < width - 1; col += 4) { val[0] = RAW(row - 1, col - 1); val[1] = RAW(row - 1, col + 1); val[2] = RAW(row + 1, col - 1); val[3] = RAW(row + 1, col + 1); RAW(row, col) = median4(val); } for (col = 2; col < width - 2; col += 4) if (HOLE(row - 2) || HOLE(row + 2)) RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1; else { val[0] = RAW(row, col - 2); val[1] = RAW(row, col + 2); val[2] = RAW(row - 2, col); val[3] = RAW(row + 2, col); RAW(row, col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek(ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar)fgetc(ifp); fseek(ifp, offset, SEEK_SET); for (i = 0; i < nseg * 2; i++) ((unsigned *)seg)[i] = get4() + data_offset * (i & 1); fseek(ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek(ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i = 0; i < nseg; i++) smal_decode_segment(seg + i, holes); if (holes) fill_holes(holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen(ifname, "rb"); #else in = (jas_stream_t *)ifp->make_jas_stream(); if (!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek(in, data_offset + 20, SEEK_SET); jimg = jas_image_decode(in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp(failure, 3); #else if (!jimg) { jas_stream_close(in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create(height / 2, width / 2); merror(jmat, "redcine_load_raw()"); img = (ushort *)calloc((height + 2), (width + 2) * 2); merror(img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat); data = jas_matrix_getref(jmat, 0, 0); for (row = c >> 1; row < height; row += 2) for (col = c & 1; col < width; col += 2) img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2]; } for (col = 1; col <= width; col++) { img[col] = img[2 * (width + 2) + col]; img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col]; } for (row = 0; row < height + 2; row++) { img[row * (width + 2)] = img[row * (width + 2) + 2]; img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3]; } for (row = 1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1)); for (; col <= width; col += 2, pix += 2) { c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c, 0, 4095); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag = true; } #endif free(img); jas_matrix_destroy(jmat); jas_image_destroy(jimg); jas_stream_close(in); #ifdef LIBRAW_LIBRARY_BUILD if (fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width * 2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row = 0; row < raw_height - top_margin * 2; row++) { for (col = 0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < height && c < width) BAYER(r, c) = RAW(row + top_margin, col + left_margin); } } } else { for (row = 0; row < height; row++) for (col = 0; col < width; col++) BAYER2(row, col) = RAW(row + top_margin, col + left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin + height; mask[0][3] += left_margin; mask[1][1] += left_margin + width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset(mblack, 0, sizeof mblack); for (zero = m = 0; m < 8; m++) for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++) for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++) { c = FC(row - top_margin, col - left_margin); mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)]; mblack[4 + c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4 + c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2); #endif for (row = 0; row < height; row++) for (col = 0; col < width; col++) if (BAYER(row, col) == 0) { tot = n = 0; for (r = row - 2; r <= row + 2; r++) for (c = col - 2; c <= col + 2; c++) if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c)) tot += (n++, BAYER(r, c)); if (n) BAYER(row, col) = tot / n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2); #endif } static const uchar xlat[2][256] = { {0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3, 0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d, 0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b, 0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b, 0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95, 0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b, 0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d, 0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43, 0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f, 0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad, 0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3, 0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17, 0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07, 0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7}, {0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9, 0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68, 0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95, 0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68, 0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42, 0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca, 0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87, 0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45, 0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94, 0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26, 0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe, 0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25, 0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65, 0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}}; void CLASS gamma_curve(double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2] = {0, 0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0) { for (i = 0; i < 48; i++) { g[2] = (bnd[0] + bnd[1]) / 2; if (g[0]) bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2]; else bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1 / g[0] - 1); } if (g[0]) g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1; else g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1; if (!mode--) { memcpy(gamm, g, sizeof gamm); return; } for (i = 0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double)i / imax) < 1) curve[i] = 0x10000 * (mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1)) : (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2])))); } } void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) work[i][j] = j == i + 3; for (j = 0; j < 3; j++) for (k = 0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i = 0; i < 3; i++) { num = work[i][i]; for (j = 0; j < 6; j++) if(fabs(num)>0.00001f) work[i][j] /= num; for (k = 0; k < 3; k++) { if (k == i) continue; num = work[k][i]; for (j = 0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i = 0; i < size; i++) for (j = 0; j < 3; j++) for (out[i][j] = k = 0; k < 3; k++) out[i][j] += work[j][k + 3] * in[i][k]; } void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j = 0; j < 3; j++) for (cam_rgb[i][j] = k = 0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i = 0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if (num > 0.00001) { for (j = 0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j = 0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse(cam_rgb, inverse, colors); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin {0.377, 0.345, 35.8}, // Light Skin {0.247, 0.251, 19.3}, // Blue Sky {0.337, 0.422, 13.3}, // Foliage {0.265, 0.240, 24.3}, // Blue Flower {0.261, 0.343, 43.1}, // Bluish Green {0.506, 0.407, 30.1}, // Orange {0.211, 0.175, 12.0}, // Purplish Blue {0.453, 0.306, 19.8}, // Moderate Red {0.285, 0.202, 6.6}, // Purple {0.380, 0.489, 44.3}, // Yellow Green {0.473, 0.438, 43.1}, // Orange Yellow {0.187, 0.129, 6.1}, // Blue {0.305, 0.478, 23.4}, // Green {0.539, 0.313, 12.0}, // Red {0.448, 0.470, 59.1}, // Yellow {0.364, 0.233, 19.8}, // Magenta {0.196, 0.252, 19.8}, // Cyan {0.310, 0.316, 90.0}, // White {0.310, 0.316, 59.1}, // Neutral 8 {0.310, 0.316, 36.2}, // Neutral 6.5 {0.310, 0.316, 19.8}, // Neutral 5 {0.310, 0.316, 9.0}, // Neutral 3.5 {0.310, 0.316, 3.1}}; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset(gmb_cam, 0, sizeof gmb_cam); for (sq = 0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++) for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++) { c = FC(row, col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row, col); BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse(gmb_xyz, inverse, NSQ); for (pass = 0; pass < 2; pass++) { for (raw_color = i = 0; i < colors; i++) for (j = 0; j < 3; j++) for (cam_xyz[i][j] = k = 0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff(rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq = 0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf(" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5)); puts(" } },"); } #undef NSQ } #endif void CLASS hat_transform(float *temp, float *base, int st, int size, int sc) { int i; for (i = 0; i < sc; i++) temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)]; for (; i + sc < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)]; for (; i < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size) #endif { temp = (float *)malloc((iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #endif // green equilibration void CLASS green_matching() { int i, j; double m1, m2, c1, c2; int o1_1, o1_2, o1_3, o1_4; int o2_1, o2_2, o2_3, o2_4; ushort(*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if (half_size || shrink) return; if (FC(oj, oi) != 3) oj++; if (FC(oj, oi) != 3) oi++; if (FC(oj, oi) != 3) oj--; img = (ushort(*)[4])calloc(height * width, sizeof *image); merror(img, "green_matching()"); memcpy(img, image, height * width * sizeof *image); for (j = oj; j < height - margin; j += 2) for (i = oi; i < width - margin; i += 2) { o1_1 = img[(j - 1) * width + i - 1][1]; o1_2 = img[(j - 1) * width + i + 1][1]; o1_3 = img[(j + 1) * width + i - 1][1]; o1_4 = img[(j + 1) * width + i + 1][1]; o2_1 = img[(j - 2) * width + i][3]; o2_2 = img[(j + 2) * width + i][3]; o2_3 = img[j * width + i - 2][3]; o2_4 = img[j * width + i + 2][3]; m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0; m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0; c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) + abs(o1_2 - o1_4)) / 6.0; c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) + abs(o2_2 - o2_4)) / 6.0; if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr)) { f = image[j * width + i][3] * m1 / m2; image[j * width + i][3] = f > 0xffff ? 0xffff : f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img = 0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2); #endif if (user_mul[0]) memcpy(pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset(dsum, 0, sizeof dsum); bottom = MIN(greybox[1] + greybox[3], height); right = MIN(greybox[0] + greybox[2], width); for (row = greybox[1]; row < bottom; row += 8) for (col = greybox[0]; col < right; col += 8) { memset(sum, 0, sizeof sum); for (y = row; y < row + 8 && y < bottom; y++) for (x = col; x < col + 8 && x < right; x++) FORC4 { if (filters) { c = fcol(y, x); val = BAYER2(y, x); } else val = image[y * width + x][c]; if (val > maximum - 25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c + 4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block:; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset(sum, 0, sizeof sum); for (row = 0; row < 8; row++) for (col = 0; col < 8; col++) { c = FC(row, col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c + 4]++; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy(pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f) { for (c = 0; c < 3; c++) pre_mul[c] /= cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf(stderr, " %f", pre_mul[c]); fputc('\n', stderr); } #endif if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1) { FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight * iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i = 0; i < size * 4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Correcting chromatic aberration...\n")); #endif for (c = 0; c < 4; c += 2) { if (aber[c] == 1) continue; img = (ushort *)malloc(size * sizeof *img); merror(img, "scale_colors()"); for (i = 0; i < size; i++) img[i] = image[i][c]; for (row = 0; row < iheight; row++) { ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5; if (ur > iheight - 2) continue; fr -= ur; for (col = 0; col < iwidth; col++) { uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5; if (uc > iwidth - 2) continue; fc -= uc; pix = img + ur * iwidth + uc; image[row * iwidth + col][c] = (pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2); #endif } void CLASS pre_interpolate() { ushort(*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row = 0; row < 3; row++) for (col = 1; col < 4; col++) if (!(image[row * width + col][0] | image[row * width + col][2])) goto break2; break2: for (; row < height; row += 3) for (col = (col - 1) % 3 + 1; col < width - 1; col += 3) { img = image + row * width + col; for (c = 0; c < 3; c += 2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort(*)[4])calloc(height, width * sizeof *img); merror(img, "pre_interpolate()"); for (row = 0; row < height; row++) for (col = 0; col < width; col++) { c = fcol(row, col); img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c]; } free(image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1, 0) >> 1; row < height; row += 2) for (col = FC(row, 1) & 1; col < width; col += 2) image[row * width + col][1] = image[row * width + col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2); #endif } void CLASS border_interpolate(int border) { unsigned row, col, y, x, f, c, sum[8]; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { if (col == border && row >= border && row < height - border) col = width - border; memset(sum, 0, sizeof sum); for (y = row - 1; y != row + 2; y++) for (x = col - 1; x != col + 2; x++) if (y < height && x < width) { f = fcol(y, x); sum[f] += image[y * width + x][f]; sum[f + 4]++; } f = fcol(row, col); FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4]; } } void CLASS lin_interpolate_loop(int code[16][16][32], int size) { int row; for (row = 1; row < height - 1; row++) { int col, *ip; ushort *pix; for (col = 1; col < width - 1; col++) { int i; int sum[4]; pix = image[row * width + col]; ip = code[row % size][col % size]; memset(sum, 0, sizeof sum); for (i = *ip++; i--; ip += 3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i = colors; --i; ip += 2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size = 16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row = 0; row < size; row++) for (col = 0; col < size; col++) { ip = code[row][col] + 1; f = fcol(row, col); memset(sum, 0, sizeof sum); for (y = -1; y <= 1; y++) for (x = -1; x <= 1; x++) { shift = (y == 0) + (x == 0); color = fcol(row + y, col + x); if (color == f) continue; *ip++ = (width * y + x) * 4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c] > 0 ? 256 / sum[c] : 0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #endif lin_interpolate_loop(code, size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02, -2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02, -2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06, -2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128, -1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120, -1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11, -1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40, -1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10, -1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10, -1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128, +0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40, +0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08, +0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30, +0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40, +0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128, +1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10}, chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1}; ushort(*brow[5])[4], *pix; int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *)calloc(prow * pcol, 1280); merror(ip, "vng_interpolate()"); for (row = 0; row < prow; row++) /* Precalculate for VNG */ for (col = 0; col < pcol; col++) { code[row][col] = ip; for (cp = terms, t = 0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row + y1, col + x1); if (fcol(row + y2, col + x2) != color) continue; diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1; if (abs(y1 - y2) == diag && abs(x1 - x2) == diag) continue; *ip++ = (y1 * width + x1) * 4 + color; *ip++ = (y2 * width + x2) * 4 + color; *ip++ = weight; for (g = 0; g < 8; g++) if (grads & 1 << g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp = chood, g = 0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y * width + x) * 4; color = fcol(row, col); if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color) *ip++ = (y * width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow); merror(brow[4], "vng_interpolate()"); for (row = 0; row < 3; row++) brow[row] = brow[4] + row * width; for (row = 2; row < height - 2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if (!((row - 2) % 256)) RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1); #endif for (col = 2; col < width - 2; col++) { pix = image[row * width + col]; ip = code[row % prow][col % pcol]; memset(gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g = 1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy(brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset(sum, 0, sizeof sum); color = fcol(row, col); for (num = g = 0; g < 8; g++, ip += 2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); for (g = 0; g < 4; g++) brow[(g - 1) & 3] = brow[g]; } memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image); free(brow[4]); free(code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = {1, width, -1, -width, 1}; int row, col, diff[2], guess[2], c, d, i; ushort(*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 3; row < height - 3; row++) for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c]; diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 + (ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0] + guess[1]) >> 2); } } void CLASS cielab(ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if (cbrt[0] < -1.0f) #endif for (i = 0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f; } for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (xyz_cam[i][j] = k = 0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int)xyz[0])]; xyz[1] = cbrt[CLIP((int)xyz[1])]; xyz[2] = cbrt[CLIP((int)xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate(int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4] = {0, 0, 0, 0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1}, patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0}, {0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}}, dir[4] = {1, TS, TS + 1, TS - 1}; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][3], (*lix)[3]; float(*drv)[TS][TS], diff[6], tr; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if (width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row, col)]++; if (cstat[0] < 6 || cstat[0] > 10 || cstat[1] < 16 || cstat[1] > 24 || cstat[2] < 6 || cstat[2] > 10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 2; k++) for (int l = 0; l < 8; l++) allhex[i][j][k][l] = 32700; #endif cielab(0, 0); ndir = 4 << (passes > 1); buffer = (char *)malloc(TS * TS * (ndir * 11 + 6)); merror(buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6)); drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6)); homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6)); int minv = 0, maxv = 0, minh = 0, maxh = 0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) for (ng = d = 0; d < 10; d += 2) { g = fcol(row, col) == 1; if (fcol(row + orth[d], col + orth[d + 2]) == 1) ng = 0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g + 1) FORC(8) { v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1]; h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1]; minv = MIN(v, minv); maxv = MAX(v, maxv); minh = MIN(v, minh); maxh = MAX(v, maxh); allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width; allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 2; k++) for (int l = 0; l < 8; l++) if (allhex[i][j][k][l] > maxh + maxv * width + 1 || allhex[i][j][k][l] < minh + minv * width - 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row = 2; row < height - 2; row++) for (min = ~(max = 0), col = 2; col < width - 2; col++) { if (fcol(row, col) == 1 && (min = ~(max = 0))) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row - sgrow) % 3) { case 1: if (row < height - 3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if (retrycount++ > width * height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top = 3; top < height - 19; top += TS - 16) for (left = 3; left < width - 19; left += TS - 16) { mrow = MIN(top + TS, height - 3); mcol = MIN(left + TS, width - 3); for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) memcpy(rgb[0][row - top][col - left], image[row * width + col], 6); FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]); color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]); FORC(2) color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] + 33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]); FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]); } for (pass = 0; pass < passes; pass++) { if (pass == 1) memcpy(rgb += 4, buffer, 4 * sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row = top + 2; row < mrow - 2; row++) for (col = left + 2; col < mcol - 2; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][1]; for (d = 3; d < 6; d++) { rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left]; val = rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f]; rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3) for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3) { rix = &rgb[0][row - top][col - left]; h = fcol(row, col + 1); memset(diff, 0, sizeof diff); for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2) { for (c = 0; c < 2; c++, h ^= 2) { g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1]; color[h][d] = g + rix[i << c][h] + rix[-i << c][h]; if (d > 1) diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d - 1] < diff[d]) FORC(2) color[c * 2][d] = color[c * 2][d - 1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2); rix += TS * TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row = top + 3; row < mrow - 3; row++) for (col = left + 3; col < mcol - 3; col++) { if ((f = 2 - fcol(row, col)) == 1) continue; rix = &rgb[0][row - top][col - left]; c = (row - sgrow) % 3 ? TS : 1; h = 3 * (c ^ TS ^ 1); for (d = 0; d < 4; d++, rix += TS * TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) < 2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1]))) ? c : h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row = top + 2; row < mrow - 2; row++) if ((row - sgrow) % 3) for (col = left + 2; col < mcol - 2; col++) if ((col - sgcol) % 3) { rix = &rgb[0][row - top][col - left]; hex = allhex[row % 3][col % 3][1]; for (d = 0; d < ndir; d += 2, rix += TS * TS) if (hex[d] + hex[d + 1]) { g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3); } else { g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2); } } } rgb = (ushort(*)[TS][TS][3])buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d = 0; d < ndir; d++) { for (row = 2; row < mrow - 2; row++) for (col = 2; col < mcol - 2; col++) cielab(rgb[d][row][col], lab[row][col]); for (f = dir[d & 3], row = 3; row < mrow - 3; row++) for (col = 3; col < mcol - 3; col++) { lix = &lab[row][col]; g = 2 * lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) + SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir * TS * TS); for (row = 4; row < mrow - 4; row++) for (col = 4; col < mcol - 4; col++) { for (tr = FLT_MAX, d = 0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d = 0; d < ndir; d++) for (v = -1; v <= 1; v++) for (h = -1; h <= 1; h++) if (drv[d][row + v][col + h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height - top < TS + 4) mrow = height - top + 2; if (width - left < TS + 4) mcol = width - left + 2; for (row = MIN(top, 8); row < mrow - 8; row++) for (col = MIN(left, 8); col < mcol - 8; col++) { for (d = 0; d < ndir; d++) for (hm[d] = 0, v = -2; v <= 2; v++) for (h = -2; h <= 2; h++) hm[d] += homo[d][row + v][col + h]; for (d = 0; d < ndir - 4; d++) if (hm[d] < hm[d + 4]) hm[d] = 0; else if (hm[d] > hm[d + 4]) hm[d + 4] = 0; for (max = hm[0], d = 1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset(avg, 0, sizeof avg); for (d = 0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort(*pix)[4]; const int rowlimit = MIN(top + TS, height - 2); const int collimit = MIN(left + TS, width - 2); for (row = top; row < rowlimit; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < collimit; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort(*pix)[4]; ushort(*rix)[3]; short(*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4 * width; const unsigned rowlimit = MIN(top + TS - 1, height - 3); const unsigned collimit = MIN(left + TS - 1, width - 3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top + 1; row < rowlimit; row++) { pix = image + row * width + left; rix = &inout_rgb[row - top][0]; lix = &out_lab[row - top][0]; for (col = left + 1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row + 1, col); t1 = 2 - c; val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1); } else { t1 = -4 + c; /* -4+c: pixel of color c to the left */ t2 = 4 + c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short(*lix)[3]; short(*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = {-1, 1, -TS, TS}; const int rowlimit = MIN(top + TS - 2, height - 4); const int collimit = MIN(left + TS - 2, width - 4); int homogeneity; char(*homogeneity_map_p)[2]; memset(out_homogeneity_map, 0, 2 * TS * TS); for (row = top + 2; row < rowlimit; row++) { tr = row - top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction = 0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col = left + 2; col < collimit; col++) { tc = col - left; homogeneity_map_p++; for (direction = 0; direction < 2; direction++) { lix = ++lixs[direction]; for (i = 0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (direction = 0; direction < 2; direction++) { homogeneity = 0; for (i = 0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top + TS - 3, height - 5); const int collimit = MIN(left + TS - 3, width - 5); ushort(*pix)[4]; ushort(*rix[2])[3]; for (row = top + 3; row < rowlimit; row++) { tr = row - top; pix = &image[row * width + left + 2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col = left + 3; col < collimit; col++) { tc = col - left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction = 0; direction < 2; direction++) { hm[direction] = 0; for (i = tr - 1; i <= tr + 1; i++) { for (j = tc - 1; j <= tc + 1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4], r; char *buffer; ushort(*rgb)[TS][TS][3]; short(*lab)[TS][TS][3]; char(*homo)[TS][2]; int terminate_flag = 0; cielab(0, 0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag) #endif #endif { buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */ merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][2])(buffer + 24 * TS * TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top = 2; top < height - 5; top += TS - 6) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if (0 == omp_get_thread_num()) #endif if (callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7); if (rr) terminate_flag = 1; } #endif for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free(buffer); } #ifdef LIBRAW_LIBRARY_BUILD if (terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = {-1, 1, -TS, TS}; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][TS][3], (*lix)[3]; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("AHD interpolation...\n")); #endif cielab(0, 0); border_interpolate(5); buffer = (char *)malloc(26 * TS * TS); merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][TS])(buffer + 24 * TS * TS); for (top = 2; top < height - 5; top += TS - 6) for (left = 2; left < width - 5; left += TS - 6) { /* Interpolate green horizontally and vertically: */ for (row = top; row < top + TS && row < height - 2; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < left + TS && col < width - 2; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d = 0; d < 2; d++) for (row = top + 1; row < top + TS - 1 && row < height - 3; row++) for (col = left + 1; col < left + TS - 1 && col < width - 3; col++) { pix = image + row * width + col; rix = &rgb[d][row - top][col - left]; lix = &lab[d][row - top][col - left]; if ((c = 2 - FC(row, col)) == 1) { c = FC(row + 1, col); val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1); rix[0][2 - c] = CLIP(val); val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1); } else val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset(homo, 0, 2 * TS * TS); for (row = top + 2; row < top + TS - 2 && row < height - 4; row++) { tr = row - top; for (col = left + 2; col < left + TS - 2 && col < width - 4; col++) { tc = col - left; for (d = 0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i = 0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (d = 0; d < 2; d++) for (i = 0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row = top + 3; row < top + TS - 3 && row < height - 5; row++) { tr = row - top; for (col = left + 3; col < left + TS - 3 && col < width - 5; col++) { tc = col - left; for (d = 0; d < 2; d++) for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++) for (j = tc - 1; j <= tc + 1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free(buffer); } #endif #undef TS void CLASS median_filter() { ushort(*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ {1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0, 3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2}; for (pass = 1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Median filter pass %d...\n"), pass); #endif for (c = 0; c < 3; c += 2) { for (pix = image; pix < image + width * height; pix++) pix[0][3] = pix[0][c]; for (pix = image + width; pix < image + width * (height - 1); pix++) { if ((pix - image + 1) % width < 2) continue; for (k = 0, i = -width; i <= width; i += width) for (j = i - 1; j <= i + 1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i = 0; i < sizeof opt; i += 2) if (med[opt[i]] > med[opt[i + 1]]) SWAP(med[opt[i]], med[opt[i + 1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip = INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned)(colors - 3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2); #endif FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { FORCC if (image[row * width + col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row * width + col][c]; cam[1][c] = MIN(cam[0][c], clip); } for (i = 0; i < 2; i++) { FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j]; for (sum[i] = 0, c = 1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1] / sum[0]); for (c = 1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j]; FORCC image[row * width + col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rebuilding highlights...\n")); #endif grow = pow(2.0, 4 - highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc = 0, c = 1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *)calloc(high, wide * sizeof *map); merror(map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1); #endif memset(map, 0, high * wide * sizeof *map); for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE * SCALE) map[mrow * wide + mcol] = sum / wgt; } for (spread = 32 / grow; spread--;) { for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { if (map[mrow * wide + mcol]) continue; sum = count = 0; for (d = 0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y * wide + x] > 0) { sum += (1 + (d & 1)) * map[y * wide + x]; count += 1 + (d & 1); } } if (count > 3) map[mrow * wide + mcol] = -(sum + grow) / (count + grow); } for (change = i = 0; i < high * wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i = 0; i < high * wide; i++) if (map[i] == 0) map[i] = 1; for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow * wide + mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free(map); } #undef SCALE void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { #ifdef LIBRAW_IOSPACE_CHECK INT64 pos = ftell(ifp); INT64 fsize = ifp->size(); if(fsize < 12 || (fsize-pos) < 12) throw LIBRAW_EXCEPTION_IO_EOF; #endif *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4) fseek(ifp, get4() + base, SEEK_SET); } void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4() + base; if (tag == tlen) thumb_length = get4(); fseek(ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); } static float libraw_powf64l(float a, float b) { return powf_lim(a, b, 64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return libraw_powf64l(2.0, in / 64.0); } static float _CanonConvertEV(short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float)Frac; return ((float)Sign * ((float)EV + Frac_f)) / 32.0f; } unsigned CLASS setCanonBodyFeatures(unsigned id) { if (id == 0x03740000) // EOS M3 id = 0x80000374; else if (id == 0x03840000) // EOS M10 id = 0x80000384; else if (id == 0x03940000) // EOS M5 id = 0x80000394; else if (id == 0x04070000) // EOS M6 id = 0x80000407; else if (id == 0x03980000) // EOS M100 id = 0x80000398; imgdata.lens.makernotes.CamID = id; if ((id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) || // M5 (id == 0x80000407) || // M6 (id == 0x80000398) // M100 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ((id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return id; } void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if (maxlen < 16) return; // too short CameraInfo[0] = 0; CameraInfo[1] = 0; if (type == 4) { if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) || (maxlen == 171) || (maxlen == 264) || (maxlen > 400)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 3) << 2)); else if (maxlen == 72) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 1) << 2)); else if ((maxlen == 85) || (maxlen == 93)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 2) << 2)); else if ((maxlen == 96) || (maxlen == 104)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 4) << 2)); } switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); imgdata.other.CameraTemperature = 0.0f; break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if (iCanonFocalType >= maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if (iCanonCurFocal >= maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if (iCanonLensID >= maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if (iCanonMinFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if (iCanonMaxFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if (iCanonLens + 64 >= maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings() { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets(int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets(short WBCTversion) { if (WBCTversion == 0) for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x80000407) || // M6 (unique_id == 0x80000398) || // M100 (unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000))) // G1 X Mark III for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData(uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64l(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 | (unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 | (unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 | (unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures(unsigned long long id) { imgdata.lens.makernotes.CamID = id; if (id == 0x5330303638ULL) { strcpy(model, "E-M10MarkIII"); } if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 24, SEEK_CUR); tempAp = get2(); if (tempAp != 0) imgdata.other.CameraTemperature = (float)(tempAp - 128); tempAp = get2(); if (tempAp != -1) imgdata.other.FlashGN = ((float)tempAp) / 32; get2(); // fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8 - 32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x000c) { unsigned tS = get4(); sprintf (imgdata.shootinginfo.BodySerial, "%d", tS); } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x009a) { get4(); imgdata.sizes.raw_crop.cwidth = get4(); imgdata.sizes.raw_crop.cheight = get4(); imgdata.sizes.raw_crop.cleft = get4(); imgdata.sizes.raw_crop.ctop = get4(); } else if (tag == 0x00a9) { long int save1 = ftell(ifp); int c; fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(), get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4013) { get4(); imgdata.makernotes.canon.AFMicroAdjMode = get4(); imgdata.makernotes.canon.AFMicroAdjValue = ((float)get4()) / ((float)get4()); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek(ifp, save1 + (0x1e << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x41 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x46 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x23 << 1), SEEK_SET); Canon_WBpresets(2, 2); fseek(ifp, save1 + (0x4b << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek(ifp, save1 + (0x18 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x90 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x95 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x9a << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x27 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa4 << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x71 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x76 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x7b << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x4e << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x53 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa8 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek(ifp, save1 + (0x2b8 << 1), SEEK_SET); // offset 696 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek(ifp, save1 + (0x2cf << 1), SEEK_SET); // offset 719 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek(ifp, save1 + (0x2d3 << 1), SEEK_SET); // offset 723 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6 { if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000) || // G1 X Mark III (unique_id == 0x80000394) || // EOS M5 (unique_id == 0x80000398) || // EOS M100 (unique_id == 0x80000407)) // EOS M6 { fseek(ifp, save1 + (0x4f << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8, 24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets(2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { fseek(ifp, save1 + (0x4c << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xba << 1), SEEK_SET); Canon_WBCTpresets(2); // BCADT fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short } int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x67 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xbc << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } fseek(ifp, save1 + (0x1e3 << 1), SEEK_SET); // offset 483 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xd5 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek(ifp, save1 + (0x1fc << 1), SEEK_SET); // offset 508 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek(ifp, save1 + (0x2dc << 1), SEEK_SET); // offset 732 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D case 1560: case 1592: case 1353: case 1602: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x107 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek(ifp, save1 + (0x230 << 1), SEEK_SET); // offset 560 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek(ifp, save1 + (0x30e << 1), SEEK_SET); // offset 782 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek(ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: case 0x1322c: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO(ushort c) { int code[] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code) / sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar *)malloc(MAX(len, 128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10 * (table_buf[iLensData + 9] >> 2) * libraw_powf64l(4, (table_buf[iLensData + 9] & 0x03) - 2); if (table_buf[iLensData + 10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f); if (table_buf[iLensData + 10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07); if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures(unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333, "Mamiya"}, {329, "Universal"}, {330, "Hasselblad H1/H2"}, {332, "Contax"}, {336, "AFi"}, {327, "Mamiya"}, {324, "Universal"}, {325, "Hasselblad H1/H2"}, {326, "Contax"}, {335, "AFi"}, {340, "Mamiya"}, {337, "Universal"}, {338, "Hasselblad H1/H2"}, {339, "Contax"}, {323, "Mamiya"}, {320, "Universal"}, {322, "Hasselblad H1/H2"}, {321, "Contax"}, {334, "AFi"}, {369, "Universal"}, {370, "Mamiya"}, {371, "Hasselblad H1/H2"}, {372, "Contax"}, {373, "Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes(unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures(unsigned id) { ushort idx; static const struct { ushort scf[8]; /* scf[0] camera id scf[1] camera format scf[2] camera mount: Minolta A, Sony E, fixed, scf[3] camera type: DSLR, NEX, SLT, ILCE, ILCA, DSC scf[4] lens mount scf[5] tag 0x2010 group (0 if not used) scf[6] offset of Sony ISO in 0x2010 table, 0xffff if not valid scf[7] offset of ImageCount3 in 0x9050 table, 0xffff if not valid */ } SonyCamFeatures[] = { {256, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {257, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {258, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {259, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {260, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {261, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {262, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {263, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {264, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {265, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {266, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {267, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {268, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {269, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {270, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {271, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {272, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {273, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {274, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {275, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {276, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {277, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {278, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff}, {279, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff}, {280, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff}, {281, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff}, {282, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {283, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {284, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff}, {285, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff}, {286, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd}, {287, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd}, {288, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 1, 0x113e, 0x01bd}, {289, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd}, {290, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd}, {291, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd}, {292, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd}, {293, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 3, 0x11f4, 0x01bd}, {294, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1254, 0x01aa}, {295, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {296, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {297, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1254, 0xffff}, {298, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff}, {299, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {300, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {301, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {302, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 5, 0x1280, 0x01aa}, {303, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1280, 0x01aa}, {304, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {305, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1280, 0x01aa}, {306, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {307, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {308, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 6, 0x113c, 0xffff}, {309, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff}, {310, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff}, {311, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {312, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {313, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01aa}, {314, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {315, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {316, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {317, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff}, {318, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {319, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0}, {320, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {321, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {322, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {323, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {324, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {325, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {326, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {327, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {328, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {329, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {330, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {331, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {332, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {333, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {334, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {335, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {336, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {337, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {338, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {339, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0}, {340, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {341, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {342, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {343, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {344, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {345, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {346, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0}, {347, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb}, {348, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {349, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {350, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb}, {351, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {352, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {353, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0}, {354, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 8, 0x0346, 0x01cd}, {355, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {356, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {357, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd}, {358, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f}, {359, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {360, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd}, {361, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {362, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f}, {363, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {364, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {365, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 9, 0x0320, 0xffff}, }; imgdata.lens.makernotes.CamID = id; if (id == 2) { imgdata.lens.makernotes.CameraMount = imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; imgdata.makernotes.sony.group2010 = 0; imgdata.makernotes.sony.real_iso_offset = 0xffff; imgdata.makernotes.sony.ImageCount3_offset = 0xffff; return; } else idx = id - 256; if ((idx >= 0) && (idx < sizeof SonyCamFeatures / sizeof *SonyCamFeatures)) { if (!SonyCamFeatures[idx].scf[2]) return; imgdata.lens.makernotes.CameraFormat = SonyCamFeatures[idx].scf[1]; imgdata.lens.makernotes.CameraMount = SonyCamFeatures[idx].scf[2]; imgdata.makernotes.sony.SonyCameraType = SonyCamFeatures[idx].scf[3]; if (SonyCamFeatures[idx].scf[4]) imgdata.lens.makernotes.LensMount = SonyCamFeatures[idx].scf[4]; imgdata.makernotes.sony.group2010 = SonyCamFeatures[idx].scf[5]; imgdata.makernotes.sony.real_iso_offset = SonyCamFeatures[idx].scf[6]; imgdata.makernotes.sony.ImageCount3_offset = SonyCamFeatures[idx].scf[7]; } char *sbstr = strstr(software, " v"); if (sbstr != NULL) { sbstr += 2; imgdata.makernotes.sony.firmware = atof(sbstr); if ((id == 306) || (id == 311)) { if (imgdata.makernotes.sony.firmware < 1.2f) imgdata.makernotes.sony.ImageCount3_offset = 0x01aa; else imgdata.makernotes.sony.ImageCount3_offset = 0x01c0; } else if (id == 312) { if (imgdata.makernotes.sony.firmware < 2.0f) imgdata.makernotes.sony.ImageCount3_offset = 0x01aa; else imgdata.makernotes.sony.ImageCount3_offset = 0x01c0; } else if ((id == 318) || (id == 340)) { if (imgdata.makernotes.sony.firmware < 1.2f) imgdata.makernotes.sony.ImageCount3_offset = 0x01a0; else imgdata.makernotes.sony.ImageCount3_offset = 0x01b6; } } } void CLASS parseSonyLensType2(uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a) << 8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf))) void CLASS parseSonyLensFeatures(uchar a, uchar b) { ushort features; features = (((ushort)a) << 8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA"); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1); return; } #undef strnXcat void CLASS process_Sony_0x0116(uchar *buf, ushort len, unsigned id) { short bufx; if (((id == 257) || (id == 262) || (id == 269) || (id == 270)) && (len >= 2)) bufx = buf[1]; else if ((id >= 273) && (len >= 3)) bufx = buf[2]; else return; imgdata.other.BatteryTemperature = (float)(bufx - 32) / 1.8f; } void CLASS process_Sony_0x2010(uchar *buf, ushort len) { if ((!imgdata.makernotes.sony.group2010) || (imgdata.makernotes.sony.real_iso_offset == 0xffff) || (len < (imgdata.makernotes.sony.real_iso_offset + 2))) return; if (imgdata.other.real_ISO < 0.1f) { uchar s[2]; s[0] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset]]; s[1] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset + 1]]; imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f)); } } void CLASS process_Sony_0x9050(uchar *buf, ushort len, unsigned id) { ushort lid; uchar s[4]; int c; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (len < 2) return; if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(libraw_powf64l(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(libraw_powf64l(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (len <= 0x106) return; if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { if (len <= 0x108) return; parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if (len <= 0x10a) return; if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) { if (len <= 0x116) return; // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); } else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (len <= 0x117) return; parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); } if ((id == 347) || (id == 350) || (id == 354) || (id == 357) || (id == 358) || (id == 360) || (id == 362)) { if (len <= 0x8d) return; unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) { if (len <= 0xf4) return; unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { if (len <= 0x7f) return; unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } if ((imgdata.makernotes.sony.ImageCount3_offset != 0xffff) && (len >= (imgdata.makernotes.sony.ImageCount3_offset + 4))) { FORC4 s[c] = SonySubstitution[buf[imgdata.makernotes.sony.ImageCount3_offset + c]]; imgdata.makernotes.sony.ImageCount3 = sget4(s); } if (id == 362) { for (c = 0; c < 6; c++) { imgdata.makernotes.sony.TimeStamp[c] = SonySubstitution[buf[0x0066 + c]]; } } return; } void CLASS process_Sony_0x9400(uchar *buf, ushort len, unsigned id) { uchar s[4]; int c; short bufx = buf[0]; if (((bufx == 0x23) || (bufx == 0x24) || (bufx == 0x26)) && (len >= 0x1f)) { // 0x9400 'c' version if ((id == 358) || (id == 362) || (id == 365)) { imgdata.makernotes.sony.ShotNumberSincePowerUp = SonySubstitution[buf[0x0a]]; } else { FORC4 s[c] = SonySubstitution[buf[0x0a + c]]; imgdata.makernotes.sony.ShotNumberSincePowerUp = sget4(s); } imgdata.makernotes.sony.Sony0x9400_version = 0xc; imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x09]]; FORC4 s[c] = SonySubstitution[buf[0x12 + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x16]]; // shots FORC4 s[c] = SonySubstitution[buf[0x1a + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_SequenceLength2 = SonySubstitution[buf[0x1e]]; // files } else if ((bufx == 0x0c) && (len >= 0x1f)) { // 0x9400 'b' version imgdata.makernotes.sony.Sony0x9400_version = 0xb; FORC4 s[c] = SonySubstitution[buf[0x08 + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s); FORC4 s[c] = SonySubstitution[buf[0x0c + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]]; imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x1e]]; } else if ((bufx == 0x0a) && (len >= 0x23)) { // 0x9400 'a' version imgdata.makernotes.sony.Sony0x9400_version = 0xa; FORC4 s[c] = SonySubstitution[buf[0x08 + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s); FORC4 s[c] = SonySubstitution[buf[0x0c + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]]; imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x22]]; } else return; } void CLASS process_Sony_0x9402(uchar *buf, ushort len) { if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_SLT) || (imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA)) return; if (len < 5) return; short bufx = buf[0x00]; if ((bufx == 0x05) || (bufx == 0xff) || (buf[0x02] != 0xff)) return; imgdata.other.AmbientTemperature = (float)((short)SonySubstitution[buf[0x04]]); return; } void CLASS process_Sony_0x9403(uchar *buf, ushort len) { if (len < 6) return; short bufx = SonySubstitution[buf[4]]; if ((bufx == 0x00) || (bufx == 0x94)) return; imgdata.other.SensorTemperature = (float)((short)SonySubstitution[buf[5]]); return; } void CLASS process_Sony_0x9406(uchar *buf, ushort len) { if (len < 6) return; short bufx = buf[0]; if ((bufx != 0x01) && (bufx != 0x08) && (bufx != 0x1b)) return; bufx = buf[2]; if ((bufx != 0x08) && (bufx != 0x1b)) return; imgdata.other.BatteryTemperature = (float)(SonySubstitution[buf[5]] - 32) / 1.8f; return; } void CLASS process_Sony_0x940c(uchar *buf, ushort len) { if ((imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_ILCE) && (imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_NEX)) return; if (len <= 0x000a) return; ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x940e(uchar *buf, ushort len, unsigned id) { if (((id == 286) || (id == 287) || (id == 294)) && (len >= 0x017e)) { imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x017d]]; } else if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA) && (len >= 0x0051)) { imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x0050]]; } else return; if (imgdata.makernotes.sony.AFMicroAdjValue != 0) imgdata.makernotes.sony.AFMicroAdjOn = 1; } void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x0116, ushort &table_buf_0x0116_len, uchar *&table_buf_0x2010, ushort &table_buf_0x2010_len, uchar *&table_buf_0x9050, ushort &table_buf_0x9050_len, uchar *&table_buf_0x9400, ushort &table_buf_0x9400_len, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_len, uchar *&table_buf_0x9403, ushort &table_buf_0x9403_len, uchar *&table_buf_0x9406, ushort &table_buf_0x9406_len, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_len, uchar *&table_buf_0x940e, ushort &table_buf_0x940e_len) { ushort lid; uchar *table_buf; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x0116_len) { process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, unique_id); free(table_buf_0x0116); table_buf_0x0116_len = 0; } if (table_buf_0x2010_len) { process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len); free(table_buf_0x2010); table_buf_0x2010_len = 0; } if (table_buf_0x9050_len) { process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, unique_id); free(table_buf_0x9050); table_buf_0x9050_len = 0; } if (table_buf_0x9400_len) { process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id); free(table_buf_0x9400); table_buf_0x9400_len = 0; } if (table_buf_0x9402_len) { process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len); free(table_buf_0x9402); table_buf_0x9402_len = 0; } if (table_buf_0x9403_len) { process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len); free(table_buf_0x9403); table_buf_0x9403_len = 0; } if (table_buf_0x9406_len) { process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len); free(table_buf_0x9406); table_buf_0x9406_len = 0; } if (table_buf_0x940c_len) { process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len); free(table_buf_0x940c); table_buf_0x940c_len = 0; } if (table_buf_0x940e_len) { process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, unique_id); free(table_buf_0x940e); table_buf_0x940e_len = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if ((!dng_writer) || (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); if (len == 5478) { imgdata.makernotes.sony.AFMicroAdjValue = table_buf[304] - 20; imgdata.makernotes.sony.AFMicroAdjOn = (((table_buf[305] & 0x80) == 0x80) ? 1 : 0); imgdata.makernotes.sony.AFMicroAdjRegisteredLenses = table_buf[305] & 0x7f; } } break; default: // CameraInfo2 & 3 if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if ((tag == 0x3000) && (len < 256000)) { uchar *table_buf_0x3000; table_buf_0x3000 = (uchar *)malloc(len); fread(table_buf_0x3000, len, 1, ifp); for (int i = 0; i < 20; i++) imgdata.makernotes.sony.SonyDateTime[i] = table_buf_0x3000[6 + i]; } else if (tag == 0x0116 && len < 256000) { table_buf_0x0116 = (uchar *)malloc(len); table_buf_0x0116_len = len; fread(table_buf_0x0116, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, imgdata.lens.makernotes.CamID); free(table_buf_0x0116); table_buf_0x0116_len = 0; } } else if (tag == 0x2010 && len < 256000) { table_buf_0x2010 = (uchar *)malloc(len); table_buf_0x2010_len = len; fread(table_buf_0x2010, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len); free(table_buf_0x2010); table_buf_0x2010_len = 0; } } else if (tag == 0x201a) { imgdata.makernotes.sony.ElectronicFrontCurtainShutter = get4(); } else if (tag == 0x201b) { uchar uc; fread(&uc, 1, 1, ifp); imgdata.shootinginfo.FocusMode = (short)uc; } else if (tag == 0x202c) { imgdata.makernotes.sony.MeteringMode2 = get2(); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_len = len; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_len = 0; } } else if (tag == 0x9400 && len < 256000) { table_buf_0x9400 = (uchar *)malloc(len); table_buf_0x9400_len = len; fread(table_buf_0x9400, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id); free(table_buf_0x9400); table_buf_0x9400_len = 0; } } else if (tag == 0x9402 && len < 256000) { table_buf_0x9402 = (uchar *)malloc(len); table_buf_0x9402_len = len; fread(table_buf_0x9402, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len); free(table_buf_0x9402); table_buf_0x9402_len = 0; } } else if (tag == 0x9403 && len < 256000) { table_buf_0x9403 = (uchar *)malloc(len); table_buf_0x9403_len = len; fread(table_buf_0x9403, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len); free(table_buf_0x9403); table_buf_0x9403_len = 0; } } else if ((tag == 0x9405) && (len < 256000) && (len > 0x64)) { uchar *table_buf_0x9405; table_buf_0x9405 = (uchar *)malloc(len); short bufx = table_buf_0x9405[0x0]; fread(table_buf_0x9405, len, 1, ifp); if (imgdata.other.real_ISO < 0.1f) { if ((bufx == 0x25) || (bufx == 0x3a) || (bufx == 0x76) || (bufx == 0x7e) || (bufx == 0x8b) || (bufx == 0x9a) || (bufx == 0xb3) || (bufx == 0xe1)) { uchar s[2]; s[0] = SonySubstitution[table_buf_0x9405[0x04]]; s[1] = SonySubstitution[table_buf_0x9405[0x05]]; imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f)); } } free(table_buf_0x9405); } else if (tag == 0x9406 && len < 256000) { table_buf_0x9406 = (uchar *)malloc(len); table_buf_0x9406_len = len; fread(table_buf_0x9406, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len); free(table_buf_0x9406); table_buf_0x9406_len = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_len = len; fread(table_buf_0x940c, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len); free(table_buf_0x940c); table_buf_0x940c_len = 0; } } else if (tag == 0x940e && len < 256000) { table_buf_0x940e = (uchar *)malloc(len); table_buf_0x940e_len = len; fread(table_buf_0x940e, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, imgdata.lens.makernotes.CamID); free(table_buf_0x940e); table_buf_0x940e_len = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } else if ((tag == 0xb02b) && !imgdata.sizes.raw_crop.cwidth && (len == 2)) { imgdata.sizes.raw_crop.cheight = get4(); imgdata.sizes.raw_crop.cwidth = get4(); } } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x0116; ushort table_buf_0x0116_len = 0; uchar *table_buf_0x2010; ushort table_buf_0x2010_len = 0; uchar *table_buf_0x9050; ushort table_buf_0x9050_len = 0; uchar *table_buf_0x9400; ushort table_buf_0x9400_len = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_len = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_len = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_len = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_len = 0; uchar *table_buf_0x940e; ushort table_buf_0x940e_len = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if (len > 8 && pos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } tag |= uptag << 16; if (len > 100 * 1024 * 1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16, len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes(tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) && !strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)) imgdata.other.CameraTemperature = getreal(type); if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } else if (tag == 0x00b9) { uchar uc; int8_t sc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTune = uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneIndex = uc; fread(&sc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneAdj = sc; } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * libraw_powf64l(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { short nWB, tWB; int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) && strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2040) || (tag == 0x2050) || (tag == 0x3000)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) || (((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; if ((tag >= 0x20400101) && (tag <= 0x20400111)) { if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } for (i = 64; i < 256; i++) { imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } else if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } else if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } else if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } else if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } else if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } else { switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 | (unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x20200306: { uchar uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.olympus.AFFineTune = uc; } break; case 0x20200307: FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2(); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float)temp; else imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x000d) { imgdata.makernotes.pentax.FocusMode = get2(); } else if (tag == 0x000e) { imgdata.makernotes.pentax.AFPointSelected = get2(); } else if (tag == 0x000f) { imgdata.makernotes.pentax.AFPointsInFocus = getint(type); } else if (tag == 0x0010) { imgdata.makernotes.pentax.FocusPosition = get2(); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x0034) { uchar uc; FORC4 { fread(&uc, 1, 1, ifp); imgdata.makernotes.pentax.DriveMode[c] = uc; } } else if (tag == 0x0038) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); } else if (tag == 0x0039) { imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x0072) { imgdata.makernotes.pentax.AFAdjustment = get2(); } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float)temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010, table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400, table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403, table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c, table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len); } next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x0116; ushort table_buf_0x0116_len = 0; uchar *table_buf_0x2010; ushort table_buf_0x2010_len = 0; uchar *table_buf_0x9050; ushort table_buf_0x9050_len = 0; uchar *table_buf_0x9400; ushort table_buf_0x9400_len = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_len = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_len = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_len = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_len = 0; uchar *table_buf_0x940e; ushort table_buf_0x940e_len = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make, "Nokia", 5)) return; fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */ !strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4)) return; if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */ !strncmp(buf, "MLY", 3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, "SAMSUNG", 7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (!strncasecmp(model, "KODAK P880", 10) || !strncasecmp(model, "KODAK P850", 10) || !strncasecmp(model, "KODAK P712", 10)) { if (tag == 0xf90b) { imgdata.makernotes.kodak.clipBlack = get2(); } else if (tag == 0xf90c) { imgdata.makernotes.kodak.clipWhite = get2(); } } if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16, len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2) ystr[j / 2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) || !strncasecmp(model, "Hasselblad A6D", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) && !strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) / (float)c; } else if (tag == 0x003b) // all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0045) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) // Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } else if (tag == 0x00b9) { uchar uc; int8_t sc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTune = uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneIndex = uc; fread(&sc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneAdj = sc; } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2); break; case 0x20400612: case 0x30000612: imgdata.sizes.raw_crop.cleft = get2(); break; case 0x20400613: case 0x30000613: imgdata.sizes.raw_crop.ctop = get2(); break; case 0x20400614: case 0x30000614: imgdata.sizes.raw_crop.cwidth = get2(); break; case 0x20400615: case 0x30000615: imgdata.sizes.raw_crop.cheight = get2(); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float)temp; else imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x000d) { imgdata.makernotes.pentax.FocusMode = get2(); } else if (tag == 0x000e) { imgdata.makernotes.pentax.AFPointSelected = get2(); } else if (tag == 0x000f) { imgdata.makernotes.pentax.AFPointsInFocus = getint(type); } else if (tag == 0x0010) { imgdata.makernotes.pentax.FocusPosition = get2(); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x0034) { uchar uc; FORC4 { fread(&uc, 1, 1, ifp); imgdata.makernotes.pentax.DriveMode[c] = uc; } } else if (tag == 0x0038) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); } else if (tag == 0x0039) { imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x0072) { imgdata.makernotes.pentax.AFAdjustment = get2(); } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float)temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010, table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400, table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403, table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c, table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, "NIKON") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * libraw_powf64l(2.0f, float(cc) / 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64l(2.0, i / 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = libraw_powf64l(2.0, i / 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = libraw_powf64l(2.0, (short)i / -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, "Canon", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 /* Canon rotation data is handled by EXIF.Orientation */ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = "065"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, "Olympus", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200306) { uchar uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.olympus.AFFineTune = uc; } if (tag == 0x20200307) { FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2(); } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, "NRW ", 4)) { fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, "PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) // Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) // Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, "NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, "Samsung", 7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } /* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); } */ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp(int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i = 19; i--;) str[i] = fgetc(ifp); else fread(str, 19, 1, ifp); memset(&t, 0, sizeof t); if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif(int base) { unsigned kodak, entries, tag, type, len, save, c; double expo, ape; kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34865: if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4)) iso_speed = getreal(type); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = libraw_powf64l(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = libraw_powf64l(2.0, ape / 2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, MIN(len,511), ifp); mn_text[511] = 0; pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm="); if(pos) { pos +=4; char *pos2 = strstr(pos, " "); if(pos2) { l = pos2 - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; #if defined WIN32 || defined(__MINGW32__) // Win32 strtok is already thread-safe pos = strtok(ccms, ","); #else char *last=0; pos = strtok_r(ccms, ",",&last); #endif if(pos) { for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; #if defined WIN32 || defined(__MINGW32__) pos = strtok(NULL, ","); #else pos = strtok_r(NULL, ",",&last); #endif if(!pos) goto end; // broken } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } } } end:; } else #endif parse_makernote(base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; // no GPS tags are 1k or larger } switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; // no GPS tags are 1k or larger } switch (tag) { case 1: case 3: case 5: gpsdata[29 + tag / 2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag / 3 * 6 + c] = get4(); break; case 6: FORC(2) gpsdata[18 + c] = get4(); break; case 18: case 29: fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp); } fseek(ifp, save, SEEK_SET); } } void CLASS romm_coeff(float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ {{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}}; int i, j, k; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) for (cmatrix[i][j] = k = 0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos(int offset) { char data[40]; int skip, from, i, c, neut[4], planes = 0, frot = 0; static const char *mod[] = {"", "DCB2", "Volare", "Cantare", "CMost", "Valeo 6", "Valeo 11", "Valeo 22", "Valeo 11p", "Valeo 17", "", "Aptus 17", "Aptus 22", "Aptus 75", "Aptus 65", "Aptus 54S", "Aptus 65S", "Aptus 75S", "AFi 5", "AFi 6", "AFi 7", "AFi-II 7", "Aptus-II 7", "", "Aptus-II 6", "", "", "Aptus-II 10", "Aptus-II 5", "", "", "", "", "Aptus-II 10R", "Aptus-II 8", "", "Aptus-II 12", "", "AFi-II 12"}; float romm_cam[3][3]; fseek(ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread(data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data, "CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data, "back_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial)); strcpy(imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data, "CaptProf_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data, "JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data, "icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data, "ShootObj_back_type")) { fscanf(ifp, "%d", &i); if ((unsigned)i < sizeof mod / sizeof(*mod)) strcpy(model, mod[i]); } if (!strcmp(data, "icc_camera_to_tone_matrix")) { for (i = 0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_color_matrix")) { for (i = 0; i < 9; i++) fscanf(ifp, "%f", (float *)romm_cam + i); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_number_of_planes")) fscanf(ifp, "%d", &planes); if (!strcmp(data, "CaptProf_raw_data_rotation")) fscanf(ifp, "%d", &flip); if (!strcmp(data, "CaptProf_mosaic_pattern")) FORC4 { fscanf(ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data, "ImgProf_rotation_angle")) { fscanf(ifp, "%d", &i); flip = i - flip; } if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf(ifp, "%d", neut + c); FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1]; } if (!strcmp(data, "Rows_data")) load_flags = get4(); parse_mos(from); fseek(ifp, skip + from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3]; } void CLASS linear_table(unsigned len) { int i; if (len > 0x10000) len = 0x10000; else if(len < 1) return; read_shorts(curve, len); for (i = len; i < 0x10000; i++) curve[i] = curve[i - 1]; maximum = curve[len < 0x1000 ? 0xfff : len - 1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags(int wb, unsigned type) { float mul[3] = {1, 1, 1}, num, mul2; int c; FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int j, c, wbi = -2, romm_camTemp[9], romm_camScale[3]; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; // int a_blck = 0; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } if (tag == 1003) imgdata.sizes.raw_crop.cleft = get2(); if (tag == 1004) imgdata.sizes.raw_crop.ctop = get2(); if (tag == 1005) imgdata.sizes.raw_crop.cwidth = get2(); if (tag == 1006) imgdata.sizes.raw_crop.cheight = get2(); if (tag == 1007) imgdata.makernotes.kodak.BlackLevelTop = get2(); if (tag == 1008) imgdata.makernotes.kodak.BlackLevelBottom = get2(); if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2()); wbi = -2; } if ((tag == 1030) && (len == 1)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 1043) && (len == 1)) imgdata.other.SensorTemperature = getreal(type); if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C"))) black = get2(); if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C"))) { if (black) // already set by tag 0x03ef black = (black + get2()) / 2; else black = get2(); } INT64 _pos2 = ftell(ifp); if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x084c) Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type); if (tag == 0x084d) Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } fseek(ifp, _pos2, SEEK_SET); if (((tag == 0x07e4) || (tag == 0xfb01)) && (len == 9)) { short validM = 0; if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camDaylight)[j] = getreal(type); } validM = 1; } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camDaylight)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } validM = 1; } } if (validM) { romm_coeff(imgdata.makernotes.kodak.romm_camDaylight); } } if (((tag == 0x07e5) || (tag == 0xfb02)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camTungsten)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camTungsten)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e6) || (tag == 0xfb03)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camFluorescent)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camFluorescent)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e7) || (tag == 0xfb04)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camFlash)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camFlash)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e8) || (tag == 0xfb05)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camCustom)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camCustom)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e9) || (tag == 0xfb06)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camAuto)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camAuto)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table(len); if (tag == 0x903) iso_speed = getreal(type); // if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 0xfa13) width = getint(type); if (tag == 0xfa14) height = (getint(type) + 1) & -2; /* height = getint(type); if (tag == 0xfa16) raw_width = get2(); if (tag == 0xfa17) raw_height = get2(); */ if (tag == 0xfa18) { imgdata.makernotes.kodak.offset_left = getint(8); if (type != 8) imgdata.makernotes.kodak.offset_left += 1; } if (tag == 0xfa19) { imgdata.makernotes.kodak.offset_top = getint(8); if (type != 8) imgdata.makernotes.kodak.offset_top += 1; } if (tag == 0xfa31) imgdata.sizes.raw_crop.cwidth = get2(); if (tag == 0xfa32) imgdata.sizes.raw_crop.cheight = get2(); if (tag == 0xfa3e) imgdata.sizes.raw_crop.cleft = get2(); if (tag == 0xfa3f) imgdata.sizes.raw_crop.ctop = get2(); fseek(ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2, wbtemp = 6500; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num = i = 0; i < 4; i++) num += getreal(type) * pow(wbtemp / 100.0, i); cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c])); } if (tag == 2317) linear_table(len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : ((ifd + 1) << 20)), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = get2(); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: if (len == 3) { FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } else if (len == 1) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = getreal(type); // Is non-short possible here?? } break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; break; #ifdef LIBRAW_LIBRARY_BUILD case 10: if (pana_raw && len == 1 && type == 3) { libraw_internal_data.unpacker_data.pana_bpp = get2(); } break; #endif case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; case 0x0120: if (pana_raw) { unsigned sorder = order; unsigned long sbase = base; base = ftell(ifp); order = get2(); fseek(ifp, 2, SEEK_CUR); fseek(ifp, get4()-8, SEEK_CUR); parse_tiff_ifd (base); base = sbase; order = sorder; } break; case 0x2009: if ((libraw_internal_data.unpacker_data.pana_encoding == 4) || (libraw_internal_data.unpacker_data.pana_encoding == 5)) { int n = MIN (8, len); int permut[8] = {3, 2, 1, 0, 3+4, 2+4, 1+4, 0+4}; imgdata.makernotes.panasonic.BlackLevelDim = len; for (int i=0; i < n; i++) { imgdata.makernotes.panasonic.BlackLevel[permut[i]] = (float) (get2()) / (float) (powf(2.f, 14.f-libraw_internal_data.unpacker_data.pana_bpp)); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 45: if (pana_raw && len == 1 && type == 3) { libraw_internal_data.unpacker_data.pana_encoding = get2(); } break; #endif case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread(desc, 512, 1, ifp); break; case 271: /* Make */ fgets(make, 64, ifp); break; case 272: /* Model */ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: // FujiFilm "As Shot" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: /* Software */ if ((pana_raw) && (tag == 11) && (type == 3)) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.makernotes.panasonic.Compression = get2(); #endif break; } fgets(software, 64, ifp); if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) || !strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: /* SubIFDs */ if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP(cam_mul[i], cam_mul[i + 1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets(model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { if(cfa_pat[i] > 31) continue; // Skip wrong data colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, "\003\004\005", 3); /* CMY */ if (cfa == 072) memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 { int q = get2(); if(q > 0) cam_mul[c ^ 1] = 4096.0 / q; } break; case 34307: /* Leaf CatchLight color matrix */ fread(software, 1, 7, ifp); if (strncmp(software, "MATRIX", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1, num); } break; case 34310: /* Leaf metadata */ parse_mos(ftell(ifp)); case 34303: strcpy(make, "Leaf"); break; case 34665: /* EXIF tag */ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy(make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, "Ixpress %d-Mp", height * width / 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n')) if (!strncmp(++cp, "Neutral ", 8)) sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, "X-A3") && strcmp(model, "X-A10") && strcmp(model, "X-A5") && strcmp(model, "X-A20")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, "X-A3") && strcmp(model, "X-A10") && strcmp(model, "X-A5") && strcmp(model, "X-A20")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5; tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_black = #endif black = getreal(type); } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) cblack[6 + c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); if(len>0) { black += num / len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif } break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) // Linear DNG case for (i = 1; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: /* DefaultScale */ { float q1 = getreal(type); float q2 = getreal(type); if(q1 > 0.00001f && q2 > 0.00001f) { pixel_aspect = q1/q2; if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; } } break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: /* DefaultCropOrigin */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); if (!strncasecmp(make, "SONY", 4)) { imgdata.sizes.raw_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0]; imgdata.sizes.raw_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1]; } } break; case 50720: /* DefaultCropSize */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); if (!strncasecmp(make, "SONY", 4)) { imgdata.sizes.raw_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2]; imgdata.sizes.raw_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3]; } } break; case 0x74c7: if ((len == 2) && !strncasecmp(make, "SONY", 4)) { imgdata.makernotes.sony.raw_crop.cleft = get4(); imgdata.makernotes.sony.raw_crop.ctop = get4(); } break; case 0x74c8: if ((len == 2) && !strncasecmp(make, "SONY", 4)) { imgdata.makernotes.sony.raw_crop.cwidth = get4(); imgdata.makernotes.sony.raw_crop.cheight = get4(); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORCC for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; INT64 save_pos = ifp->tell(); parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); curr_pos = save_pos + MakN_length - 6; fseek(ifp, curr_pos, SEEK_SET); fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "SR2 ", 4)) { order = 0x4d4d; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; unsigned *buf_SR2; uchar *cbuf_SR2; unsigned icbuf_SR2; unsigned entries, tag, type, len, save; int ival; unsigned SR2SubIFDOffset = 0; unsigned SR2SubIFDLength = 0; unsigned SR2SubIFDKey = 0; int base = curr_pos + 6 - pos_in_original_raw; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 0x7200) { SR2SubIFDOffset = get4(); } else if (tag == 0x7201) { SR2SubIFDLength = get4(); } else if (tag == 0x7221) { SR2SubIFDKey = get4(); } fseek(ifp, save, SEEK_SET); } if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength+1024))) // 1024b for safety { fseek(ifp, SR2SubIFDOffset + base, SEEK_SET); fread(buf_SR2, SR2SubIFDLength, 1, ifp); sony_decrypt(buf_SR2, SR2SubIFDLength / 4, 1, SR2SubIFDKey); cbuf_SR2 = (uchar *)buf_SR2; entries = sget2(cbuf_SR2); icbuf_SR2 = 2; while (entries--) { tag = sget2(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 2; type = sget2(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 2; len = sget4(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 4; if (len * ("11124811248484"[type < 14 ? type : 0] - '0') > 4) { ival = sget4(cbuf_SR2 + icbuf_SR2) - SR2SubIFDOffset; } else { ival = icbuf_SR2; } if(ival > SR2SubIFDLength) // points out of orig. buffer size break; // END processing. Generally we should check against SR2SubIFDLength minus 6 of 8, depending on tag, but we allocated extra 1024b for buffer, so this does not matter icbuf_SR2 += 4; switch (tag) { case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = sget2(cbuf_SR2 + ival + 2 * c); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = sget2(cbuf_SR2 + ival + 2 * c); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; } } free(buf_SR2); } } /* SR2 processed */ break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: /* PreviewColorSpace */ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: /* OpcodeList2 */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length / 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC if(fabs(asn[c])>0.0001) cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC if(fabs(cc[c][c])>0.0001) pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff(int base) { int doff; fseek(ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek(ifp, doff + base, SEEK_SET); if (parse_tiff_ifd(base)) break; } return 1; } void CLASS apply_tiff() { int max_samp = 0, ties = 0, raw = -1, thm = -1, i; unsigned long long ns, os; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i = tiff_nifds; i--;) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i = 0; i < tiff_nifds; i++) { if( tiff_ifd[i].t_width < 1 || tiff_ifd[i].t_width > 65535 || tiff_ifd[i].t_height < 1 || tiff_ifd[i].t_height > 65535) continue; /* wrong image dimensions */ if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width * raw_height; ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i = tiff_nifds; i--;) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: #ifdef LIBRAW_LIBRARY_BUILD if (INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height)) #else if (tiff_ifd[raw].bytes == raw_width * raw_height) #endif { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL) #else if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) #endif { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } #ifdef LIBRAW_LIBRARY_BUILD if (INT64(tiff_ifd[raw].bytes) * 8ULL != INT64(raw_width) * INT64(raw_height) * INT64(tiff_bps)) #else if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps) #endif { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].samples == 4 && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 8ULL) // Sony ARQ { tiff_bps = 14; tiff_samples = 4; load_raw = &CLASS sony_arq_load_raw; filters = 0; strcpy(cdesc, "RGBG"); break; } if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 2ULL == INT64(raw_width) * INT64(raw_height) * 3ULL) #else if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3) #endif load_flags = 24; #ifdef LIBRAW_LIBRARY_BUILD if (INT64(tiff_ifd[raw].bytes) * 5ULL == INT64(raw_width) * INT64(raw_height) * 8ULL) #else if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8) #endif { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 7ULL > INT64(raw_width) * INT64(raw_height)) #else if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height) #endif load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: #ifdef LIBRAW_LIBRARY_BUILD if ((INT64(raw_width) + 9ULL) / 10ULL * 16ULL * INT64(raw_height) == INT64(tiff_ifd[raw].bytes)) #else if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes) #endif { load_raw = &CLASS packed_load_raw; load_flags = 1; } #ifdef LIBRAW_LIBRARY_BUILD else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL) #else else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) #endif { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } #ifdef LIBRAW_LIBRARY_BUILD else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes)) #else else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes) #endif { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); memset(cblack, 0, sizeof cblack); filters = 0; } #ifdef LIBRAW_LIBRARY_BUILD else if (INT64(raw_width) * INT64(raw_height) * 2ULL == INT64(tiff_ifd[raw].bytes)) #else else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes) #endif { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL) { load_raw = &CLASS packed_load_raw; load_flags = 80; } else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last if (INT64(tiff_ifd[raw].strip_byte_counts[i]) * 2ULL != INT64(tiff_ifd[raw].rows_per_strip) * INT64(raw_width) * 3ULL) { fit = 0; break; } if (fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") && !strstr(model2, "DEBUG RAW"))) && strncmp(software, "Nikon Scan", 10)) is_raw = 0; for (i = 0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) > thumb_width * thumb_height / (SQR(thumb_misc) + 1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make, "Imacon", 6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta(int base) { int save, tag, len, offset, high = 0, wide = 0, i, c; short sorder = order; fseek(ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save = ftell(ifp)) < offset) { for (tag = i = 0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek(ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model, "DiMAGE A200") ? 0 : 3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff(ftell(ifp)); data_offset = offset; } fseek(ifp, save + len + 8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save = ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if (ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length() - 3, 3, L"JPG"); if (!ifp->subfile_open(rawfile.c_str())) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif if (!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif ext = strrchr(ifname, '.'); file = strrchr(ifname, '/'); if (!file) file = strrchr(ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname - 1; #else if (!file) file = (char *)ifname - 1; #endif file++; if (!ext || strlen(ext) != 4 || ext - file != 8) return; jname = (char *)malloc(strlen(ifname) + 1); merror(jname, "parse_external_jpeg()"); strcpy(jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp(ext, ".jpg")) { strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg"); if (isdigit(*file)) { memcpy(jfile, file + 4, 4); memcpy(jfile + 4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp(jname, ifname)) { if ((ifp = fopen(jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Reading metadata from %s ...\n"), jname); #endif parse_tiff(12); thumb_offset = 0; is_raw = 1; fclose(ifp); } } #else if (strcmp(jname, ifname)) { if (!ifp->subfile_open(jname)) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("Failed to read metadata from %s\n"), jname); #endif } free(jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = {0x410, 0x45f3}; int i, bpp, row, col, vbits = 0; unsigned long bitbuf = 0; if ((get2(), get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i = row = 0; row < 8; row++) for (col = 0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff(int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi = -1; ushort key[] = {0x410, 0x45f3}; fseek(ifp, offset + length - 4, SEEK_SET); tboff = get4() + offset; fseek(ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek(ifp, offset + get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff(ftell(ifp), len, depth + 1); #endif if (type == 0x0810) fread(artist, 64, 1, ifp); if (type == 0x080a) { fread(make, 64, 1, ifp); fseek(ifp, strbuflen(make) - 63, SEEK_CUR); fread(model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = libraw_powf64l(2.0f, -int_to_float((get4(), get4()))); aperture = libraw_powf64l(2.0f, int_to_float(get4()) / 2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = libraw_powf64l(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(), get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = libraw_powf64l(2.0, (get2(), (short)get2()) / 64.0); #endif shutter = libraw_powf64l(2.0, -((short)get2()) / 32.0); wbi = (get2(), get2()); if (wbi > 17) wbi = 0; fseek(ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2() / 10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek(ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek(ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, o, SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp, o, SEEK_SET); } if (type == 0x580b) { if (strcmp(model, "Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek(ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0, wbi, 17)] - '0'; key[0] = key[1] = 0; } fseek(ifp, 78 + c * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0, wbi, 9)] - '0'; fseek(ifp, 2 + wbi * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(), get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if (imgdata.lens.makernotes.CanonFocalUnits > 1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD unique_id = setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime(gmtime(&timestamp)); #endif fseek(ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek(ifp, 0, SEEK_SET); memset(&t, 0, sizeof t); do { fgets(line, 128, ifp); if ((val = strchr(line, '='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line, "DAT")) sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line, "TIM")) sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line, "HDR")) thumb_offset = atoi(val); if (!strcmp(line, "X ")) raw_width = atoi(val); if (!strcmp(line, "Y ")) raw_height = atoi(val); if (!strcmp(line, "TX ")) thumb_width = atoi(val); if (!strcmp(line, "TY ")) thumb_height = atoi(val); } while (strncmp(line, "EOHD", 4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy(make, "Rollei"); strcpy(model, "d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek(ifp, 4, SEEK_SET); entries = get4(); fseek(ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread(str, 8, 1, ifp); if (!strcmp(str, "META")) meta_offset = off; if (!strcmp(str, "THUMB")) thumb_offset = off; if (!strcmp(str, "RAW0")) data_offset = off; } fseek(ifp, meta_offset + 20, SEEK_SET); fread(make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(), get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one(int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset(&ph1, 0, sizeof ph1); fseek(ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek(ifp, get4() + base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, base + data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0211: imgdata.other.SensorTemperature2 = int_to_float(data); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f)); else imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3] - '0'; break; case 0x106: for (i = 0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i] = #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff(romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data + base; break; case 0x110: meta_offset = data + base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.SensorTemperature = ph1.tag_210; #endif break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data + base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data + base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data + base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i = 0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread(model, 1, 63, ifp); if ((cp = strstr(model, " camera"))) *cp = 0; } fseek(ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek(ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy(make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy(model, "LightPhase"); break; case 2682: strcpy(model, "H 10"); break; case 4128: strcpy(model, "H 20"); break; case 5488: strcpy(model, "H 25"); break; } } void CLASS parse_fuji(int offset) { unsigned entries, tag, len, save, c; fseek(ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0, MIN(q, 2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); // IB start #ifdef LIBRAW_LIBRARY_BUILD } else if (tag == 0x110) { imgdata.sizes.raw_crop.ctop = get2(); imgdata.sizes.raw_crop.cleft = get2(); } else if (tag == 0x111) { imgdata.sizes.raw_crop.cheight = get2(); imgdata.sizes.raw_crop.cwidth = get2(); } else if ((tag == 0x122) && !strcmp(model, "DBP for GX680")) { int k = get2(); int l = get2(); /* margins? */ int m = get2(); /* margins? */ int n = get2(); // printf ("==>>0x122: height= %d l= %d m= %d width= %d\n", k, l, m, n); } else if (tag == 0x9650) { short a = (short)get2(); float b = fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2f00) { int nWBs = get4(); nWBs = MIN(nWBs, 6); for (int wb_ind = 0; wb_ind < nWBs; wb_ind++) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2(); fseek(ifp, 8, SEEK_CUR); } } else if (tag == 0x2000) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2(); } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } else if (tag == 0x2410) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2(); #endif // IB end } else if (tag == 0xc000) /* 0xc000 tag versions, second ushort; valid if the first ushort is 0 X100F 0x0259 X100T 0x0153 X-E2 0x014f 0x024f depends on firmware X-A1 0x014e XQ2 0x0150 XQ1 0x0150 X100S 0x0149 0x0249 depends on firmware X30 0x0152 X20 0x0146 X-T10 0x0154 X-T2 0x0258 X-M1 0x014d X-E2s 0x0355 X-A2 0x014e X-T20 0x025b GFX 50S 0x025a X-T1 0x0151 0x0251 0x0351 depends on firmware X70 0x0155 X-Pro2 0x0255 */ { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10") || !strcmp(model, "X-A5") || !strcmp(model, "X-A20")) { int wb[4]; int nWB, tWB, pWB; int iCCT = 0; int cnt; fseek(ifp, save + 0x200, SEEK_SET); for (int wb_ind = 0; wb_ind < 42; wb_ind++) { nWB = get4(); tWB = get4(); wb[0] = get4() << 1; wb[1] = get4(); wb[3] = get4(); wb[2] = get4() << 1; if (tWB && (iCCT < 255)) { imgdata.color.WBCT_Coeffs[iCCT][0] = tWB; for (cnt = 0; cnt < 4; cnt++) imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt]; iCCT++; } if (nWB != 70) { for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2) { if (Fuji_wb_list2[pWB] == nWB) { for (cnt = 0; cnt < 4; cnt++) imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt]; break; } } } } } else { libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len >> 1); } #endif order = c; } fseek(ifp, save + len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save + hlen) >= 0 && (save + hlen) <= ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm t; order = 0x4949; fread(tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4)) { int maxloop = 1000; get4(); while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag, "nctg", 4)) { while (ftell(ifp) + 7 < end) { i = get2(); size = get2(); if ((i + 1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek(ifp, size, SEEK_CUR); } } else if (!memcmp(tag, "IDIT", 4) && size < 64) { fread(date, 64, 1, ifp); date[size] = 0; memset(&t, 0, sizeof t); if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i = 0; i < 12 && strcasecmp(mon[i], month); i++) ; t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek(ifp, size, SEEK_CUR); } void CLASS parse_qt(int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp) + 7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread(tag, 4, 1, ifp); if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4)) parse_qt(save + size); if (!memcmp(tag, "CNDA", 4)) parse_jpeg(ftell(ifp)); fseek(ifp, save + size, SEEK_SET); } } void CLASS parse_smal(int offset, int fsize) { int ver; fseek(ifp, offset + 2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek(ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy(make, "SMaL"); sprintf(model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek(ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek(ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek(ifp, off_head + 4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(), get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek(ifp, off_setup + 792, SEEK_SET); strcpy(make, "CINE"); sprintf(model, "%d", get4()); fseek(ifp, 12, SEEK_CUR); switch ((i = get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek(ifp, 72, SEEK_CUR); switch ((get4() + 3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek(ifp, 668, SEEK_CUR); shutter = get4() / 1000000000.0; fseek(ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek(ifp, shot_select * 8, SEEK_CUR); data_offset = (INT64)get4() + 8; data_offset += (INT64)get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek(ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek(ifp, 0, SEEK_END); fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek(ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek(ifp, len - 8, SEEK_CUR); } } else { rdvo = get4(); fseek(ifp, 12, SEEK_CUR); is_raw = get4(); fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff(const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD , int internal_only #endif ) { // clang-format off static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, /* updated */ { 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } }, { "Canon EOS D60", 0, 0xfa0, /* updated */ { 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } }, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D Mark II", 0, 0x38de, /* updated */ { 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } }, { "Canon EOS 6D", 0, 0x3c82, /* skipped update */ { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 77D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 800D", 0, 0, { 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 200D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60Da", 0, 0x2ff7, /* added */ { 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } }, { "Canon EOS M6", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M5", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M2", 0, 0, /* added */ { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M100", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, /* updated */ { 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */ { 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, {"Canon PowerShot 600", 0, 0, /* added */ { -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, /* updated */ { 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } }, { "Canon PowerShot G1 X Mark III", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, /* updated */ { -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } }, { "Canon PowerShot G2", 0, 0, /* updated */ { 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, /* updated */ { 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, /* updated */ { 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X Mark II", 0, 0, { 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, /* updated */ { -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } }, { "Canon PowerShot Pro90", 0, 0, /* updated */ { -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } }, { "Canon PowerShot S30", 0, 0, /* updated */ { 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } }, { "Canon PowerShot S40", 0, 0, /* updated */ { 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } }, { "Canon PowerShot S45", 0, 0, /* updated */ { 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } }, { "Canon PowerShot S50", 0, 0, /* updated */ { 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot D10", 127, 0, /* DJC */ { 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-F1", 0, 0, /* added */ { 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } }, { "Casio EX-FH100", 0, 0, /* added */ { 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, /* updated */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F810", 0, 0, /* added */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, /* updated */ { 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100F", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A10", 0, 0, { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A20", 0, 0, /* temp */ { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-A3", 0, 0, { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-A5", 0, 0, /* temp */ { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-E3", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T20", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T10", 0, 0, /* updated */ { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-H1", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm GFX 50S", 0, 0, { 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } }, { "GITUP GIT2P", 4160, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "GITUP GIT2", 3200, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Hasselblad HV", 0, 0, /* added */ { 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } }, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Lusso", 0, 0, /* added */ { 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad 500 mech.", 0, 0, /* added */ { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad CFV", 0, 0, { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad 39-Coated", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H-39MP",0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H2D-39", 0, 0, /* added */ { 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } }, { "Hasselblad H3D-50", 0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H3D", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, { 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } }, { "Hasselblad H5D-50c",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "Hasselblad H5D-50",0, 0, { 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } }, { "Hasselblad H6D-100c",0, 0, { 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } }, { "Hasselblad X1D",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Photo Control Camerz ZDS 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf C-Most", 0, 0, /* updated */ { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus-II 8", 0, 0, /* added */ { 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } }, { "Leaf AFi-II 7", 0, 0, /* added */ { 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } }, { "Leaf Aptus-II 5", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 65S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 75S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 50", 0, 0, { 3984,0,0,0,10000,0,0,0,7666 } }, { "Leaf Credo 60", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leica M10", 0, 0, /* added */ { 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } }, { "Leica M9", 0, 0, /* added */ { 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } }, { "Leica M8", 0, 0, /* added */ { 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } }, { "Leica M (Typ 240)", 0, 0, /* added */ { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica M (Typ 262)", 0, 0, { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Leica S2", 0, 0, /* added */ { 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } }, {"Leica S-E (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, {"Leica S (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica Q (Typ 116)", 0, 0, /* updated */ { 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } }, { "Leica T (Typ 701)", 0, 0, /* added */ { 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } }, { "Leica X2", 0, 0, /* added */ { 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } }, { "Leica X1", 0, 0, /* added */ { 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } }, { "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */ { 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } }, { "Mamiya M31", 0, 0, /* added */ { 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } }, { "Mamiya M22", 0, 0, /* added */ { 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } }, { "Mamiya M18", 0, 0, /* added */ { 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, /* updated */ { 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */ { 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } }, { "Minolta DiMAGE 7i", 0, 0xf7d, /* added */ { 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } }, { "Minolta DiMAGE 7", 0, 0xf7d, /* updated */ { 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } }, { "Minolta DiMAGE A1", 0, 0xf8b, /* updated */ { 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta Maxxum 5D", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta Maxxum 7D", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, /* updated */ { 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } }, { "Nikon D2X", 0, 0, /* updated */ { 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D5600", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, /* updated */ { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D850", 0, 0, { 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } }, { "Nikon D810A", 0, 0, { 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, /* updated */ { -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } }, { "Nikon E5400", 0, 0, /* updated */ { 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } }, { "Nikon E5700", 0, 0, /* updated */ { -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Kalon", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Deneb", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, /* updated */ { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, /* updated */ { 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, /* updated */ { 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, /* updated */ { 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL9", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, { 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } }, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP565UZ", 0, 0, /* added */ { 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, /* updated */ { 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus TG-5", 0, 0, { 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax GR", 0, 0, /* added */ { 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } }, { "Pentax K-01", 0, 0, /* added */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K10D", 0, 0, /* updated */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax K-m", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax KP", 0, 0, { 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, /* updated */ { 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } }, { "Pentax K-30", 0, 0, /* updated */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K-3 II", 0, 0, /* updated */ { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-500", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-50", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, { 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } }, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax KP", 0, 0, /* temp */ { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax Q7", 0, 0, /* added */ { 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } }, { "Pentax Q10", 0, 0, /* updated */ { 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } }, { "Pentax Q", 0, 0, /* added */ { 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } }, { "Pentax MX-1", 0, 0, /* updated */ { 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* updated */ { 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } }, { "Panasonic DMC-CM10", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */ { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Leica V-LUX 1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX3", 0, 0xf7f, /* added */ { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX2", 0, 0, /* added */ { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-LUX 2", 0, 0xf7f, /* added */ { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX 3", 0, 0, /* added */ { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */ { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ2500", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZH1", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-FX180", -15, 0xfff, /* added */ { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-G9", -15, 0, { 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic AG-GH4", -15, 0, /* added */ { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, {"Panasonic DC-GH5s", -15, 0, { 6929,-2355,-708,-4192,12534,1828,-1097,1989,5195 } }, { "Panasonic DC-GH5", -15, 0, { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DC-GF10", -15, 0, /* temp, markets: GF10, GF90 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF90", -15, 0, /* temp, markets: GF10, GF90 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DC-GX9", -15, 0, /* temp */ { 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DC-ZS200", -15, 0, /* temp, markets: ZS200 TZ200 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DC-TZ200", -15, 0, /* temp, markets: ZS200 TZ200 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One H25", 0, 0, /* added */ { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ280", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ260", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ250",0, 0, // {3984,0,0,0,10000,0,0,0,7666}}, {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */ { "Phase One IQ180", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ160", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ150", 0, 0, /* added */ {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */ // { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ140", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P 45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P 30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P 21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ3 100MP", 0, 0, /* added */ // {2423,0,0,0,9901,0,0,0,7989}}, { 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */ { "Phase One IQ3 80MP", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ3 60MP", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ3 50MP", 0, 0, /* added */ // { 3984,0,0,0,10000,0,0,0,7666 } }, {10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */ { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Polaroid x530", 0, 0, { 13458,-2556,-510,-5444,15081,205,0,0,12120 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */ { 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } }, { "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */ { 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } }, { "Ricoh GR DIGITAL 3", 0, 0, /* added */ { 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } }, { "Ricoh GR DIGITAL 4", 0, 0, /* added */ { 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Ricoh GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh RICOH GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh GXR MOUNT A12", 0, 0, /* added */ { 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } }, { "Ricoh GXR A16", 0, 0, /* added */ { 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } }, { "Ricoh GXR A12", 0, 0, /* added */ { 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } }, { "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN120", 0, 0, /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung Galaxy S7 Edge", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy S7", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy NX", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX U", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* used for NX10/NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NXF1", 0, 0, /* added */ { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */ { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma sd Quattro", 2047, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma SD9", 15, 4095, /* updated */ { 13564,-2537,-751,-5465,15154,194,-67,116,10425 } }, { "Sigma SD10", 15, 16383, /* updated */ { 6787,-1682,575,-3091,8357,160,217,-369,12314 } }, { "Sigma SD14", 15, 16383, /* updated */ { 13589,-2509,-739,-5440,15104,193,-61,105,10554 } }, { "Sigma SD15", 15, 4095, /* updated */ { 13556,-2537,-730,-5462,15144,195,-61,106,10577 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP1X", 0, 4095, /* updated */ { 13704,-2452,-857,-5413,15073,186,-89,151,9820 } }, { "Sigma DP1", 0, 4095, /* updated */ { 12774,-2591,-394,-5333,14676,207,15,-21,12127 } }, { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, {"Sony DSC-RX10M4", -800, 0, { 7699,-2566,-629,-2967,11270,1928,-378,1286,4807 } }, { "Sony DSC-RX10",0, 0, /* same for M2/M3 */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, /* updated */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, {"Sony DSC-RX0", -800, 0, /* temp */ { 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 16596, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 16596, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A550", 0, 16596, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A5", 0, 0xfeb, /* Is there any cameras not covered above? */ { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, { 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } }, { "Sony ILCE-9", 0, 0, { 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } }, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM3", 0, 0, { 6640,-1847,-503,-5238,13010,2474,-993,1673,6527 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony MODEL-NAME", 0, 0, /* added */ { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-VG30", 0, 0, /* added */ { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-VG900", 0, 0, /* added */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; // clang-format on double cam_xyz[4][3]; char name[130]; int i, j; if (colors > 4 || colors < 1) return; int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0; if (cblack[4] * cblack[5] > 0) { for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) bl64 += cblack[c + 6]; bl64 /= cblack[4] * cblack[5]; } int rblack = black + bl4 + bl64; sprintf(name, "%s %s", t_make, t_model); for (i = 0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (!dng_version) { if (table[i].t_black > 0) { black = (ushort)table[i].t_black; memset(cblack, 0, sizeof(cblack)); } else if (table[i].t_black < 0 && rblack == 0) { black = (ushort)(-table[i].t_black); memset(cblack, 0, sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort)table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j = 0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if (internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if (!internal_only) #endif cam_xyz_coeff(rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff(int index) { static const float table[][12] = {/* index 0 -- all Foveon cameras */ {1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113}, /* index 1 -- Kodak DC20 and DC25 */ {2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25}, /* index 2 -- Logitech Fotoman Pixtura */ {1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672}, /* index 3 -- Nikon E880, E900, and E990 */ {-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705}}; int i, c; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i * colors + c]; } short CLASS guess_byte_order(int words) { uchar test[4][2]; int t = 2, msb; double diff, sum[2] = {0, 0}; fread(test[0], 2, 2, ifp); for (words -= 2; words--;) { fread(test[t], 2, 1, ifp); for (msb = 0; msb < 2; msb++) { diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]); sum[msb] += diff * diff; } t = (t + 1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green(int bps, int bite, int off0, int off1) { UINT64 bitbuf = 0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; if(width > 2064) return 0.f; // too wide FORC(2) { fseek(ifp, c ? off1 : off0, SEEK_SET); for (vbits = col = 0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps); } } FORC(width - 1) { sum[c & 1] += ABS(img[0][c] - img[1][c + 1]); sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]); } return 100 * log(sum[0] / sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace((unsigned char)string[i])) string[i] = 0; else break; } } void CLASS initdata() { tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } for (int i = 0; i < 0x10000; i++) curve[i] = i; memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { {3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0}, {3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0}, {3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4}, {3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21}, {3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2}, {3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0}, {4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19}, {4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6}, }; static const ushort canon[][11] = { {1944, 1416, 0, 0, 48, 0}, {2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25}, {2224, 1456, 48, 6, 0, 2}, {2376, 1728, 12, 6, 52, 2}, {2672, 1968, 12, 6, 44, 2}, {3152, 2068, 64, 12, 0, 0, 16}, {3160, 2344, 44, 12, 4, 4}, {3344, 2484, 4, 6, 52, 6}, {3516, 2328, 42, 14, 0, 0}, {3596, 2360, 74, 12, 0, 0}, {3744, 2784, 52, 12, 8, 12}, {3944, 2622, 30, 18, 6, 2}, {3948, 2622, 42, 18, 0, 2}, {3984, 2622, 76, 20, 0, 2, 14}, {4104, 3048, 48, 12, 24, 12}, {4116, 2178, 4, 2, 0, 0}, {4152, 2772, 192, 12, 0, 0}, {4160, 3124, 104, 11, 8, 65}, {4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49}, {4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49}, {4312, 2876, 22, 18, 0, 2}, {4352, 2874, 62, 18, 0, 0}, {4476, 2954, 90, 34, 0, 0}, {4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49}, {4480, 3366, 80, 50, 0, 0}, {4496, 3366, 80, 50, 12, 0}, {4768, 3516, 96, 16, 0, 0, 0, 16}, {4832, 3204, 62, 26, 0, 0}, {4832, 3228, 62, 51, 0, 0}, {5108, 3349, 98, 13, 0, 0}, {5120, 3318, 142, 45, 62, 0}, {5280, 3528, 72, 52, 0, 0}, /* EOS M */ {5344, 3516, 142, 51, 0, 0}, {5344, 3584, 126, 100, 0, 2}, {5360, 3516, 158, 51, 0, 0}, {5568, 3708, 72, 38, 0, 0}, {5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49}, {5712, 3774, 62, 20, 10, 2}, {5792, 3804, 158, 51, 0, 0}, {5920, 3950, 122, 80, 2, 0}, {6096, 4056, 72, 34, 0, 0}, /* EOS M3 */ {6288, 4056, 266, 36, 0, 0}, /* EOS 80D */ {6384, 4224, 120, 44, 0, 0}, /* 6D II */ {6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */ {8896, 5920, 160, 64, 0, 0}, }; static const struct { ushort id; char t_model[20]; } unique[] = { {0x001, "EOS-1D"}, {0x167, "EOS-1DS"}, {0x168, "EOS 10D"}, {0x169, "EOS-1D Mark III"}, {0x170, "EOS 300D"}, {0x174, "EOS-1D Mark II"}, {0x175, "EOS 20D"}, {0x176, "EOS 450D"}, {0x188, "EOS-1Ds Mark II"}, {0x189, "EOS 350D"}, {0x190, "EOS 40D"}, {0x213, "EOS 5D"}, {0x215, "EOS-1Ds Mark III"}, {0x218, "EOS 5D Mark II"}, {0x232, "EOS-1D Mark II N"}, {0x234, "EOS 30D"}, {0x236, "EOS 400D"}, {0x250, "EOS 7D"}, {0x252, "EOS 500D"}, {0x254, "EOS 1000D"}, {0x261, "EOS 50D"}, {0x269, "EOS-1D X"}, {0x270, "EOS 550D"}, {0x281, "EOS-1D Mark IV"}, {0x285, "EOS 5D Mark III"}, {0x286, "EOS 600D"}, {0x287, "EOS 60D"}, {0x288, "EOS 1100D"}, {0x289, "EOS 7D Mark II"}, {0x301, "EOS 650D"}, {0x302, "EOS 6D"}, {0x324, "EOS-1D C"}, {0x325, "EOS 70D"}, {0x326, "EOS 700D"}, {0x327, "EOS 1200D"}, {0x328, "EOS-1D X Mark II"}, {0x331, "EOS M"}, {0x335, "EOS M2"}, {0x374, "EOS M3"}, /* temp */ {0x384, "EOS M10"}, /* temp */ {0x394, "EOS M5"}, /* temp */ {0x398, "EOS M100"}, /* temp */ {0x346, "EOS 100D"}, {0x347, "EOS 760D"}, {0x349, "EOS 5D Mark IV"}, {0x350, "EOS 80D"}, {0x382, "EOS 5DS"}, {0x393, "EOS 750D"}, {0x401, "EOS 5DS R"}, {0x404, "EOS 1300D"}, {0x405, "EOS 800D"}, {0x406, "EOS 6D Mark II"}, {0x407, "EOS M6"}, {0x408, "EOS 77D"}, {0x417, "EOS 200D"}, }, sonique[] = { {0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"}, {0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"}, {0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"}, {0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"}, {0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"}, {0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"}, {0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"}, {0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"}, {0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"}, {0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"}, {0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"}, {0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"}, {0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"}, {0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"}, {0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"}, {0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"}, {0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"}, {0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16c, "DSC-RX0"}, {0x16d, "DSC-RX10M4"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { {786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"}, {1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"}, {1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"}, {5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"}, {5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12}, {10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"}, {10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12}, {16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"}, {15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"}, {31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"}, {23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"}, {32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"}, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb {1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"}, {2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"}, {2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"}, {2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"}, {3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"}, {3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"}, {5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"}, {5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"}, {6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"}, {6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"}, {9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"}, {10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"}, {10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"}, {10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"}, {10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"}, {15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"}, {16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"}, {16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"}, {17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"}, {17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"}, {19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"}, {19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"}, {20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"}, {20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"}, {21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"}, {26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"}, {26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"}, {26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"}, {41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"}, {42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"}, // Android Raw dumps id end {20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff}, {2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078}, {5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"}, {6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"}, {6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"}, {6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"}, {7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"}, {9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"}, {9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"}, {10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"}, {10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"}, {12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"}, {15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"}, {15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"}, {15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"}, {18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"}, {18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"}, {19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"}, {21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"}, {24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"}, {30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"}, {1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"}, {3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"}, {6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"}, {7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"}, {2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"}, {4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"}, {6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"}, {7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"}, {7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"}, {7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"}, {7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"}, {7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"}, {9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"}, {10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"}, {10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"}, {10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"}, {12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"}, {12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"}, {15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"}, {18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"}, {7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"}, {787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"}, {28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"}, {15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"}, {3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"}, {307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"}, {62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"}, {4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"}, {4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160}, {2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"}, {6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160}, {460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"}, {12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556}, {18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"}, {614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"}, {15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"}, {3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212}, {1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513}, {1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"}, {2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"}, {2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"}, {4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"}, {4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"}, {5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"}, {5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"}, {7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"}, {8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"}, {5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"}, {3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"}, {4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"}, {6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"}, {10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"}, {4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"}, {4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8}, {13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"}, {6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"}, {311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"}, {16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, {2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])]; #endif static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"}; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize = 1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings); for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++) memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0])); camera_count += sizeof(const_table) / sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 = imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature = imgdata.other.exifAmbientTemperature = -1000.0f; for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } #endif memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i = 0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i = 0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek(ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(fread(head, 1, 64, ifp) < 64) throw LIBRAW_EXCEPTION_IO_CORRUPT; libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread(head, 1, 32, ifp); #endif fseek(ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4))) { parse_phase_one(cp - head); if (cp - head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp(head + 6, "HEAPCCDR", 8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(hlen, flen - hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4)) { fseek(ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek(ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp(head + 25, "ARECOYK", 7)) { strcpy(make, "Contax"); strcpy(model, "N Digital"); fseek(ifp, 33, SEEK_SET); get_timestamp(1); fseek(ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = libraw_powf64l(2.0f, (((float)get4()) / 8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek(ifp, 88, SEEK_SET); aperture = libraw_powf64l(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp(head, "PXN")) { strcpy(make, "Logitech"); strcpy(model, "Fotoman Pixtura"); } else if (!strcmp(head, "qktk")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp(head, "qktn")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp(head, "FUJIFILM", 8)) { #ifdef LIBRAW_LIBRARY_BUILD strncpy(model, head + 0x1c,0x20); model[0x20]=0; memcpy(model2, head + 0x3c, 4); model2[4] = 0; #endif fseek(ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek(ifp, 92, SEEK_SET); parse_fuji(get4()); if (thumb_offset > 120) { fseek(ifp, 120, SEEK_SET); is_raw += (i = get4()) ? 1 : 0; if (is_raw == 2 && shot_select) parse_fuji(i); } load_raw = &CLASS unpacked_load_raw; fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET); parse_tiff(data_offset = get4()); parse_tiff(thumb_offset + 12); apply_tiff(); } else if (!memcmp(head, "RIFF", 4)) { fseek(ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp(head + 4, "ftypqt ", 9)) { fseek(ifp, 0, SEEK_SET); parse_qt(fsize); is_raw = 0; } else if (!memcmp(head, "\0\001\0\001\0@", 6)) { fseek(ifp, 6, SEEK_SET); fread(make, 1, 8, ifp); fread(model, 1, 8, ifp); fread(model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp(head, "NOKIARAW", 8)) { strcpy(make, "NOKIA"); order = 0x4949; fseek(ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); // bytes count width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // Data integrity check if (width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width * height) || i > (2 * width * height)) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif switch (tiff_bps = i * 8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp(head, "ARRI", 4)) { order = 0x4949; fseek(ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy(make, "ARRI"); fseek(ifp, 668, SEEK_SET); fread(model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp(head, "XPDS", 4)) { order = 0x4949; fseek(ifp, 0x800, SEEK_SET); fread(make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek(ifp, 56, SEEK_CUR); fread(model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve(0, 12.25, 1, 1023); } else if (!memcmp(head + 4, "RED1", 4)) { strcpy(make, "Red"); strcpy(model, "One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp(head, "DSC-Image", 9)) parse_rollei(); else if (!memcmp(head, "PWAD", 4)) parse_sinar_ia(); else if (!memcmp(head, "\0MRM", 4)) parse_minolta(0); else if (!memcmp(head, "FOVb", 4)) { #ifdef LIBRAW_LIBRARY_BUILD /* no foveon support for dcraw build from libraw source */ parse_x3f(); #endif } else if (!memcmp(head, "CI", 2)) parse_cine(); if (make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize = i = 0; i < camera_count; i++) #else for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy(make, table[i].t_make); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon", 5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy(model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff ? 0 : table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); break; } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal(0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp, 0, SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); strcpy(model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); if (!strncmp(model, "ov5647", 6)) strcpy(model, "RPi OV5647 v.1"); else strcpy(model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) && fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn")) { strcpy(make, "OmniVision"); data_offset = ftell(ifp) + 0x8000 - 32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i = 0; i < sizeof corp / sizeof *corp; i++) if (strcasestr(make, corp[i])) /* Simplify company names */ strcpy(make, corp[i]); if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) && ((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION")))) *cp = 0; if (!strncasecmp(model, "PENTAX", 6)) strcpy(make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make, sizeof(make)); remove_trailing_spaces(model, sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp(model, make, i) && model[i++] == ' ') memmove(model, model + i, 64 - i); if (!strncmp(model, "FinePix ", 8)) memmove(model, model + 8,strlen(model)-7); if (!strncmp(model, "Digital Camera ", 15)) memmove(model, model + 15,strlen(model)-14); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model, "K-5", 3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model, "K-70")) { height = 4016; top_margin = 32; width = 6020; left_margin = 60; } if (width == 4736 && !strcmp(model, "K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6112 && !strcmp(model, "KP")) { /* From DNG, maybe too strict */ left_margin = 54; top_margin = 28; width = 6028; height = raw_height - top_margin; } if (width == 6080 && !strcmp(model, "K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model, "645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i = 0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff("Canon", unique[i].t_model); strcpy(model, unique[i].t_model); } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff("Sony", sonique[i].t_model); strcpy(model, sonique[i].t_model); } } if (!strncmp(make, "Nikon", 5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy(model, "C603"); } #ifndef LIBRAW_LIBRARY_BUILD if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); #else /* Always 512 for arw2_load_raw */ if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12)); #endif if (is_foveon) { if (height * 2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; } else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3)) { top_margin = 18; height = raw_height - top_margin; if (raw_width == 7392) { left_margin = 6; width = 7376; } } else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height, width); SWAP(raw_height, raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model, "PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256 / 235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model, "PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model, "PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model, "PowerShot A610")) { if (canon_s2is()) strcpy(model + 10, "S2 IS"); } else if (!strcmp(model, "PowerShot SX220 HS")) { mask[1][3] = -4; top_margin = 16; left_margin = 92; } else if (!strcmp(model, "PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model, "PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width - left_margin - 48; height = raw_height - top_margin - 14; } else if (!strcmp(model, "PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model, "EOS D2000C")) { filters = 0x61616161; if (!black) black = curve[200]; } else if (!strcmp(model, "D1")) { cam_mul[0] *= 256 / 527.0; cam_mul[2] *= 256 / 317.0; } else if (!strcmp(model, "D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000")) { height -= 3; width -= 4; } else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model, "D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model, "D5000") || !strcmp(model, "D90")) { width -= 42; } else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A")) { width -= 44; } else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4)) { width -= 46; } else if (!strcmp(model, "D4") || !strcmp(model, "Df")) { width -= 52; left_margin = 2; } else if (!strcmp(model, "D500")) { // Empty - to avoid width-1 below } else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3)) { width--; } else if (!strcmp(model, "D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model, "D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model, "D2H", 3)) { left_margin = 6; width -= 14; } else if (!strncmp(model, "D2X", 3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model, "D300", 4)) { width -= 32; } else if (!strncmp(make, "Nikon", 5) && raw_width == 4032) { if (!strcmp(model, "COOLPIX P7700")) { adobe_coeff("Nikon", "COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P7800")) { adobe_coeff("Nikon", "COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P340")) load_flags = 0; } else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2")) black = 255; } else if (!strncmp(model, "COOLPIX B700", 12)) { load_flags = 24; black = 200; } else if (!strncmp(model, "1 ", 2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy(model, "E995"); if (strcmp(model, "E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy(model, "E2500"); if (!strcmp(model, "E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model + 1) < 3700) filters = 0x49494949; if (!strcmp(model, "Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green(12, 32, 1188864, 3576832); c = find_green(12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i, c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy(make, "Minolta"); strcpy(model, "DiMAGE Z2"); } load_flags = 6 + 24 * (make[0] == 'M'); } else if (fsize == 6291456) { fseek(ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy(make, "ISG"); model[0] = 0; } } else if (!strncmp(make, "Fujifilm", 8)) { if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { left_margin = 0; top_margin = 0; width = raw_width; height = raw_height; } if (!strcmp(model + 7, "S2Pro")) { strcpy(model, "S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2) && filters >=1000) // Bayer and not X-models maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if (!strcmp(model, "GFX 50S")) { left_margin = 0; top_margin = 0; } if (!strcmp(model, "S5500")) { height -= (top_margin = 6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6]; } else if (!strcmp(model, "KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model, "KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make, "Minolta", 7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model, "DiMAGE A", 8)) { if (!strcmp(model, "DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6)) { sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M')); adobe_coeff(make, model + 20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "DiMAGE G", 8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model, "*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model, "*ist DS")) { height -= 2; } else if (!strncmp(make, "Samsung", 7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000")) { top_margin = 38; left_margin = 92; width = 5456; height = 3634; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make, "Samsung", 7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model, "EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model, "WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model, "WB550")) { strcpy(model, "WB550"); } else if (!strcmp(model, "EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin = 24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model, "STV680 VGA")) { black = 16; } else if (!strcmp(model, "N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model, "640x480")) { gamma_curve(0.45, 4.5, 1, 255); } else if (!strncmp(make, "Hasselblad", 10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if (!strncasecmp(model, "H3D", 3)) { adobe_coeff("Hasselblad", "H3DII-39"); strcpy(model, "H3DII-39"); } } else if (raw_width == 12000) // H6D 100c, A6D 100c { left_margin = 64; width = 11608; top_margin = 108; height = raw_height - top_margin; adobe_coeff("Hasselblad", "H6D-100c"); } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad", "H4D-40"); strcpy(model, "H4D-40"); } else if (raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad", "X1D"); maximum = 0xffff; tiff_bps = 16; } else if (raw_width == 9044) { if (black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H4D-60"); strcpy(model, "H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model, "H3DII-60"); } } else if (raw_width == 4090) { strcpy(model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if (!strncasecmp(model, "H5D", 3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model, "H5D-50"); } else if (!strncasecmp(model, "H3D", 3)) { black = 0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H3D-50"); strcpy(model, "H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model, "H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples + 1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make, "Sinar", 5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make, "Leaf", 4)) { maximum = 0x3fff; fseek(ifp, data_offset, SEEK_SET); if (ljpeg_start(&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy(cdesc, "RBTG"); strcpy(model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy(model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width + height == 3144 + 2060) { if (!model[0]) strcpy(model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6)) { if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height)) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i = 0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model, "C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make, "Olympus", 7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model, "E-300") || !strcmp(model, "E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset(cblack, 0, sizeof cblack); } } else if (!strcmp(model, "STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model, "E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model, "SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model, "TG-4")) { width -= 16; } else if (!strcmp(model, "TG-5")) { width -= 26; } } else if (!strcmp(model, "N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model, "DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy(cdesc, "RGBE"); } else if (!strcmp(model, "DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make, "Sony", 4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make, "Sony", 4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make, "Sony", 4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make, "Sony", 4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make, "Sony", 4) && raw_width == 6048) { width -= 24; if (strstr(model, "RX1") || strstr(model, "A99")) width -= 6; } else if (!strncmp(make, "Sony", 4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make, "Sony", 4) && raw_width == 8000) { width -= 32; } else if (!strcmp(model, "DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model, "PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve(0, 7, 1, 255); } else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP")) { order = 0x4949; if (filters && data_offset) { fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts(curve, 256); } else gamma_curve(0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model, "EasyShare", 9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make, "Kodak", 5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model, "DCS460A")) goto bw; } else if (!strcmp(model, "DCS660M")) { black = 214; goto bw; } else if (!strcmp(model, "DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model + 4, "20X")) strcpy(cdesc, "MYCY"); if (strstr(model, "DC25")) { strcpy(model, "DC25"); data_offset = 15424; } if (!strncmp(model, "DC2", 3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0 * height) / (3.0 * width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0 * height) / (373.0 * width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model, "40")) { strcpy(model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model, "DC50")) { strcpy(model, "DC50"); height = 512; width = 768; iso_speed = 84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model, "DC120")) { strcpy(model, "DC120"); raw_height = height = 976; raw_width = width = 848; iso_speed = 160; pixel_aspect = height / 0.75 / width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model, "DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed = 140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model, "Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model, "QuickTake", 9)) { if (head[5]) strcpy(model + 10, "200"); fseek(ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(), get2()) == 30 ? 738 : 736; if (height > width) { SWAP(height, width); fseek(ifp, data_offset - 6, SEEK_SET); flip = ~get2() & 3 ? 5 : 6; } filters = 0x61616161; } else if (!strncmp(make, "Rollei", 6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model, "GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model, "BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1 /* alloc in unpack() may be fooled by size adjust */ || ((int)width + (int)left_margin > 65535) || ((int)height + (int)top_margin > 65535)) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if (!model[0]) sprintf(model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if (dng_version) /* Override black level by DNG tags */ { /* copy DNG data from per-IFD field to color.dng */ int iifd = 0; // Active IFD we'll show to user. for (; iifd < tiff_nifds; iifd++) if (tiff_ifd[iifd].offset == data_offset) // found break; int pifd = -1; for (int ii = 0; ii < tiff_nifds; ii++) if (tiff_ifd[ii].offset == thumb_offset) // found { pifd = ii; break; } #define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < tiff_nifds) { int sidx; // Per field, not per structure if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2 && tiff_ifd[sidx].dng_levels.default_crop[2] > 0 && tiff_ifd[sidx].dng_levels.default_crop[3] > 0) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ maximum = imgdata.color.dng_levels.dng_whitelevel[0]; black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for (int i = 0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125) { memcpy(rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff(make, model); #ifdef LIBRAW_LIBRARY_BUILD else if (imgdata.color.cam_xyz[0][0] < 0.01) adobe_coeff(make, model, 1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff("Apple", "Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if (fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED)) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY"); if (!raw_height) raw_height = height; if (!raw_width) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if (flip > 89 || flip < -89) { switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { {0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}}; static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static const double adobe_rgb[3][3] = { {0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}}; static const double wide_rgb[3][3] = { {0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}}; static const double prophoto_rgb[3][3] = { {0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}}; static const double aces_rgb[3][3] = { {0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}}; static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb}; static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"}; static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d}; unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20}; /* bXYZ */ static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc}; unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000}; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2); #endif gamma_curve(gamm[0], gamm[1], 0, 0); memcpy(out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *)calloc(phead[0], 1); merror(oprof, "convert_to_rgb()"); memcpy(oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12 * pbody[0]; for (i = 0; i < pbody[0]; i++) { oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i * 3 + 2] = oprof[0]; oprof[0] += (pbody[i * 3 + 3] + 3) & -4; } memcpy(oprof + 32, pbody, sizeof pbody); oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1; memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite); pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16; for (i = 4; i < 7; i++) memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve); pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { for (num = k = 0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5; } for (i = 0; i < phead[0] / 4; i++) oprof[i] = htonl(oprof[i]); strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw"); strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (out_cam[i][j] = k = 0; k < 3; k++) out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color - 1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset(histogram, 0, sizeof histogram); for (img = image[0], row = 0; row < height; row++) for (col = 0; col < width; col++, img += 4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int)out[c]); } else if (document_mode) img[0] = img[fcol(row, col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort(*)[4])calloc(high, wide * sizeof *img); merror(img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2); #endif for (row = 0; row < high; row++) for (col = 0; col < wide; col++) { ur = r = fuji_width + (row - col) * step; uc = c = (row + col) * step; if (ur > height - 2 || uc > width - 2) continue; fr = r - ur; fc = c - uc; pix = image + ur * width + uc; for (i = 0; i < colors; i++) img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) + (pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr; } free(image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort(*)[4])calloc(width, newdim * sizeof *img); merror(img, "stretch()"); for (rc = row = 0; row < newdim; row++, rc += pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c * width]; if (c + 1 < height) pix1 += width * 4; for (col = 0; col < width; col++, pix0 += 4, pix1 += 4) FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort(*)[4])calloc(height, newdim * sizeof *img); merror(img, "stretch()"); for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c + 1 < width) pix1 += 4; for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4) FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } width = newdim; } free(image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2); #endif } int CLASS flip_index(int row, int col) { if (flip & 4) SWAP(row, col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct libraw_tiff_tag *tt; int c; tt = (struct libraw_tiff_tag *)(ntag + 1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count - 1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val + c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head(struct tiff_hdr *th, int full) { int c, psize = 0; struct tm *t; memset(th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4 + c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy(th->t_desc, desc, 512); strncpy(th->t_make, make, 64); strncpy(th->t_model, model, 64); strcpy(th->soft, "dcraw v" DCRAW_VERSION); t = localtime(&timestamp); sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); strncpy(th->t_artist, artist, 64); if (full) { tiff_set(th, &th->ntag, 254, 4, 1, 0); tiff_set(th, &th->ntag, 256, 4, 1, width); tiff_set(th, &th->ntag, 257, 4, 1, height); tiff_set(th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag - 1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set(th, &th->ntag, 259, 3, 1, 1); tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set(th, &th->ntag, 277, 3, 1, colors); tiff_set(th, &th->ntag, 278, 4, 1, height); tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8); } else tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0'); tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set(th, &th->ntag, 284, 3, 1, 1); tiff_set(th, &th->ntag, 296, 3, 1, 2); tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set(th, &th->ngps, 0, 1, 4, 0x202); tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy(th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc(0xff, tfp); fputc(0xd8, tfp); if (strcmp(t_humb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, tfp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, tfp); } fwrite(t_humb + 2, 1, t_humb_length - 2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp, thumb, thumb_length); free(thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); fputc(0xff, ofp); fputc(0xd8, ofp); if (strcmp(thumb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, ofp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, ofp); } fwrite(thumb + 2, 1, thumb_length - 2, ofp); free(thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white = 0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white = c = 0; c < colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height, width); ppm = (uchar *)calloc(width, colors * output_bps / 8); ppm2 = (ushort *)ppm; merror(ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head(&th, 1); fwrite(&th, sizeof th, 1, ofp); if (oprof) fwrite(oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps) - 1, cdesc); else fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1); soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, width); for (row = 0; row < height; row++, soff += rstep) { for (col = 0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col * colors + c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab((char *)ppm2, (char *)ppm2, width * colors * 2); fwrite(ppm, colors * output_bps / 8, width, ofp); } free(ppm); }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_94_0
crossvul-cpp_data_bad_845_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/gd/ext_gd.h" #include <sys/types.h> #include <sys/stat.h> #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/comparisons.h" #include "hphp/runtime/base/plain-file.h" #include "hphp/runtime/base/request-event-handler.h" #include "hphp/runtime/base/runtime-option.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-printf.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/ext/std/ext_std_file.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/util/alloc.h" #include "hphp/util/rds-local.h" #include "hphp/runtime/ext/gd/libgd/gd.h" #include "hphp/runtime/ext/gd/libgd/gdfontt.h" /* 1 Tiny font */ #include "hphp/runtime/ext/gd/libgd/gdfonts.h" /* 2 Small font */ #include "hphp/runtime/ext/gd/libgd/gdfontmb.h" /* 3 Medium bold font */ #include "hphp/runtime/ext/gd/libgd/gdfontl.h" /* 4 Large font */ #include "hphp/runtime/ext/gd/libgd/gdfontg.h" /* 5 Giant font */ #include <zlib.h> #include <set> #include <folly/portability/Stdlib.h> #include <folly/portability/Unistd.h> /* Section Filters Declarations */ /* IMPORTANT NOTE FOR NEW FILTER * Do not forget to update: * IMAGE_FILTER_MAX: define the last filter index * IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments * image_filter array in PHP_FUNCTION(imagefilter) */ #define IMAGE_FILTER_NEGATE 0 #define IMAGE_FILTER_GRAYSCALE 1 #define IMAGE_FILTER_BRIGHTNESS 2 #define IMAGE_FILTER_CONTRAST 3 #define IMAGE_FILTER_COLORIZE 4 #define IMAGE_FILTER_EDGEDETECT 5 #define IMAGE_FILTER_EMBOSS 6 #define IMAGE_FILTER_GAUSSIAN_BLUR 7 #define IMAGE_FILTER_SELECTIVE_BLUR 8 #define IMAGE_FILTER_MEAN_REMOVAL 9 #define IMAGE_FILTER_SMOOTH 10 #define IMAGE_FILTER_PIXELATE 11 #define IMAGE_FILTER_MAX 11 #define IMAGE_FILTER_MAX_ARGS 6 #define IMAGE_TYPE_GIF 1 #define IMAGE_TYPE_JPEG 2 #define IMAGE_TYPE_PNG 4 #define IMAGE_TYPE_WBMP 8 #define IMAGE_TYPE_XPM 16 // #define IM_MEMORY_CHECK namespace HPHP { /////////////////////////////////////////////////////////////////////////////// #define HAS_GDIMAGESETANTIALIASED #if defined(HAS_GDIMAGEANTIALIAS) #define SetAntiAliased(gd, flag) gdImageAntialias(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #elif defined(HAS_GDIMAGESETANTIALIASED) #define SetAntiAliased(gd, flag) ((gd)->AA = (flag)) #define SetupAntiAliasedColor(gd, color) \ ((gd)->AA ? \ gdImageSetAntiAliased(im, color), gdAntiAliased : \ color) #else #define SetAntiAliased(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #endif /////////////////////////////////////////////////////////////////////////////// // sweep() { this->~Image(); } IMPLEMENT_RESOURCE_ALLOCATION(Image) void Image::reset() { if (m_gdImage) { gdImageDestroy(m_gdImage); m_gdImage = nullptr; } } Image::~Image() { reset(); } struct ImageMemoryAlloc final : RequestEventHandler { ImageMemoryAlloc() : m_mallocSize(0) {} void requestInit() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); #endif assertx(m_mallocSize == 0); m_mallocSize = 0; } void requestShutdown() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); assertx(m_mallocSize == 0); #endif m_mallocSize = 0; } void *imMalloc(size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); if (m_mallocSize + size < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &size, sizeof(size)); m_mallocSize += size; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &size, sizeof(size)); m_mallocSize += size; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void *imCalloc(size_t nmemb, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); size_t bytes = nmemb * size; if (m_mallocSize + bytes < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + bytes); if (!ptr) return nullptr; memset(ptr, 0, sizeof(ln) + sizeof(size) + bytes); memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &bytes, sizeof(bytes)); m_mallocSize += bytes; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + bytes); if (!ptr) return nullptr; memcpy(ptr, &bytes, sizeof(bytes)); memset((char *)ptr + sizeof(size), 0, bytes); m_mallocSize += bytes; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void imFree(void *ptr #ifdef IM_MEMORY_CHECK , int ln #endif ) { size_t size; void *sizePtr = (char *)ptr - sizeof(size); memcpy(&size, sizePtr, sizeof(size)); m_mallocSize -= size; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); int count = m_alloced.erase((char*)sizePtr - sizeof(ln)); assertx(count == 1); // double free on failure assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(lnPtr); #else assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(sizePtr); #endif } // wrapper of realloc, the original buffer is freed on failure void *imRealloc(void *ptr, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); #ifdef IM_MEMORY_CHECK if (!ptr) return imMalloc(size, ln); if (!size) { imFree(ptr, ln); return nullptr; } #else if (!ptr) return imMalloc(size); if (!size) { imFree(ptr); return nullptr; } #endif void *sizePtr = (char *)ptr - sizeof(size); size_t oldSize = 0; if (ptr) memcpy(&oldSize, sizePtr, sizeof(oldSize)); int diff = size - oldSize; void *tmp; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(lnPtr, sizeof(ln) + sizeof(size) + size))) { int count = m_alloced.erase(ptr); assertx(count == 1); // double free on failure local_free(lnPtr); return nullptr; } memcpy(tmp, &ln, sizeof(ln)); memcpy((char*)tmp + sizeof(ln), &size, sizeof(size)); m_mallocSize += diff; if (tmp != lnPtr) { int count = m_alloced.erase(lnPtr); assertx(count == 1); m_alloced.insert(tmp); } return ((char *)tmp + sizeof(ln) + sizeof(size)); #else if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(sizePtr, sizeof(size) + size))) { local_free(sizePtr); return nullptr; } memcpy(tmp, &size, sizeof(size)); m_mallocSize += diff; return ((char *)tmp + sizeof(size)); #endif } #ifdef IM_MEMORY_CHECK void imDump(void *ptrs[], int &n) { int i = 0; for (auto iter = m_alloced.begin(); iter != m_alloced.end(); ++i, ++iter) { void *p = *iter; assertx(p); if (i < n) ptrs[i] = p; int ln; size_t size; memcpy(&ln, p, sizeof(ln)); memcpy(&size, (char*)p + sizeof(ln), sizeof(size)); printf("%d: (%p, %lu)\n", ln, p, size); } n = (i < n) ? i : n; } #endif private: size_t m_mallocSize; #ifdef IM_MEMORY_CHECK std::set<void *> m_alloced; #endif }; IMPLEMENT_STATIC_REQUEST_LOCAL(ImageMemoryAlloc, s_ima); #ifdef IM_MEMORY_CHECK #define IM_MALLOC(size) s_ima->imMalloc((size), __LINE__) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size), __LINE__) #define IM_FREE(ptr) s_ima->imFree((ptr), __LINE__) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size), __LINE__) #else #define IM_MALLOC(size) s_ima->imMalloc((size)) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size)) #define IM_FREE(ptr) s_ima->imFree((ptr)) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size)) #endif #define CHECK_BUFFER(begin, end, size) \ do { \ if (((char*)end) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d)", \ __FUNCTION__, __LINE__, begin, end, size); \ return; \ } \ } while (0) #define CHECK_BUFFER_R(begin, end, size, retcod) \ do { \ if (((char*)(end)) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d, %d)", \ __FUNCTION__, __LINE__, begin, end, size, retcod); \ return retcod; \ } \ } while (0) #define CHECK_ALLOC(ptr, size) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return; \ } \ } while (0) #define CHECK_ALLOC_R(ptr, size, retcod) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return retcod; \ } \ } while (0) // original Zend name is _estrndup static char *php_strndup_impl(const char* s, uint32_t length #ifdef IM_MEMORY_CHECK , int ln #endif ) { char *p; #ifdef IM_MEMORY_CHECK p = (char *)s_ima->imMalloc((length+1), ln); #else p = (char *)s_ima->imMalloc((length+1)); #endif CHECK_ALLOC_R(p, length+1, nullptr); memcpy(p, s, length); p[length] = 0; return p; } static char *php_strdup_impl(const char* s #ifdef IM_MEMORY_CHECK , int ln #endif ) { #ifdef IM_MEMORY_CHECK return php_strndup_impl(s, strlen(s), ln); #else return php_strndup_impl(s, strlen(s)); #endif } #ifdef IM_MEMORY_CHECK #define PHP_STRNDUP(var, s, length) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strndup_impl((s), (length), __LINE__); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strdup_impl(s, __LINE__); \ } while (0) #else #define PHP_STRNDUP(var, s, length) \ do { \ if (var) IM_FREE(var); \ (var) = php_strndup_impl((s), (length)); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) IM_FREE(var); \ (var) = php_strdup_impl(s); \ } while (0) #endif typedef enum { IMAGE_FILETYPE_UNKNOWN=0, IMAGE_FILETYPE_GIF=1, IMAGE_FILETYPE_JPEG, IMAGE_FILETYPE_PNG, IMAGE_FILETYPE_SWF, IMAGE_FILETYPE_PSD, IMAGE_FILETYPE_BMP, IMAGE_FILETYPE_TIFF_II, /* intel */ IMAGE_FILETYPE_TIFF_MM, /* motorola */ IMAGE_FILETYPE_JPC, IMAGE_FILETYPE_JP2, IMAGE_FILETYPE_JPX, IMAGE_FILETYPE_JB2, IMAGE_FILETYPE_SWC, IMAGE_FILETYPE_IFF, IMAGE_FILETYPE_WBMP, /* IMAGE_FILETYPE_JPEG2000 is a userland alias for IMAGE_FILETYPE_JPC */ IMAGE_FILETYPE_XBM, IMAGE_FILETYPE_ICO, IMAGE_FILETYPE_COUNT /* Must remain last */ } image_filetype; // PHP extension STANDARD: image.c /* file type markers */ static const char php_sig_gif[3] = {'G', 'I', 'F'}; static const char php_sig_psd[4] = {'8', 'B', 'P', 'S'}; static const char php_sig_bmp[2] = {'B', 'M'}; static const char php_sig_swf[3] = {'F', 'W', 'S'}; static const char php_sig_swc[3] = {'C', 'W', 'S'}; static const char php_sig_jpg[3] = {(char) 0xff, (char) 0xd8, (char) 0xff}; static const char php_sig_png[8] = {(char) 0x89, (char) 0x50, (char) 0x4e, (char) 0x47, (char) 0x0d, (char) 0x0a, (char) 0x1a, (char) 0x0a}; static const char php_sig_tif_ii[4] = {'I','I', (char)0x2A, (char)0x00}; static const char php_sig_tif_mm[4] = {'M','M', (char)0x00, (char)0x2A}; static const char php_sig_jpc[3] = {(char)0xff, (char)0x4f, (char)0xff}; static const char php_sig_jp2[12] = {(char)0x00, (char)0x00, (char)0x00, (char)0x0c, (char)0x6a, (char)0x50, (char)0x20, (char)0x20, (char)0x0d, (char)0x0a, (char)0x87, (char)0x0a}; static const char php_sig_iff[4] = {'F','O','R','M'}; static const char php_sig_ico[4] = {(char)0x00, (char)0x00, (char)0x01, (char)0x00}; static struct gfxinfo *php_handle_gif(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(3, SEEK_CUR)) return nullptr; String dim = stream->read(5); if (dim.length() != 5) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->width = (unsigned int)s[0] | (((unsigned int)s[1])<<8); result->height = (unsigned int)s[2] | (((unsigned int)s[3])<<8); result->bits = s[4]&0x80 ? ((((unsigned int)s[4])&0x07) + 1) : 0; result->channels = 3; /* always */ return result; } static struct gfxinfo *php_handle_psd(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(8); if (dim.length() != 8) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->height = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->width = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); return result; } static struct gfxinfo *php_handle_bmp(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int size; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(16); if (dim.length() != 16) return nullptr; s = (unsigned char *)dim.c_str(); size = (((unsigned int)s[3]) << 24) + (((unsigned int)s[2]) << 16) + (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (size == 12) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); result->bits = ((unsigned int)s[11]); } else if (size > 12 && (size <= 64 || size == 108 || size == 124)) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[7]) << 24) + (((unsigned int)s[6]) << 16) + (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[11]) << 24) + (((unsigned int)s[10]) << 16) + (((unsigned int)s[9]) << 8) + ((unsigned int)s[8]); result->height = abs((int32_t)result->height); result->bits = (((unsigned int)s[15]) << 8) + ((unsigned int)s[14]); } else { return nullptr; } return result; } static unsigned long int php_swf_get_bits(unsigned char* buffer, unsigned int pos, unsigned int count) { unsigned int loop; unsigned long int result = 0; for (loop = pos; loop < pos + count; loop++) { result = result + ((((buffer[loop / 8]) >> (7 - (loop % 8))) & 0x01) << (count - (loop - pos) - 1)); } return result; } static struct gfxinfo *php_handle_swc(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned long len=64, szlength; int factor=1,maxfactor=16; int slength, status=0; unsigned char *b, *buf=nullptr; String bufz; String tmp; b = (unsigned char *)IM_CALLOC(1, len + 1); CHECK_ALLOC_R(b, (len + 1), nullptr); if (!stream->seek(5, SEEK_CUR)) { IM_FREE(b); return nullptr; } String a = stream->read(64); if (a.length() != 64) { IM_FREE(b); return nullptr; } if (uncompress((Bytef*)b, &len, (const Bytef*)a.c_str(), 64) != Z_OK) { /* failed to decompress the file, will try reading the rest of the file */ if (!stream->seek(8, SEEK_SET)) { IM_FREE(b); return nullptr; } while (!(tmp = stream->read(8192)).empty()) { bufz += tmp; } slength = bufz.length(); /* * zlib::uncompress() wants to know the output data length * if none was given as a parameter * we try from input length * 2 up to input length * 2^8 * doubling it whenever it wasn't big enough * that should be eneugh for all real life cases */ do { szlength=slength*(1<<factor++); buf = (unsigned char *) IM_REALLOC(buf,szlength); if (!buf) IM_FREE(b); CHECK_ALLOC_R(buf, szlength, nullptr); status = uncompress((Bytef*)buf, &szlength, (const Bytef*)bufz.c_str(), slength); } while ((status==Z_BUF_ERROR)&&(factor<maxfactor)); if (status == Z_OK) { memcpy(b, buf, len); } if (buf) { IM_FREE(buf); } } if (!status) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); if (!result) IM_FREE(b); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (b, 0, 5); result->width = (php_swf_get_bits (b, 5 + bits, bits) - php_swf_get_bits (b, 5, bits)) / 20; result->height = (php_swf_get_bits (b, 5 + (3 * bits), bits) - php_swf_get_bits (b, 5 + (2 * bits), bits)) / 20; } else { result = nullptr; } IM_FREE(b); return result; } static struct gfxinfo *php_handle_swf(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned char *a; if (!stream->seek(5, SEEK_CUR)) return nullptr; String str = stream->read(32); if (str.length() != 32) return nullptr; a = (unsigned char *)str.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (a, 0, 5); result->width = (php_swf_get_bits (a, 5 + bits, bits) - php_swf_get_bits (a, 5, bits)) / 20; result->height = (php_swf_get_bits (a, 5 + (3 * bits), bits) - php_swf_get_bits (a, 5 + (2 * bits), bits)) / 20; result->bits = 0; result->channels = 0; return result; } static struct gfxinfo *php_handle_png(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; /* Width: 4 bytes * Height: 4 bytes * Bit depth: 1 byte * Color type: 1 byte * Compression method: 1 byte * Filter method: 1 byte * Interlace method: 1 byte */ if (!stream->seek(8, SEEK_CUR)) return nullptr; String dim = stream->read(9); if (dim.length() < 9) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->height = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); result->bits = (unsigned int)s[8]; return result; } /* routines to handle JPEG data */ /* some defines for the different JPEG block types */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_APP0 0xe0 #define M_APP1 0xe1 #define M_APP2 0xe2 #define M_APP3 0xe3 #define M_APP4 0xe4 #define M_APP5 0xe5 #define M_APP6 0xe6 #define M_APP7 0xe7 #define M_APP8 0xe8 #define M_APP9 0xe9 #define M_APP10 0xea #define M_APP11 0xeb #define M_APP12 0xec #define M_APP13 0xed #define M_APP14 0xee #define M_APP15 0xef #define M_COM 0xFE /* COMment */ #define M_PSEUDO 0xFFD8 /* pseudo marker for start of image(byte 0) */ #define M_EXIF 0xE1 /* Exif Attribute Information */ static unsigned short php_read2(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(2); /* just return 0 if we hit the end-of-file */ if (str.length() != 2) return 0; a = (unsigned char *)str.c_str(); return (((unsigned short)a[0]) << 8) + ((unsigned short)a[1]); } static unsigned int php_next_marker(const req::ptr<File>& file, int /*last_marker*/, int ff_read) { int a=0, marker; // get marker byte, swallowing possible padding if (!ff_read) { size_t extraneous = 0; while ((marker = file->getc()) != 0xff) { if (marker == EOF) { return M_EOI;/* we hit EOF */ } extraneous++; } if (extraneous) { raise_warning("corrupt JPEG data: %zu extraneous bytes before marker", extraneous); } } a = 1; do { if ((marker = file->getc()) == EOF) { return M_EOI;/* we hit EOF */ } ++a; } while (marker == 0xff); if (a < 2) { return M_EOI; /* at least one 0xff is needed before marker code */ } return (unsigned int)marker; } static int php_skip_variable(const req::ptr<File>& stream) { off_t length = (unsigned int)php_read2(stream); if (length < 2) { return 0; } length = length - 2; stream->seek(length, SEEK_CUR); return 1; } static int php_read_APP(const req::ptr<File>& stream, unsigned int marker, Array& info) { unsigned short length; unsigned char markername[16]; length = php_read2(stream); if (length < 2) { return 0; } length -= 2; /* length includes itself */ String buffer = stream->read(length); if (buffer.empty()) { return 0; } snprintf((char*)markername, sizeof(markername), "APP%d", marker - M_APP0); if (!info.exists(String((const char *)markername))) { /* XXX we only catch the 1st tag of it's kind! */ info.set(String((char*)markername, CopyString), buffer); } return 1; } static struct gfxinfo *php_handle_jpeg(const req::ptr<File>& file, Array& info) { struct gfxinfo *result = nullptr; unsigned int marker = M_PSEUDO; unsigned short length, ff_read=1; for (;;) { marker = php_next_marker(file, marker, ff_read); ff_read = 0; switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if (result == nullptr) { /* handle SOFn block */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); length = php_read2(file); result->bits = file->getc(); result->height = php_read2(file); result->width = php_read2(file); result->channels = file->getc(); if (info.isNull() || length < 8) { /* if we don't want an extanded info -> return */ return result; } if (!file->seek(length - 8, SEEK_CUR)) { /* file error after info */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_APP0: case M_APP1: case M_APP2: case M_APP3: case M_APP4: case M_APP5: case M_APP6: case M_APP7: case M_APP8: case M_APP9: case M_APP10: case M_APP11: case M_APP12: case M_APP13: case M_APP14: case M_APP15: if (!info.isNull()) { if (!php_read_APP(file, marker, info)) { /* read all the app markes... */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_SOS: case M_EOI: /* we're about to hit image data, or are at EOF. stop processing. */ return result; default: if (!php_skip_variable(file)) { /* anything else isn't interesting */ return result; } break; } } return result; /* perhaps image broken -> no info but size */ } static unsigned short php_read4(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(4); /* just return 0 if we hit the end-of-file */ if (str.length() != 4) return 0; a = (unsigned char *)str.c_str(); return (((unsigned int)a[0]) << 24) + (((unsigned int)a[1]) << 16) + (((unsigned int)a[2]) << 8) + (((unsigned int)a[3])); } /* JPEG 2000 Marker Codes */ #define JPEG2000_MARKER_PREFIX 0xFF /* All marker codes start with this */ #define JPEG2000_MARKER_SOC 0x4F /* Start of Codestream */ #define JPEG2000_MARKER_SOT 0x90 /* Start of Tile part */ #define JPEG2000_MARKER_SOD 0x93 /* Start of Data */ #define JPEG2000_MARKER_EOC 0xD9 /* End of Codestream */ #define JPEG2000_MARKER_SIZ 0x51 /* Image and tile size */ #define JPEG2000_MARKER_COD 0x52 /* Coding style default */ #define JPEG2000_MARKER_COC 0x53 /* Coding style component */ #define JPEG2000_MARKER_RGN 0x5E /* Region of interest */ #define JPEG2000_MARKER_QCD 0x5C /* Quantization default */ #define JPEG2000_MARKER_QCC 0x5D /* Quantization component */ #define JPEG2000_MARKER_POC 0x5F /* Progression order change */ #define JPEG2000_MARKER_TLM 0x55 /* Tile-part lengths */ #define JPEG2000_MARKER_PLM 0x57 /* Packet length, main header */ #define JPEG2000_MARKER_PLT 0x58 /* Packet length, tile-part header */ #define JPEG2000_MARKER_PPM 0x60 /* Packed packet headers, main header */ #define JPEG2000_MARKER_PPT 0x61 /* Packed packet headers, tile part header */ #define JPEG2000_MARKER_SOP 0x91 /* Start of packet */ #define JPEG2000_MARKER_EPH 0x92 /* End of packet header */ #define JPEG2000_MARKER_CRG 0x63 /* Component registration */ #define JPEG2000_MARKER_COM 0x64 /* Comment */ /* Main loop to parse JPEG2000 raw codestream structure */ static struct gfxinfo *php_handle_jpc(const req::ptr<File>& file) { struct gfxinfo *result = nullptr; int highest_bit_depth, bit_depth; unsigned char first_marker_id; unsigned int i; /* JPEG 2000 components can be vastly different from one another. Each component can be sampled at a different resolution, use a different colour space, have a separate colour depth, and be compressed totally differently! This makes giving a single "bit depth" answer somewhat problematic. For this implementation we'll use the highest depth encountered. */ /* Get the single byte that remains after the file type indentification */ first_marker_id = file->getc(); /* Ensure that this marker is SIZ (as is mandated by the standard) */ if (first_marker_id != JPEG2000_MARKER_SIZ) { raise_warning("JPEG2000 codestream corrupt(Expected SIZ marker " "not found after SOC)"); return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); php_read2(file); /* Lsiz */ php_read2(file); /* Rsiz */ result->width = php_read4(file); /* Xsiz */ result->height = php_read4(file); /* Ysiz */ #if MBO_0 php_read4(file); /* XOsiz */ php_read4(file); /* YOsiz */ php_read4(file); /* XTsiz */ php_read4(file); /* YTsiz */ php_read4(file); /* XTOsiz */ php_read4(file); /* YTOsiz */ #else if (!file->seek(24, SEEK_CUR)) { IM_FREE(result); return nullptr; } #endif result->channels = php_read2(file); /* Csiz */ if (result->channels > 256) { IM_FREE(result); return nullptr; } /* Collect bit depth info */ highest_bit_depth = bit_depth = 0; for (i = 0; i < result->channels; i++) { bit_depth = file->getc(); /* Ssiz[i] */ bit_depth++; if (bit_depth > highest_bit_depth) { highest_bit_depth = bit_depth; } file->getc(); /* XRsiz[i] */ file->getc(); /* YRsiz[i] */ } result->bits = highest_bit_depth; return result; } /* main loop to parse JPEG 2000 JP2 wrapper format structure */ static struct gfxinfo *php_handle_jp2(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; unsigned int box_length; unsigned int box_type; char jp2c_box_id[] = {(char)0x6a, (char)0x70, (char)0x32, (char)0x63}; /* JP2 is a wrapper format for JPEG 2000. Data is contained within "boxes". Boxes themselves can be contained within "super-boxes". Super-Boxes can contain super-boxes which provides us with a hierarchical storage system. It is valid for a JP2 file to contain multiple individual codestreams. We'll just look for the first codestream at the root of the box structure and handle that. */ for (;;) { box_length = php_read4(stream); /* LBox */ /* TBox */ String str = stream->read(sizeof(box_type)); if (str.length() != sizeof(box_type)) { /* Use this as a general "out of stream" error */ break; } memcpy(&box_type, str.c_str(), sizeof(box_type)); if (box_length == 1) { /* We won't handle XLBoxes */ return nullptr; } if (!memcmp(&box_type, jp2c_box_id, 4)) { /* Skip the first 3 bytes to emulate the file type examination */ stream->seek(3, SEEK_CUR); result = php_handle_jpc(stream); break; } /* Stop if this was the last box */ if ((int)box_length <= 0) { break; } /* Skip over LBox (Which includes both TBox and LBox itself */ if (!stream->seek(box_length - 8, SEEK_CUR)) { break; } } if (result == nullptr) { raise_warning("JP2 file has no codestreams at root level"); } return result; } /* tiff constants */ static const int php_tiff_bytes_per_format[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1}; static int get_php_tiff_bytes_per_format(int format) { int size = sizeof(php_tiff_bytes_per_format)/sizeof(int); if (format >= size) { raise_warning("Invalid format %d", format); format = 0; } return php_tiff_bytes_per_format[format]; } /* uncompressed only */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 /* compressed images only */ #define TAG_COMP_IMAGEWIDTH 0xA002 #define TAG_COMP_IMAGEHEIGHT 0xA003 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 static int php_vspprintf(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, ...) ATTRIBUTE_PRINTF(3,4); static int php_vspprintf(char **pbuf, size_t max_len, const char *fmt, ...) { va_list arglist; char *buf; va_start(arglist, fmt); int len = vspprintf_ap(&buf, max_len, fmt, arglist); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } va_end(arglist); return len; } static int php_vspprintf_ap(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, va_list ap) ATTRIBUTE_PRINTF(3,0); static int php_vspprintf_ap(char **pbuf, size_t max_len, const char *fmt, va_list ap) { char *buf; int len = vspprintf_ap(&buf, max_len, fmt, ap); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } return len; } /* Convert a 16 bit unsigned value from file's native byte order */ static int php_ifd_get16u(void *Short, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Short)[0] << 8) | ((unsigned char *)Short)[1]; } else { return (((unsigned char *)Short)[1] << 8) | ((unsigned char *)Short)[0]; } } /* Convert a 16 bit signed value from file's native byte order */ static signed short php_ifd_get16s(void *Short, int motorola_intel) { return (signed short)php_ifd_get16u(Short, motorola_intel); } /* Convert a 32 bit signed value from file's native byte order */ static int php_ifd_get32s(void *Long, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Long)[0] << 24) | (((unsigned char *)Long)[1] << 16) | (((unsigned char *)Long)[2] << 8) | (((unsigned char *)Long)[3] << 0); } else { return (((unsigned char *)Long)[3] << 24) | (((unsigned char *)Long)[2] << 16) | (((unsigned char *)Long)[1] << 8) | (((unsigned char *)Long)[0] << 0); } } /* Convert a 32 bit unsigned value from file's native byte order */ static unsigned php_ifd_get32u(void *Long, int motorola_intel) { return (unsigned)php_ifd_get32s(Long, motorola_intel) & 0xffffffff; } /* main loop to parse TIFF structure */ static struct gfxinfo *php_handle_tiff(const req::ptr<File>& stream, int motorola_intel) { struct gfxinfo *result = nullptr; int i, num_entries; unsigned char *dir_entry; size_t dir_size, entry_value, width=0, height=0, ifd_addr; int entry_tag , entry_type; String ifd_ptr = stream->read(4); if (ifd_ptr.length() != 4) return nullptr; ifd_addr = php_ifd_get32u((void*)ifd_ptr.c_str(), motorola_intel); if (!stream->seek(ifd_addr-8, SEEK_CUR)) return nullptr; String ifd_data = stream->read(2); if (ifd_data.length() != 2) return nullptr; num_entries = php_ifd_get16u((void*)ifd_data.c_str(), motorola_intel); dir_size = 2/*num dir entries*/ +12/*length of entry*/* num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; String ifd_data2 = stream->read(dir_size-2); if ((size_t)ifd_data2.length() != dir_size-2) return nullptr; ifd_data += ifd_data2; /* now we have the directory we can look how long it should be */ for(i=0;i<num_entries;i++) { dir_entry = (unsigned char*)ifd_data.c_str()+2+i*12; entry_tag = php_ifd_get16u(dir_entry+0, motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, motorola_intel); switch(entry_type) { case TAG_FMT_BYTE: case TAG_FMT_SBYTE: entry_value = (size_t)(dir_entry[8]); break; case TAG_FMT_USHORT: entry_value = php_ifd_get16u(dir_entry+8, motorola_intel); break; case TAG_FMT_SSHORT: entry_value = php_ifd_get16s(dir_entry+8, motorola_intel); break; case TAG_FMT_ULONG: entry_value = php_ifd_get32u(dir_entry+8, motorola_intel); break; case TAG_FMT_SLONG: entry_value = php_ifd_get32s(dir_entry+8, motorola_intel); break; default: continue; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGEWIDTH: width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGEHEIGHT: height = entry_value; break; } } if ( width && height) { /* not the same when in for-loop */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->height = height; result->width = width; result->bits = 0; result->channels = 0; return result; } return nullptr; } static struct gfxinfo *php_handle_iff(const req::ptr<File>& stream) { struct gfxinfo * result; char *a; int chunkId; int size; short width, height, bits; String str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); if (strncmp(a+4, "ILBM", 4) && strncmp(a+4, "PBM ", 4)) { return nullptr; } /* loop chunks to find BMHD chunk */ do { str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); chunkId = php_ifd_get32s(a+0, 1); size = php_ifd_get32s(a+4, 1); if (size < 0) return nullptr; if ((size & 1) == 1) { size++; } if (chunkId == 0x424d4844) { /* BMHD chunk */ if (size < 9) return nullptr; str = stream->read(9); if (str.length() != 9) return nullptr; a = (char *)str.c_str(); width = php_ifd_get16s(a+0, 1); height = php_ifd_get16s(a+2, 1); bits = a[8] & 0xff; if (width > 0 && height > 0 && bits > 0 && bits < 33) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = width; result->height = height; result->bits = bits; result->channels = 0; return result; } } else { if (!stream->seek(size, SEEK_CUR)) return nullptr; } } while (1); } /* * int WBMP file format type * byte Header Type * byte Extended Header * byte Header Data (type 00 = multibyte) * byte Header Data (type 11 = name/pairs) * int Number of columns * int Number of rows */ static int php_get_wbmp(const req::ptr<File>& file, struct gfxinfo **result, int check) { int i, width = 0, height = 0; if (!file->rewind()) { return 0; } /* get type */ if (file->getc() != 0) { return 0; } /* skip header */ do { i = file->getc(); if (i < 0) { return 0; } } while (i & 0x80); /* get width */ do { i = file->getc(); if (i < 0) { return 0; } width = (width << 7) | (i & 0x7f); } while (i & 0x80); /* get height */ do { i = file->getc(); if (i < 0) { return 0; } height = (height << 7) | (i & 0x7f); } while (i & 0x80); // maximum valid sizes for wbmp (although 127x127 may be a // more accurate one) if (!height || !width || height > 2048 || width > 2048) { return 0; } if (!check) { (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_WBMP; } static struct gfxinfo *php_handle_wbmp(const req::ptr<File>& stream) { struct gfxinfo *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); if (!php_get_wbmp(stream, &result, 0)) { IM_FREE(result); return nullptr; } return result; } static int php_get_xbm(const req::ptr<File>& stream, struct gfxinfo **result) { String fline; char *iname; char *type; int value; unsigned int width = 0, height = 0; if (result) { *result = nullptr; } if (!stream->rewind()) { return 0; } while (!(fline = HHVM_FN(fgets)(Resource(stream), 0).toString()).empty()) { iname = (char *)IM_MALLOC(fline.size() + 1); CHECK_ALLOC_R(iname, (fline.size() + 1), 0); if (sscanf(fline.c_str(), "#define %s %d", iname, &value) == 2) { if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("width", type)) { width = (unsigned int)value; if (height) { IM_FREE(iname); break; } } if (!strcmp("height", type)) { height = (unsigned int)value; if (width) { IM_FREE(iname); break; } } } IM_FREE(iname); } if (width && height) { if (result) { *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(*result, sizeof(struct gfxinfo), 0); (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_XBM; } return 0; } static struct gfxinfo *php_handle_xbm(const req::ptr<File>& stream) { struct gfxinfo *result; php_get_xbm(stream, &result); return result; } static struct gfxinfo *php_handle_ico(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int num_icons = 0; String dim = stream->read(2); if (dim.length() != 2) { return nullptr; } s = (unsigned char *)dim.c_str(); num_icons = (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (num_icons < 1 || num_icons > 255) { return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); while (num_icons > 0) { dim = stream->read(16); if (dim.length() != 16) { break; } s = (unsigned char *)dim.c_str(); if ((((unsigned int)s[7]) << 8) + ((unsigned int)s[6]) >= result->bits) { result->width = (unsigned int)s[0]; result->height = (unsigned int)s[1]; result->bits = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); } num_icons--; } return result; } /* Convert internal image_type to mime type */ static char *php_image_type_to_mime_type(int image_type) { switch( image_type) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } /* detect filetype from first bytes */ static int php_getimagetype(const req::ptr<File>& file) { String fileType = file->read(3); if (fileType.length() != 3) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 3 */ if (!memcmp(fileType.c_str(), php_sig_gif, 3)) { return IMAGE_FILETYPE_GIF; } else if (!memcmp(fileType.c_str(), php_sig_jpg, 3)) { return IMAGE_FILETYPE_JPEG; } else if (!memcmp(fileType.c_str(), php_sig_png, 3)) { String data = file->read(5); if (data.length() != 5) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } if (!memcmp((fileType + data).c_str(), php_sig_png, 8)) { return IMAGE_FILETYPE_PNG; } else { raise_warning("PNG file corrupted by ASCII conversion"); return IMAGE_FILETYPE_UNKNOWN; } } else if (!memcmp(fileType.c_str(), php_sig_swf, 3)) { return IMAGE_FILETYPE_SWF; } else if (!memcmp(fileType.c_str(), php_sig_swc, 3)) { return IMAGE_FILETYPE_SWC; } else if (!memcmp(fileType.c_str(), php_sig_psd, 3)) { return IMAGE_FILETYPE_PSD; } else if (!memcmp(fileType.c_str(), php_sig_bmp, 2)) { return IMAGE_FILETYPE_BMP; } else if (!memcmp(fileType.c_str(), php_sig_jpc, 3)) { return IMAGE_FILETYPE_JPC; } String data = file->read(1); if (data.length() != 1) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 4 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_tif_ii, 4)) { return IMAGE_FILETYPE_TIFF_II; } else if (!memcmp(fileType.c_str(), php_sig_tif_mm, 4)) { return IMAGE_FILETYPE_TIFF_MM; } else if (!memcmp(fileType.c_str(), php_sig_iff, 4)) { return IMAGE_FILETYPE_IFF; } else if (!memcmp(fileType.c_str(), php_sig_ico, 4)) { return IMAGE_FILETYPE_ICO; } data = file->read(8); if (data.length() != 8) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 12 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_jp2, 12)) { return IMAGE_FILETYPE_JP2; } /* AFTER ALL ABOVE FAILED */ if (php_get_wbmp(file, nullptr, 1)) { return IMAGE_FILETYPE_WBMP; } if (php_get_xbm(file, nullptr)) { return IMAGE_FILETYPE_XBM; } return IMAGE_FILETYPE_UNKNOWN; } String HHVM_FUNCTION(image_type_to_mime_type, int64_t imagetype) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } Variant HHVM_FUNCTION(image_type_to_extension, int64_t imagetype, bool include_dot /*=true */) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return include_dot ? String(".gif") : String("gif"); case IMAGE_FILETYPE_JPEG: return include_dot ? String(".jpeg") : String("jpeg"); case IMAGE_FILETYPE_PNG: return include_dot ? String(".png") : String("png"); case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return include_dot ? String(".swf") : String("swf"); case IMAGE_FILETYPE_PSD: return include_dot ? String(".psd") : String("psd"); case IMAGE_FILETYPE_BMP: case IMAGE_FILETYPE_WBMP: return include_dot ? String(".bmp") : String("bmp"); case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return include_dot ? String(".tiff") : String("tiff"); case IMAGE_FILETYPE_IFF: return include_dot ? String(".iff") : String("iff"); case IMAGE_FILETYPE_JPC: return include_dot ? String(".jpc") : String("jpc"); case IMAGE_FILETYPE_JP2: return include_dot ? String(".jp2") : String("jp2"); case IMAGE_FILETYPE_JPX: return include_dot ? String(".jpx") : String("jpx"); case IMAGE_FILETYPE_JB2: return include_dot ? String(".jb2") : String("jb2"); case IMAGE_FILETYPE_XBM: return include_dot ? String(".xbm") : String("xbm"); case IMAGE_FILETYPE_ICO: return include_dot ? String(".ico") : String("ico"); default: return false; } } const StaticString s_bits("bits"), s_channels("channels"), s_mime("mime"), s_linespacing("linespacing"); gdImagePtr get_valid_image_resource(const Resource& image) { auto img_res = dyn_cast_or_null<Image>(image); if (!img_res || !img_res->get()) { raise_warning("supplied resource is not a valid Image resource"); return nullptr; } return img_res->get(); } Variant getImageSize(const req::ptr<File>& stream, VRefParam imageinfo) { int itype = 0; struct gfxinfo *result = nullptr; auto imageInfoPtr = imageinfo.getVariantOrNull(); if (imageInfoPtr) { *imageInfoPtr = Array::Create(); } itype = php_getimagetype(stream); switch( itype) { case IMAGE_FILETYPE_GIF: result = php_handle_gif(stream); break; case IMAGE_FILETYPE_JPEG: { Array infoArr; if (imageInfoPtr) { infoArr = Array::Create(); } result = php_handle_jpeg(stream, infoArr); if (imageInfoPtr) { *imageInfoPtr = infoArr; } } break; case IMAGE_FILETYPE_PNG: result = php_handle_png(stream); break; case IMAGE_FILETYPE_SWF: result = php_handle_swf(stream); break; case IMAGE_FILETYPE_SWC: result = php_handle_swc(stream); break; case IMAGE_FILETYPE_PSD: result = php_handle_psd(stream); break; case IMAGE_FILETYPE_BMP: result = php_handle_bmp(stream); break; case IMAGE_FILETYPE_TIFF_II: result = php_handle_tiff(stream, 0); break; case IMAGE_FILETYPE_TIFF_MM: result = php_handle_tiff(stream, 1); break; case IMAGE_FILETYPE_JPC: result = php_handle_jpc(stream); break; case IMAGE_FILETYPE_JP2: result = php_handle_jp2(stream); break; case IMAGE_FILETYPE_IFF: result = php_handle_iff(stream); break; case IMAGE_FILETYPE_WBMP: result = php_handle_wbmp(stream); break; case IMAGE_FILETYPE_XBM: result = php_handle_xbm(stream); break; case IMAGE_FILETYPE_ICO: result = php_handle_ico(stream); break; default: case IMAGE_FILETYPE_UNKNOWN: break; } if (result) { DArrayInit ret(7); ret.set(0, (int64_t)result->width); ret.set(1, (int64_t)result->height); ret.set(2, itype); char *temp; php_vspprintf(&temp, 0, "width=\"%d\" height=\"%d\"", result->width, result->height); ret.set(3, String(temp, CopyString)); if (temp) IM_FREE(temp); if (result->bits != 0) { ret.set(s_bits, (int64_t)result->bits); } if (result->channels != 0) { ret.set(s_channels, (int64_t)result->channels); } ret.set(s_mime, (char*)php_image_type_to_mime_type(itype)); IM_FREE(result); return ret.toVariant(); } else { return false; } } Variant HHVM_FUNCTION(getimagesize, const String& filename, VRefParam imageinfo /*=null */) { if (auto stream = File::Open(filename, "rb")) { return getImageSize(stream, imageinfo); } return false; } Variant HHVM_FUNCTION(getimagesizefromstring, const String& imagedata, VRefParam imageinfo /*=null */) { String data = "data://text/plain;base64,"; data += StringUtil::Base64Encode(imagedata); if (auto stream = File::Open(data, "r")) { return getImageSize(stream, imageinfo); } return false; } // PHP extension gd.c #define HAVE_GDIMAGECREATEFROMPNG 1 #if HAVE_LIBTTF|HAVE_LIBFREETYPE #ifndef ENABLE_GD_TTF #define ENABLE_GD_TTF #endif #endif #define PHP_GDIMG_TYPE_GIF 1 #define PHP_GDIMG_TYPE_PNG 2 #define PHP_GDIMG_TYPE_JPG 3 #define PHP_GDIMG_TYPE_WBM 4 #define PHP_GDIMG_TYPE_XBM 5 #define PHP_GDIMG_TYPE_XPM 6 #define PHP_GDIMG_CONVERT_WBM 7 #define PHP_GDIMG_TYPE_GD 8 #define PHP_GDIMG_TYPE_GD2 9 #define PHP_GDIMG_TYPE_GD2PART 10 #define PHP_GDIMG_TYPE_WEBP 11 #define PHP_GD_VERSION_STRING "bundled (2.0.34 compatible)" #define USE_GD_IOCTX 1 #define CTX_PUTC(c,ctx) ctx->putC(ctx, c) #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static req::ptr<File> php_open_plain_file(const String& filename, const char *mode, FILE **fpp) { auto file = File::Open(filename, mode); auto plain_file = dyn_cast_or_null<PlainFile>(file); if (!plain_file) return nullptr; if (FILE* fp = plain_file->getStream()) { if (fpp) *fpp = fp; return file; } file->close(); return nullptr; } static int php_write(void *buf, uint32_t size) { g_context->write((const char *)buf, size); return size; } static void _php_image_output_putc(struct gdIOCtx* /*ctx*/, int c) { /* without the following downcast, the write will fail * (i.e., will write a zero byte) for all * big endian architectures: */ unsigned char ch = (unsigned char) c; php_write(&ch, 1); } static int _php_image_output_putbuf(struct gdIOCtx* /*ctx*/, const void* buf, int len) { return php_write((void *)buf, len); } static void _php_image_output_ctxfree(struct gdIOCtx *ctx) { if (ctx) { IM_FREE(ctx); } } static bool _php_image_output_ctx(const Resource& image, const String& filename, int quality, int basefilter, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp = nullptr; int q = quality, i; int f = basefilter; gdIOCtx *ctx; /* The third (quality) parameter for Wbmp stands for the threshold when called from image2wbmp(). The third (quality) parameter for Wbmp and Xbm stands for the foreground color index when called from imagey<type>(). */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } ctx = gdNewFileCtx(fp); } else { ctx = (gdIOCtx *)IM_MALLOC(sizeof(gdIOCtx)); CHECK_ALLOC_R(ctx, sizeof(gdIOCtx), false); ctx->putC = _php_image_output_putc; ctx->putBuf = _php_image_output_putbuf; ctx->gd_free = _php_image_output_ctxfree; } switch(image_type) { case PHP_GDIMG_CONVERT_WBM: if (q<0||q>255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); } case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, gdIOCtx *, int))(func_p))(im, ctx, q); break; case PHP_GDIMG_TYPE_PNG: ((void(*)(gdImagePtr, gdIOCtx *, int, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_WEBP: ((void(*)(gdImagePtr, gdIOCtx *, int64_t, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_XBM: case PHP_GDIMG_TYPE_WBM: if (q == -1) { // argc < 3 for(i=0; i < gdImageColorsTotal(im); i++) { if (!gdImageRed(im, i) && !gdImageGreen(im, i) && !gdImageBlue(im, i)) break; } q = i; } if (image_type == PHP_GDIMG_TYPE_XBM) { ((void(*)(gdImagePtr, char *, int, gdIOCtx *))(func_p)) (im, (char*)filename.c_str(), q, ctx); } else { ((void(*)(gdImagePtr, int, gdIOCtx *))(func_p))(im, q, ctx); } break; default: ((void(*)(gdImagePtr, gdIOCtx *))(func_p))(im, ctx); break; } ctx->gd_free(ctx); if (fp) { fflush(fp); file->close(); } return true; } /* It converts a gd Image to bw using a threshold value */ static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold) { gdImagePtr im_dest; int white, black; int color, color_org, median; int dest_height = gdImageSY(im_org); int dest_width = gdImageSX(im_org); int x, y; im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate temporary buffer"); return; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } if (im_org->trueColor) { gdImageTrueColorToPalette(im_org, 1, 256); } for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel(im_org, x, y); median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageWBMPCtx (im_dest, black, out); } /* * converts jpeg/png images to wbmp and resizes them as needed */ static bool _php_image_convert(const String& f_org, const String& f_dest, int dest_height, int dest_width, int threshold, int image_type) { gdImagePtr im_org, im_dest, im_tmp; req::ptr<File> org_file, dest_file; FILE *org, *dest; int org_height, org_width; int white, black; int color, color_org, median; int x, y; float x_ratio, y_ratio; #ifdef HAVE_GD_JPG // long ignore_warning; #endif /* Check threshold value */ if (threshold < 0 || threshold > 8) { raise_warning("Invalid threshold value '%d'", threshold); return false; } /* Open origin file */ org_file = php_open_plain_file(f_org, "rb", &org); if (!org_file) { return false; } /* Open destination file */ dest_file = php_open_plain_file(f_dest, "wb", &dest); if (!dest_file) { return false; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid GIF file", f_org.c_str()); return false; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im_org = gdImageCreateFromJpeg(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid JPEG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid PNG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_PNG */ #ifdef HAVE_LIBVPX case PHP_GDIMG_TYPE_WEBP: im_org = gdImageCreateFromWebp(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid webp file", f_org.c_str()); return false; } break; #endif /* HAVE_LIBVPX */ default: raise_warning("Format not supported"); return false; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == nullptr) { raise_warning("Unable to allocate temporary buffer"); return false; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); org_file->close(); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate destination buffer"); return false; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } threshold = threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel(im_dest, x, y, color); } } gdImageDestroy(im_tmp); gdImageWBMP(im_dest, black , dest); fflush(dest); dest_file->close(); gdImageDestroy(im_dest); return true; } // For quality and type, -1 means that the argument does not exist static bool _php_image_output(const Resource& image, const String& filename, int quality, int type, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp; int q = quality, i, t = type; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ /* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */ /* The quality parameter for gd2 stands for chunk size */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, fp); break; case PHP_GDIMG_TYPE_JPG: { // gdImageJpeg ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, fp, q); break; } case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) break; } // gdImageWBMP ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, i, fp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } // gdImageGd ((void(*)(gdImagePtr, FILE *))(func_p))(im, fp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } // gdImageGd2 ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; default: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; } fflush(fp); file->close(); } else { int b; FILE *tmp; char buf[4096]; char path[PATH_MAX]; // open a temporary file snprintf(path, sizeof(path), "/tmp/XXXXXX"); int fd = mkstemp(path); if (fd == -1 || (tmp = fdopen(fd, "r+b")) == nullptr) { if (fd != -1) close(fd); raise_warning("Unable to open temporary file"); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, tmp); break; case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, tmp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) { break; } } ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, q, tmp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, tmp, q, t); break; default: ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; } fseek(tmp, 0, SEEK_SET); while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) { g_context->write(buf, b); } fclose(tmp); /* make sure that the temporary file is removed */ unlink((const char *)path); } return true; } static gdImagePtr _php_image_create_from(const String& filename, int srcX, int srcY, int width, int height, int image_type, char *tn, gdImagePtr(*func_p)(), gdImagePtr(*ioctx_func_p)()) { VMRegAnchor _; gdImagePtr im = nullptr; #ifdef HAVE_GD_JPG // long ignore_warning; #endif if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (width < 1 || height < 1) { raise_warning("Zero width or height not allowed"); return nullptr; } } auto file = File::Open(filename, "rb"); if (!file) { raise_warning("failed to open stream: %s", filename.c_str()); return nullptr; } FILE *fp = nullptr; auto plain_file = dyn_cast<PlainFile>(file); if (plain_file) { fp = plain_file->getStream(); } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; // copy all String buff = file->read(8192); String str; do { str = file->read(8192); buff += str; } while (!str.empty()); if (buff.empty()) { raise_warning("Cannot read image data"); return nullptr; } io_ctx = gdNewDynamicCtxEx(buff.length(), (char *)buff.c_str(), 0); if (!io_ctx) { raise_warning("Cannot allocate GD IO context"); return nullptr; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = ((gdImagePtr(*)(gdIOCtx *, int, int, int, int))(ioctx_func_p)) (io_ctx, srcX, srcY, width, height); } else { im = ((gdImagePtr(*)(gdIOCtx *))(ioctx_func_p))(io_ctx); } io_ctx->gd_free(io_ctx); } else { /* TODO: try and force the stream to be FILE* */ assertx(false); } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = ((gdImagePtr(*)(FILE *, int, int, int, int))(func_p)) (fp, srcX, srcY, width, height); break; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(filename); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im = gdImageCreateFromJpeg(fp); break; #endif default: im = ((gdImagePtr(*)(FILE*))(func_p))(fp); break; } fflush(fp); } if (im) { file->close(); return im; } raise_warning("'%s' is not a valid %s file", filename.c_str(), tn); file->close(); return nullptr; } static const char php_sig_gd2[3] = {'g', 'd', '2'}; /* getmbi ** ------ ** Get a multibyte integer from a generic getin function ** 'getin' can be getc, with in = NULL ** you can find getin as a function just above the main function ** This way you gain a lot of flexibilty about how this package ** reads a wbmp file. */ static int getmbi(gdIOCtx *ctx) { int i, mbi = 0; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); mbi = (mbi << 7) | (i & 0x7f); } while (i & 0x80); return (mbi); } /* skipheader ** ---------- ** Skips the ExtHeader. Not needed for the moment ** */ int skipheader (gdIOCtx *ctx) { int i; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); } while (i & 0x80); return (0); } static int _php_image_type (char data[8]) { if (data == nullptr) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (getmbi(io_ctx) == 0 && skipheader(io_ctx) == 0 ) { io_ctx->gd_free(io_ctx); return PHP_GDIMG_TYPE_WBM; } else { io_ctx->gd_free(io_ctx); } } } return -1; } gdImagePtr _php_image_create_from_string(const String& image, char *tn, gdImagePtr (*ioctx_func_p)()) { VMRegAnchor _; gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(image.length(), (char *)image.c_str(), 0); if (!io_ctx) { return nullptr; } gdImagePtr im = (*(gdImagePtr (*)(gdIOCtx *))ioctx_func_p)(io_ctx); if (!im) { raise_warning("Passed data is not in '%s' format", tn); io_ctx->gd_free(io_ctx); return nullptr; } io_ctx->gd_free(io_ctx); return im; } static gdFontPtr php_find_gd_font(int size) { gdFontPtr font; switch (size) { case 1: font = gdFontTiny; break; case 2: font = gdFontSmall; break; case 3: font = gdFontMediumBold; break; case 4: font = gdFontLarge; break; case 5: font = gdFontGiant; break; default: raise_warning("Unsupported font: %d", size); // font = zend_list_find(size - 5, &ind_type); // if (!font || ind_type != le_gd_font) { if (size < 1) { font = gdFontTiny; } else { font = gdFontGiant; } break; } return font; } /* workaround for a bug in gd 1.2 */ static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy, px, py, fline; cx = 0; cy = 0; if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } /* * arg = 0 ImageChar * arg = 1 ImageCharUp * arg = 2 ImageString * arg = 3 ImageStringUp */ static bool php_imagechar(const Resource& image, int size, int x, int y, const String& c, int color, int mode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ch = 0; gdFontPtr font; if (mode < 2) { ch = (int)((unsigned char)(c.charAt(0))); } font = php_find_gd_font(size); switch (mode) { case 0: gdImageChar(im, font, x, y, ch, color); break; case 1: php_gdimagecharup(im, font, x, y, ch, color); break; case 2: for (int i = 0; (i < c.length()); i++) { gdImageChar(im, font, x, y, (int)((unsigned char)c.charAt(i)), color); x += font->w; } break; case 3: for (int i = 0; (i < c.length()); i++) { gdImageCharUp(im, font, x, y, (int)c.charAt(i), color); y -= font->w; } break; } return true; } /* arg = 0 normal polygon arg = 1 filled polygon */ static bool php_imagepolygon(const Resource& image, const Array& points, int num_points, int color, int filled) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdPointPtr pts; int nelem, i; nelem = points.size(); if (nelem < 6) { raise_warning("You must have at least 3 points in your array"); return false; } if (nelem < num_points * 2) { raise_warning("Trying to use %d points in array with only %d points", num_points, nelem/2); return false; } pts = (gdPointPtr)IM_MALLOC(num_points * sizeof(gdPoint)); CHECK_ALLOC_R(pts, (num_points * sizeof(gdPoint)), false); for (i = 0; i < num_points; i++) { if (points.exists(i * 2)) { pts[i].x = points[i * 2].toInt32(); } if (points.exists(i * 2 + 1)) { pts[i].y = points[i * 2 + 1].toInt32(); } } if (filled) { gdImageFilledPolygon(im, pts, num_points, color); } else { color = SetupAntiAliasedColor(im, color); gdImagePolygon(im, pts, num_points, color); } IM_FREE(pts); return true; } static bool php_image_filter_negate(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageNegate(im) == 1; } static bool php_image_filter_grayscale(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGrayScale(im) == 1; } static bool php_image_filter_brightness(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int brightness = arg1; return gdImageBrightness(im, brightness) == 1; } static bool php_image_filter_contrast(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int contrast = arg1; return gdImageContrast(im, contrast) == 1; } static bool php_image_filter_colorize(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int arg3 /* = 0 */, int /*arg4*/ /* = 0 */) { int r = arg1; int g = arg2; int b = arg3; int a = arg1; return gdImageColor(im, r, g, b, a) == 1; } static bool php_image_filter_edgedetect(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEdgeDetectQuick(im) == 1; } static bool php_image_filter_emboss(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEmboss(im) == 1; } static bool php_image_filter_gaussian_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGaussianBlur(im) == 1; } static bool php_image_filter_selective_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageSelectiveBlur(im) == 1; } static bool php_image_filter_mean_removal(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageMeanRemoval(im) == 1; } static bool php_image_filter_smooth(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int weight = arg1; return gdImageSmooth(im, weight) == 1; } static bool php_image_filter_pixelate(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int blocksize = arg1; unsigned mode = arg2; return gdImagePixelate(im, blocksize, mode) == 1; } /* * arg = 0 ImageFontWidth * arg = 1 ImageFontHeight */ static int php_imagefontsize(int size, int arg) { gdFontPtr font = php_find_gd_font(size); return (arg ? font->h : font->w); } #ifdef ENABLE_GD_TTF #define TTFTEXT_DRAW 0 #define TTFTEXT_BBOX 1 #endif #ifdef ENABLE_GD_TTF static Variant php_imagettftext_common(int mode, int extended, const Variant& arg1, const Variant& arg2, const Variant& arg3, const Variant& arg4, const Variant& arg5 = uninit_variant, const Variant& arg6 = uninit_variant, const Variant& arg7 = uninit_variant, const Variant& arg8 = uninit_variant, const Variant& arg9 = uninit_variant) { gdImagePtr im=nullptr; long col = -1, x = -1, y = -1; int brect[8]; double ptsize, angle; String str; String fontname; Array extrainfo; char *error = nullptr; gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { ptsize = arg1.toDouble(); angle = arg2.toDouble(); fontname = arg3.toString(); str = arg4.toString(); extrainfo = arg5; } else { Resource image = arg1.toResource(); ptsize = arg2.toDouble(); angle = arg3.toDouble(); x = arg4.toInt64(); y = arg5.toInt64(); col = arg6.toInt64(); fontname = arg7.toString(); str = arg8.toString(); extrainfo = arg9; im = get_valid_image_resource(image); if (!im) return false; } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && !extrainfo.empty()) { /* parse extended info */ /* walk the assoc array */ for (ArrayIter iter(extrainfo); iter; ++iter) { Variant key = iter.first(); if (!key.isString()) continue; Variant item = iter.second(); if (equal(key, s_linespacing)) { strex.flags |= gdFTEX_LINESPACE; strex.linespacing = item.toDouble(); } } } FILE *fp = nullptr; if (!RuntimeOption::FontPath.empty()) { fontname = String(RuntimeOption::FontPath.c_str()) + HHVM_FN(basename)(fontname); } auto stream = php_open_plain_file(fontname, "rb", &fp); if (!stream) { raise_warning("Invalid font filename %s", fontname.c_str()); return false; } stream->close(); #ifdef USE_GD_IMGSTRTTF if (extended) { error = gdImageStringFTEx(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str(), &strex); } else { error = gdImageStringFT(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str()); } #else /* !USE_GD_IMGSTRTTF */ error = gdttf(im, brect, col, fontname.c_str(), ptsize, angle, x, y, str.c_str()); #endif if (error) { raise_warning("%s", error); return false; } /* return array with the text's bounding box */ Array ret = Array::CreateDArray(); for (int i = 0; i < 8; i++) { ret.set(i, brect[i]); } return ret; } #endif /* ENABLE_GD_TTF */ const StaticString s_GD_Version("GD Version"), s_FreeType_Support("FreeType Support"), s_FreeType_Linkage("FreeType Linkage"), s_with_freetype("with freetype"), s_with_TTF_library("with TTF library"), s_with_unknown_library("with unknown library"), s_T1Lib_Support("T1Lib_Support"), s_GIF_Read_Support("GIF Read Support"), s_GIF_Create_Support("GIF Create Support"), s_JPG_Support("JPEG Support"), s_PNG_Support("PNG Support"), s_WBMP_Support("WBMP Support"), s_XPM_Support("XPM Support"), s_XBM_Support("XBM Support"), s_JIS_mapped_Japanese_Font_Support("JIS-mapped Japanese Font Support"); Array HHVM_FUNCTION(gd_info) { Array ret = Array::CreateDArray(); ret.set(s_GD_Version, PHP_GD_VERSION_STRING); #ifdef ENABLE_GD_TTF ret.set(s_FreeType_Support, true); #if HAVE_LIBFREETYPE ret.set(s_FreeType_Linkage, s_with_freetype); #elif HAVE_LIBTTF ret.set(s_FreeType_Linkage, s_with_TTF_library); #else ret.set(s_FreeType_Linkage, s_with_unknown_library); #endif #else ret.set(s_FreeType_Support, false); #endif #ifdef HAVE_LIBT1 ret.set(s_T1Lib_Support, true); #else ret.set(s_T1Lib_Support, false); #endif ret.set(s_GIF_Read_Support, true); ret.set(s_GIF_Create_Support, true); #ifdef HAVE_GD_JPG ret.set(s_JPG_Support, true); #else ret.set(s_JPG_Support, false); #endif #ifdef HAVE_GD_PNG ret.set(s_PNG_Support, true); #else ret.set(s_PNG_Support, false); #endif ret.set(s_WBMP_Support, true); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret.set(s_XPM_Support, true); #else ret.set(s_XPM_Support, false); #endif ret.set(s_XBM_Support, true); #if defined(USE_GD_JISX0208) && defined(HAVE_GD_BUNDLED) ret.set(s_JIS_mapped_Japanese_Font_Support, true); #else ret.set(s_JIS_mapped_Japanese_Font_Support, false); #endif return ret; } #define FLIPWORD(a) (((a & 0xff000000) >> 24) | \ ((a & 0x00ff0000) >> 8) | \ ((a & 0x0000ff00) << 8) | \ ((a & 0x000000ff) << 24)) Variant HHVM_FUNCTION(imageloadfont, const String& /*file*/) { // TODO: ind = 5 + zend_list_insert(font, le_gd_font); throw_not_supported(__func__, "NYI"); #ifdef NEVER Variant stream; zval **file; int hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; stream = File::Open(file, "rb"); if (!stream) { raise_warning("failed to open file: %s", file.c_str()); return false; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) IM_MALLOC(sizeof(gdFont)); CHECK_ALLOC_R(font, sizeof(gdFont), false); b = 0; String hdr = stream->read(hdr_size); if (hdr.length() < hdr_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading header"); } else { raise_warning("Error while reading header"); } stream->close(); return false; } memcpy((void*)font, hdr.c_str(), hdr.length()); i = int64_t(f_tell(stream)); stream->seek(0, SEEK_END); body_size_check = int64_t(f_tell(stream)) - hdr_size; stream->seek(i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (font->nchars <= 0 || font->h <= 0 || font->nchars >= INT_MAX || font->h >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if ((font->nchars * font->h) <= 0 || font->w <= 0 || (font->nchars * font->h) >= INT_MAX || font->w >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if (body_size != body_size_check) { raise_warning("Error reading font"); IM_FREE(font); stream->close(); return false; } String body = stream->read(body_size); if (body.length() < body_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading body"); } else { raise_warning("Error while reading body"); } stream->close(); return false; } font->data = IM_MALLOC(body_size); CHECK_ALLOC_R(font->data, body_size, false); memcpy((void*)font->data, body.c_str(), body.length()); stream->close(); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ // ind = 5 + zend_list_insert(font, le_gd_font); return ind; #endif } bool HHVM_FUNCTION(imagesetstyle, const Resource& image, const Array& style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int *stylearr; int index; size_t malloc_size = sizeof(int) * style.size(); stylearr = (int *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(stylearr, malloc_size, false); index = 0; for (ArrayIter iter(style); iter; ++iter) { stylearr[index++] = cellToInt(tvToCell(iter.secondVal())); } gdImageSetStyle(im, stylearr, index); IM_FREE(stylearr); return true; } const StaticString s_x("x"), s_y("y"), s_width("width"), s_height("height"); Variant HHVM_FUNCTION(imagecrop, const Resource& image, const Array& rect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; gdRect gdrect; if (rect.exists(s_x)) { gdrect.x = rect[s_x].toInt64(); } else { raise_warning("imagecrop(): Missing x position"); return false; } if (rect.exists(s_y)) { gdrect.y = rect[s_y].toInt64(); } else { raise_warning("imagecrop(): Missing y position"); return false; } if (rect.exists(s_width)) { gdrect.width = rect[s_width].toInt64(); } else { raise_warning("imagecrop(): Missing width position"); return false; } if (rect.exists(s_height)) { gdrect.height = rect[s_height].toInt64(); } else { raise_warning("imagecrop(): Missing height position"); return false; } imcropped = gdImageCrop(im, &gdrect); if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecropauto, const Resource& image, int64_t mode /* = -1 */, double threshold /* = 0.5f */, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; switch (mode) { case -1: mode = GD_CROP_DEFAULT; case GD_CROP_DEFAULT: case GD_CROP_TRANSPARENT: case GD_CROP_BLACK: case GD_CROP_WHITE: case GD_CROP_SIDES: imcropped = gdImageCropAuto(im, mode); break; case GD_CROP_THRESHOLD: if (color < 0) { raise_warning("imagecropauto(): Color argument missing " "with threshold mode"); return false; } imcropped = gdImageCropThreshold(im, color, (float) threshold); break; default: raise_warning("imagecropauto(): Unknown crop mode"); return false; } if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecreatetruecolor, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreateTrueColor(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } bool f_imageistruecolor(const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return im->trueColor; } Variant HHVM_FUNCTION(imagetruecolortopalette, const Resource& image, bool dither, int64_t ncolors) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (ncolors <= 0 || ncolors >= INT_MAX) { raise_warning("Number of colors has to be greater than zero"); return false; } gdImageTrueColorToPalette(im, dither, ncolors); return true; } Variant HHVM_FUNCTION(imagecolormatch, const Resource& image1, const Resource& image2) { gdImagePtr im1 = get_valid_image_resource(image1); if (!im1) return false; gdImagePtr im2 = get_valid_image_resource(image2); if (!im2) return false; int result; result = gdImageColorMatch(im1, im2); switch (result) { case -1: raise_warning("Image1 must be TrueColor"); return false; case -2: raise_warning("Image2 must be Palette"); return false; case -3: raise_warning("Image1 and Image2 must be the same size"); return false; case -4: raise_warning("Image2 must have at least one color"); return false; } return true; } bool HHVM_FUNCTION(imagesetthickness, const Resource& image, int64_t thickness) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetThickness(im, thickness); return true; } bool HHVM_FUNCTION(imagefilledellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledEllipse(im, cx, cy, width, height, color); return true; } bool HHVM_FUNCTION(imagefilledarc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color, int64_t style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; gdImageFilledArc(im, cx, cy, width, height, start, end, color, style); return true; } Variant HHVM_FUNCTION(imageaffine, const Resource& image, const Array& affine /* = Array() */, const Array& clip /* = Array() */) { gdImagePtr src = get_valid_image_resource(image); if (!src) return false; gdImagePtr dst = nullptr; gdRect rect; gdRectPtr pRect = nullptr; int nelem = affine.size(); int i; double daffine[6]; if (nelem != 6) { raise_warning("imageaffine(): Affine array must have six elements"); return false; } for (i = 0; i < nelem; i++) { if (affine[i].isInteger()) { daffine[i] = affine[i].toInt64(); } else if (affine[i].isDouble() || affine[i].isString()) { daffine[i] = affine[i].toDouble(); } else { raise_warning("imageaffine(): Invalid type for element %i", i); return false; } } if (!clip.empty()) { if (clip.exists(s_x)) { rect.x = clip[s_x].toInt64(); } else { raise_warning("imageaffine(): Missing x position"); return false; } if (clip.exists(s_y)) { rect.y = clip[s_y].toInt64(); } else { raise_warning("imageaffine(): Missing y position"); return false; } if (clip.exists(s_width)) { rect.width = clip[s_width].toInt64(); } else { raise_warning("imageaffine(): Missing width position"); return false; } if (clip.exists(s_height)) { rect.height = clip[s_height].toInt64(); } else { raise_warning("imageaffine(): Missing height position"); return false; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = nullptr; } if (gdTransformAffineGetImage(&dst, src, pRect, daffine) != GD_TRUE) { return false; } return Variant(req::make<Image>(dst)); } Variant HHVM_FUNCTION(imageaffinematrixconcat, const Array& m1, const Array& m2) { int nelem1 = m1.size(); int nelem2 = m2.size(); int i; double dm1[6]; double dm2[6]; double dmr[6]; Array ret = Array::Create(); if (nelem1 != 6 || nelem2 != 6) { raise_warning("imageaffinematrixconcat(): Affine array must " "have six elements"); return false; } for (i = 0; i < 6; i++) { if (m1[i].isInteger()) { dm1[i] = m1[i].toInt64(); } else if (m1[i].isDouble() || m1[i].isString()) { dm1[i] = m1[i].toDouble(); } else { raise_warning("imageaffinematrixconcat(): Invalid type for " "element %i", i); return false; } if (m2[i].isInteger()) { dm2[i] = m2[i].toInt64(); } else if (m2[i].isDouble() || m2[i].isString()) { dm2[i] = m2[i].toDouble(); } else { raise_warning("imageaffinematrixconcat():Invalid type for" "element %i", i); return false; } } if (gdAffineConcat(dmr, dm1, dm2) != GD_TRUE) { return false; } for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), dmr[i]); } return ret; } Variant HHVM_FUNCTION(imageaffinematrixget, int64_t type, const Variant& options /* = Array() */) { Array ret = Array::Create(); double affine[6]; int res = GD_FALSE, i; switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; Array aoptions = options.toArray(); if (aoptions.empty()) { raise_warning("imageaffinematrixget(): Array expected as options"); return false; } if (aoptions.exists(s_x)) { x = aoptions[s_x].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (aoptions.exists(s_y)) { y = aoptions[s_y].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; double doptions = options.toDouble(); if (!doptions) { raise_warning("imageaffinematrixget(): Number is expected as option"); return false; } angle = doptions; if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: raise_warning("imageaffinematrixget():Invalid type for " "element %" PRId64, type); return false; } if (res == GD_FALSE) { return false; } else { for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), affine[i]); } } return ret; } bool HHVM_FUNCTION(imagealphablending, const Resource& image, bool blendmode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, blendmode); return true; } bool HHVM_FUNCTION(imagesavealpha, const Resource& image, bool saveflag) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSaveAlpha(im, saveflag); return true; } bool HHVM_FUNCTION(imagelayereffect, const Resource& image, int64_t effect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, effect); return true; } Variant HHVM_FUNCTION(imagecolorallocatealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagecolorresolvealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolveAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorclosestalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorexactalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExactAlpha(im, red, green, blue, alpha); } bool HHVM_FUNCTION(imagecopyresampled, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = get_valid_image_resource(src_im); if (!im_src) return false; gdImagePtr im_dst = get_valid_image_resource(dst_im); if (!im_dst) return false; gdImageCopyResampled(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagerotate, const Resource& source_image, double angle, int64_t bgd_color, int64_t /*ignore_transparent*/ /* = 0 */) { gdImagePtr im_src = get_valid_image_resource(source_image); if (!im_src) return false; gdImagePtr im_dst = gdImageRotateInterpolated(im_src, angle, bgd_color); if (!im_dst) return false; return Variant(req::make<Image>(im_dst)); } bool HHVM_FUNCTION(imagesettile, const Resource& image, const Resource& tile) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr til = get_valid_image_resource(tile); if (!til) return false; gdImageSetTile(im, til); return true; } bool HHVM_FUNCTION(imagesetbrush, const Resource& image, const Resource& brush) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr tile = get_valid_image_resource(brush); if (!tile) return false; gdImageSetBrush(im, tile); return true; } bool HHVM_FUNCTION(imagesetinterpolation, const Resource& image, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (method == -1) method = GD_BILINEAR_FIXED; return gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method); } Variant HHVM_FUNCTION(imagecreate, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreate(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } int64_t HHVM_FUNCTION(imagetypes) { int ret=0; ret = IMAGE_TYPE_GIF; #ifdef HAVE_GD_JPG ret |= IMAGE_TYPE_JPEG; #endif #ifdef HAVE_GD_PNG ret |= IMAGE_TYPE_PNG; #endif ret |= IMAGE_TYPE_WBMP; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret |= IMAGE_TYPE_XPM; #endif return ret; } Variant HHVM_FUNCTION(imagecreatefromstring, const String& data) { gdImagePtr im; int imtype; char sig[8]; if (data.length() < 8) { raise_warning("Empty string or invalid image"); return false; } memcpy(sig, data.c_str(), 8); imtype = _php_image_type(sig); switch (imtype) { case PHP_GDIMG_TYPE_JPG: #ifdef HAVE_GD_JPG im = _php_image_create_from_string(data, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpegCtx); #else raise_warning("No JPEG support"); return false; #endif break; case PHP_GDIMG_TYPE_PNG: #ifdef HAVE_GD_PNG im = _php_image_create_from_string(data, "PNG", (gdImagePtr(*)())gdImageCreateFromPngCtx); #else raise_warning("No PNG support"); return false; #endif break; case PHP_GDIMG_TYPE_WEBP: #ifdef HAVE_LIBVPX im = _php_image_create_from_string(data, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebpCtx); #else raise_warning("No webp support (libvpx is needed)"); return false; #endif break; case PHP_GDIMG_TYPE_GIF: im = _php_image_create_from_string(data, "GIF", (gdImagePtr(*)())gdImageCreateFromGifCtx); break; case PHP_GDIMG_TYPE_WBM: im = _php_image_create_from_string(data, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMPCtx); break; case PHP_GDIMG_TYPE_GD2: im = _php_image_create_from_string(data, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Ctx); break; default: raise_warning("Data is not in a recognized format"); return false; } if (!im) { raise_warning("Couldn't create GD Image Stream out of Data"); return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgif, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (gdImagePtr(*)())gdImageCreateFromGif, (gdImagePtr(*)())gdImageCreateFromGifCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #ifdef HAVE_GD_JPG Variant HHVM_FUNCTION(imagecreatefromjpeg, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpeg, (gdImagePtr(*)())gdImageCreateFromJpegCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_GD_PNG Variant HHVM_FUNCTION(imagecreatefrompng, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_PNG, "PNG", (gdImagePtr(*)())gdImageCreateFromPng, (gdImagePtr(*)())gdImageCreateFromPngCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_LIBVPX Variant HHVM_FUNCTION(imagecreatefromwebp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebp, (gdImagePtr(*)())gdImageCreateFromWebpCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromxbm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XBM, "XBM", (gdImagePtr(*)())gdImageCreateFromXbm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) Variant HHVM_FUNCTION(imagecreatefromxpm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XPM, "XPM", (gdImagePtr(*)())gdImageCreateFromXpm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromwbmp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMP, (gdImagePtr(*)())gdImageCreateFromWBMPCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (gdImagePtr(*)())gdImageCreateFromGd, (gdImagePtr(*)())gdImageCreateFromGdCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD2, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2, (gdImagePtr(*)())gdImageCreateFromGd2Ctx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2part, const String& filename, int64_t srcx, int64_t srcy, int64_t width, int64_t height) { gdImagePtr im = _php_image_create_from(filename, srcx, srcy, width, height, PHP_GDIMG_TYPE_GD2PART, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Part, (gdImagePtr(*)())gdImageCreateFromGd2PartCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } bool HHVM_FUNCTION(imagegif, const Resource& image, const String& filename /* = null_string */) { return _php_image_output_ctx(image, filename, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (void (*)())gdImageGifCtx); } #ifdef HAVE_GD_PNG bool HHVM_FUNCTION(imagepng, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */, int64_t filters /* = -1 */) { return _php_image_output_ctx(image, filename, quality, filters, PHP_GDIMG_TYPE_PNG, "PNG", (void (*)())gdImagePngCtxEx); } #endif #ifdef HAVE_LIBVPX bool HHVM_FUNCTION(imagewebp, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = 80 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (void (*)())gdImageWebpCtx); } #endif #ifdef HAVE_GD_JPG bool HHVM_FUNCTION(imagejpeg, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (void (*)())gdImageJpegCtx); } #endif bool HHVM_FUNCTION(imagewbmp, const Resource& image, const String& filename /* = null_string */, int64_t foreground /* = -1 */) { return _php_image_output_ctx(image, filename, foreground, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (void (*)())gdImageWBMPCtx); } bool HHVM_FUNCTION(imagegd, const Resource& image, const String& filename /* = null_string */) { return _php_image_output(image, filename, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (void (*)())gdImageGd); } bool HHVM_FUNCTION(imagegd2, const Resource& image, const String& filename /* = null_string */, int64_t chunk_size /* = 0 */, int64_t type /* = 0 */) { return _php_image_output(image, filename, chunk_size, type, PHP_GDIMG_TYPE_GD2, "GD2", (void (*)())gdImageGd2); } bool HHVM_FUNCTION(imagedestroy, const Resource& image) { auto img_res = cast<Image>(image); gdImagePtr im = img_res->get(); if (!im) return false; img_res->reset(); return true; } Variant HHVM_FUNCTION(imagecolorallocate, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocate(im, red, green, blue); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagepalettecopy, const Resource& dst, const Resource& src) { gdImagePtr dstim = cast<Image>(dst)->get(); gdImagePtr srcim = cast<Image>(src)->get(); if (!dstim || !srcim) return false; gdImagePaletteCopy(dstim, srcim); return true; } Variant HHVM_FUNCTION(imagecolorat, const Resource& image, int64_t x, int64_t y) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (gdImageTrueColor(im)) { if (im->tpixels && gdImageBoundsSafe(im, x, y)) { return gdImageTrueColorPixel(im, x, y); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } else { if (im->pixels && gdImageBoundsSafe(im, x, y)) { return (im->pixels[y][x]); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } } Variant HHVM_FUNCTION(imagecolorclosest, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosest(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorclosesthwb, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestHWB(im, red, green, blue); } bool HHVM_FUNCTION(imagecolordeallocate, const Resource& image, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; /* We can return right away for a truecolor image as deallocating colours is meaningless here */ if (gdImageTrueColor(im)) return true; if (color >= 0 && color < gdImageColorsTotal(im)) { gdImageColorDeallocate(im, color); return true; } else { raise_warning("Color index %" PRId64 " out of range", color); return false; } } Variant HHVM_FUNCTION(imagecolorresolve, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolve(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorexact, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExact(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorset, const Resource& image, int64_t index, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && index < gdImageColorsTotal(im)) { im->red[index] = red; im->green[index] = green; im->blue[index] = blue; return true; } else { return false; } } const StaticString s_red("red"), s_green("green"), s_blue("blue"), s_alpha("alpha"); Variant HHVM_FUNCTION(imagecolorsforindex, const Resource& image, int64_t index) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && (gdImageTrueColor(im) || index < gdImageColorsTotal(im))) { return make_map_array( s_red, gdImageRed(im,index), s_green, gdImageGreen(im,index), s_blue, gdImageBlue(im,index), s_alpha, gdImageAlpha(im,index) ); } raise_warning("Color index %" PRId64 " out of range", index); return false; } bool HHVM_FUNCTION(imagegammacorrect, const Resource& image, double inputgamma, double outputgamma) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (inputgamma <= 0.0 || outputgamma <= 0.0) { raise_warning("Gamma values should be positive"); return false; } if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColor((int)((pow((pow((gdTrueColorGetRed(c)/255.0), inputgamma)),1.0/outputgamma)*255) + .5), (int)((pow((pow((gdTrueColorGetGreen(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5), (int)((pow((pow((gdTrueColorGetBlue(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5))); } } return true; } for (int i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->green[i] = (int)((pow((pow((im->green[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); } return true; } bool HHVM_FUNCTION(imagesetpixel, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetPixel(im, x, y, color); return true; } bool HHVM_FUNCTION(imageline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagedashedline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageDashedLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagerectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagefilledrectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagearc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, start, end, color); return true; } bool HHVM_FUNCTION(imageellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, 0, 360, color); return true; } bool HHVM_FUNCTION(imagefilltoborder, const Resource& image, int64_t x, int64_t y, int64_t border, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFillToBorder(im, x, y, border, color); return true; } bool HHVM_FUNCTION(imagefill, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFill(im, x, y, color); return true; } Variant HHVM_FUNCTION(imagecolorstotal, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return (gdImageColorsTotal(im)); } Variant HHVM_FUNCTION(imagecolortransparent, const Resource& image, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (color != -1) { // has color argument gdImageColorTransparent(im, color); } return gdImageGetTransparent(im); } TypedValue HHVM_FUNCTION(imageinterlace, const Resource& image, TypedValue interlace /* = 0 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return make_tv<KindOfBoolean>(false); if (!tvIsNull(interlace)) { // has interlace argument gdImageInterlace(im, tvAssertInt(interlace)); } return make_tv<KindOfInt64>(gdImageGetInterlaced(im)); } bool HHVM_FUNCTION(imagepolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 0); } bool HHVM_FUNCTION(imagefilledpolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 1); } int64_t HHVM_FUNCTION(imagefontwidth, int64_t font) { return php_imagefontsize(font, 0); } int64_t HHVM_FUNCTION(imagefontheight, int64_t font) { return php_imagefontsize(font, 1); } bool HHVM_FUNCTION(imagechar, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 0); } bool HHVM_FUNCTION(imagecharup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 1); } bool HHVM_FUNCTION(imagestring, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 2); } bool HHVM_FUNCTION(imagestringup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 3); } bool HHVM_FUNCTION(imagecopy, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopy(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h); return true; } bool HHVM_FUNCTION(imagecopymerge, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMerge(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopymergegray, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMergeGray(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopyresized, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; if (dst_w <= 0 || dst_h <= 0 || src_w <= 0 || src_h <= 0) { raise_warning("Invalid image dimensions"); return false; } gdImageCopyResized(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagesx, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSX(im); } Variant HHVM_FUNCTION(imagesy, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSY(im); } #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE Variant HHVM_FUNCTION(imageftbbox, double size, double angle, const String& font_file, const String& text, const Array& extrainfo /*=[] */) { return php_imagettftext_common(TTFTEXT_BBOX, 1, size, angle, font_file, text, extrainfo); } Variant HHVM_FUNCTION(imagefttext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t col, const String& font_file, const String& text, const Array& extrainfo) { return php_imagettftext_common(TTFTEXT_DRAW, 1, image, size, angle, x, y, col, font_file, text, extrainfo); } #endif #ifdef ENABLE_GD_TTF Variant HHVM_FUNCTION(imagettfbbox, double size, double angle, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_BBOX, 0, size, angle, fontfile, text); } Variant HHVM_FUNCTION(imagettftext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t color, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_DRAW, 0, image, size.toDouble(), angle.toDouble(), x, y, color, fontfile, text); } #endif bool HHVM_FUNCTION(image2wbmp, const Resource& image, const String& filename /* = null_string */, int64_t threshold /* = -1 */) { return _php_image_output(image, filename, threshold, -1, PHP_GDIMG_CONVERT_WBM, "WBMP", (void (*)())_php_image_bw_convert); } bool HHVM_FUNCTION(jpeg2wbmp, const String& jpegname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(jpegname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_JPG); } bool HHVM_FUNCTION(png2wbmp, const String& pngname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(pngname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_PNG); } bool HHVM_FUNCTION(imagefilter, const Resource& res, int64_t filtertype, const Variant& arg1 /*=0*/, const Variant& arg2 /*=0*/, const Variant& arg3 /*=0*/, const Variant& arg4 /*=0*/) { gdImagePtr im = get_valid_image_resource(res); if (!im) return false; /* Exists purely to mirror PHP5's invalid arg logic for this function */ #define IMFILT_TYPECHK(n) \ if (!arg##n.isBoolean() && !arg##n.isNumeric(true)) { \ raise_warning("imagefilter() expected boolean/numeric for argument %d", \ (n+2)); \ return false; \ } IMFILT_TYPECHK(1) IMFILT_TYPECHK(2) IMFILT_TYPECHK(3) IMFILT_TYPECHK(4) #undef IMFILT_TYPECHECK using image_filter = bool (*)(gdImagePtr, int, int, int, int); image_filter filters[] = { php_image_filter_negate, php_image_filter_grayscale, php_image_filter_brightness, php_image_filter_contrast, php_image_filter_colorize, php_image_filter_edgedetect, php_image_filter_emboss, php_image_filter_gaussian_blur, php_image_filter_selective_blur, php_image_filter_mean_removal, php_image_filter_smooth, php_image_filter_pixelate, }; auto const num_filters = sizeof(filters) / sizeof(image_filter); if (filtertype >= 0 && filtertype < num_filters) { return filters[filtertype](im, arg1.toInt64(), arg2.toInt64(), arg3.toInt64(), arg4.toInt64()); } return false; } bool HHVM_FUNCTION(imageflip, const Resource& image, int64_t mode /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (mode == -1) mode = GD_FLIP_HORINZONTAL; switch (mode) { case GD_FLIP_VERTICAL: gdImageFlipVertical(im); break; case GD_FLIP_HORINZONTAL: gdImageFlipHorizontal(im); break; case GD_FLIP_BOTH: gdImageFlipBoth(im); break; default: raise_warning("imageflip(): Unknown flip mode"); return false; } return true; } // gdImageConvolution does not exist in our libgd.a, copied from // php's libgd/gd.c /* Filters function added on 2003/12 * by Pierre-Alain Joye (pajoye@pearfr.org) **/ static int hphp_gdImageConvolution(gdImagePtr src, float filter[3][3], float filter_div, float offset) { int x, y, i, j, new_a; float new_r, new_g, new_b; int new_pxl, pxl=0; gdImagePtr srcback; if (src==nullptr) { return 0; } /* We need the orinal image with each safe neoghb. pixel */ srcback = gdImageCreateTrueColor (src->sx, src->sy); gdImageCopy(srcback, src,0,0,0,0,src->sx,src->sy); if (srcback==nullptr) { return 0; } for ( y=0; y<src->sy; y++) { for(x=0; x<src->sx; x++) { new_r = new_g = new_b = 0; new_a = gdImageAlpha(srcback, pxl); for (j=0; j<3; j++) { int yv = std::min(std::max(y - 1 + j, 0), src->sy - 1); for (i=0; i<3; i++) { pxl = gdImageGetPixel(srcback, std::min(std::max(x - 1 + i, 0), src->sx - 1), yv); new_r += (float)gdImageRed(srcback, pxl) * filter[j][i]; new_g += (float)gdImageGreen(srcback, pxl) * filter[j][i]; new_b += (float)gdImageBlue(srcback, pxl) * filter[j][i]; } } new_r = (new_r/filter_div)+offset; new_g = (new_g/filter_div)+offset; new_b = (new_b/filter_div)+offset; new_r = (new_r > 255.0f)? 255.0f : ((new_r < 0.0f)? 0.0f:new_r); new_g = (new_g > 255.0f)? 255.0f : ((new_g < 0.0f)? 0.0f:new_g); new_b = (new_b > 255.0f)? 255.0f : ((new_b < 0.0f)? 0.0f:new_b); new_pxl = gdImageColorAllocateAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); if (new_pxl == -1) { new_pxl = gdImageColorClosestAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); } gdImageSetPixel (src, x, y, new_pxl); } } gdImageDestroy(srcback); return 1; } bool HHVM_FUNCTION(imageconvolution, const Resource& image, const Array& matrix, double div, double offset) { gdImagePtr im_src = cast<Image>(image)->get(); if (!im_src) return false; int nelem = matrix.size(); int i, j; float mtx[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; Variant v; Array row; if (nelem != 3) { raise_warning("You must have 3x3 array"); return false; } for (i=0; i<3; i++) { if (matrix.exists(i) && (v = matrix[i]).isArray()) { if ((row = v.toArray()).size() != 3) { raise_warning("You must have 3x3 array"); return false; } for (j=0; j<3; j++) { if (row.exists(j)) { mtx[i][j] = row[j].toDouble(); } else { raise_warning("You must have a 3x3 matrix"); return false; } } } } if (hphp_gdImageConvolution(im_src, mtx, div, offset)) { return true; } else { return false; } } bool HHVM_FUNCTION(imageantialias, const Resource& image, bool on) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; SetAntiAliased(im, on); return true; } Variant HHVM_FUNCTION(imagescale, const Resource& image, int64_t newwidth, int64_t newheight /* =-1 */, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imscaled = nullptr; gdInterpolationMethod old_method; if (method == -1) method = GD_BILINEAR_FIXED; if (newheight < 0) { /* preserve ratio */ long src_x, src_y; src_x = gdImageSX(im); src_y = gdImageSY(im); if (src_x) { newheight = newwidth * src_y / src_x; } } if (newheight <= 0 || newheight > INT_MAX || newwidth <= 0 || newwidth > INT_MAX) { return false; } old_method = im->interpolation_id; if (gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method)) { imscaled = gdImageScale(im, newwidth, newheight); } gdImageSetInterpolationMethod(im, old_method); if (imscaled == nullptr) { return false; } return Variant(req::make<Image>(imscaled)); } namespace { // PHP extension STANDARD: iptc.c inline int php_iptc_put1(req::ptr<File> /*file*/, int spool, unsigned char c, unsigned char** spoolbuf) { if (spool > 0) { g_context->write((const char *)&c, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_get1(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; char cc; c = file->getc(); if (c == EOF) return EOF; if (spool > 0) { cc = c; g_context->write((const char *)&cc, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_read_remaining(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { while (php_iptc_get1(file, spool, spoolbuf) != EOF) continue; return M_EOI; } int php_iptc_skip_variable(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { unsigned int length; int c1, c2; if ((c1 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; if ((c2 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) { if (php_iptc_get1(file, spool, spoolbuf) == EOF) return M_EOI; } return 0; } int php_iptc_next_marker(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; /* skip unimportant stuff */ c = php_iptc_get1(file, spool, spoolbuf); if (c == EOF) return M_EOI; while (c != 0xff) { if ((c = php_iptc_get1(file, spool, spoolbuf)) == EOF) { return M_EOI; /* we hit EOF */ } } /* get marker byte, swallowing possible padding */ do { c = php_iptc_get1(file, 0, 0); if (c == EOF) return M_EOI; /* we hit EOF */ else if (c == 0xff) php_iptc_put1(file, spool, (unsigned char)c, spoolbuf); } while (c == 0xff); return (unsigned int) c; } } const StaticString s_size("size"); Variant HHVM_FUNCTION(iptcembed, const String& iptcdata, const String& jpeg_file_name, int64_t spool /* = 0 */) { char psheader[] = "\xFF\xED\0\0Photoshop 3.0\08BIM\x04\x04\0\0\0"; static_assert(sizeof(psheader) == 28, "psheader must be 28 bytes"); unsigned int iptcdata_len = iptcdata.length(); unsigned int marker, inx; unsigned char *spoolbuf = nullptr, *poi = nullptr; bool done = false; bool written = false; auto file = File::Open(jpeg_file_name, "rb"); if (!file) { raise_warning("failed to open file: %s", jpeg_file_name.c_str()); return false; } if (spool < 2) { auto stat = HHVM_FN(fstat)(Resource(file)); // TODO(t7561579) until we can properly handle non-file streams here, don't // pretend we can and crash. if (!stat.isArray()) { raise_warning("unable to stat input"); return false; } auto& stat_arr = stat.toCArrRef(); auto st_size = stat_arr[s_size].toInt64(); if (st_size < 0) { raise_warning("unsupported stream type"); return false; } if (iptcdata_len >= (INT64_MAX - sizeof(psheader) - st_size - 1024 - 1)) { raise_warning("iptcdata too long"); return false; } auto malloc_size = iptcdata_len + sizeof(psheader) + st_size + 1024 + 1; poi = spoolbuf = (unsigned char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(poi, malloc_size, false); memset(poi, 0, malloc_size); } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xFF) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xD8) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } while (!done) { marker = php_iptc_next_marker(file, spool, poi?&poi:0); if (marker == M_EOI) { /* EOF */ break; } else if (marker != M_APP13) { php_iptc_put1(file, spool, (unsigned char)marker, poi?&poi:0); } switch (marker) { case M_APP13: /* we are going to write a new APP13 marker, so don't output the old one */ php_iptc_skip_variable(file, 0, 0); php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; case M_APP0: /* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */ case M_APP1: if (written) { /* don't try to write the data twice */ break; } written = true; php_iptc_skip_variable(file, spool, poi?&poi:0); if (iptcdata_len & 1) { iptcdata_len++; /* make the length even */ } psheader[2] = (iptcdata_len + sizeof(psheader)) >> 8; psheader[3] = (iptcdata_len + sizeof(psheader)) & 0xff; for (inx = 0; inx < sizeof(psheader); inx++) { php_iptc_put1(file, spool, psheader[inx], poi ? &poi : 0); } php_iptc_put1(file, spool, (unsigned char)(iptcdata_len>>8), poi?&poi:0); php_iptc_put1(file, spool, (unsigned char)(iptcdata_len&0xff), poi?&poi:0); for (inx = 0; inx < iptcdata_len; inx++) { php_iptc_put1(file, spool, iptcdata.c_str()[inx], poi?&poi:0); } break; case M_SOS: /* we hit data, no more marker-inserting can be done! */ php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; default: php_iptc_skip_variable(file, spool, poi?&poi:0); break; } } file->close(); if (spool < 2) { return String((char *)spoolbuf, poi - spoolbuf, AttachString); } return true; } Variant HHVM_FUNCTION(iptcparse, const String& iptcblock) { unsigned int inx = 0, len, tagsfound = 0; unsigned char *buffer, recnum, dataset, key[16]; unsigned int str_len = iptcblock.length(); Array ret; buffer = (unsigned char *)iptcblock.c_str(); while (inx < str_len) { /* find 1st tag */ if ((buffer[inx] == 0x1c) && ((buffer[inx+1] == 0x01) || (buffer[inx+1] == 0x02))) { break; } else { inx++; } } while (inx < str_len) { if (buffer[ inx++ ] != 0x1c) { /* we ran against some data which does not conform to IPTC - stop parsing! */ break; } if ((inx + 4) >= str_len) break; dataset = buffer[inx++]; recnum = buffer[inx++]; if (buffer[inx] & (unsigned char) 0x80) { /* long tag */ if (inx + 6 >= str_len) break; len = (((long)buffer[inx + 2]) << 24) + (((long)buffer[inx + 3]) << 16) + (((long)buffer[inx + 4]) << 8) + (((long)buffer[inx + 5])); inx += 6; } else { /* short tag */ len = (((unsigned short)buffer[inx])<<8) | (unsigned short)buffer[inx+1]; inx += 2; } snprintf((char *)key, sizeof(key), "%d#%03d", (unsigned int)dataset, (unsigned int)recnum); if ((len > str_len) || (inx + len) > str_len) { break; } String skey((const char *)key, CopyString); if (!ret.exists(skey)) { ret.set(skey, Array::CreateVArray()); } auto const lval = ret.lvalAt(skey); forceToArray(lval).append( String((const char *)(buffer+inx), len, CopyString)); inx += len; tagsfound++; } if (!tagsfound) { return false; } return ret; } // PHP extension exif.c #define NUM_FORMATS 13 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 #define TAG_FMT_IFD 13 /* Describes tag values */ #define TAG_GPS_VERSION_ID 0x0000 #define TAG_GPS_LATITUDE_REF 0x0001 #define TAG_GPS_LATITUDE 0x0002 #define TAG_GPS_LONGITUDE_REF 0x0003 #define TAG_GPS_LONGITUDE 0x0004 #define TAG_GPS_ALTITUDE_REF 0x0005 #define TAG_GPS_ALTITUDE 0x0006 #define TAG_GPS_TIME_STAMP 0x0007 #define TAG_GPS_SATELLITES 0x0008 #define TAG_GPS_STATUS 0x0009 #define TAG_GPS_MEASURE_MODE 0x000A #define TAG_GPS_DOP 0x000B #define TAG_GPS_SPEED_REF 0x000C #define TAG_GPS_SPEED 0x000D #define TAG_GPS_TRACK_REF 0x000E #define TAG_GPS_TRACK 0x000F #define TAG_GPS_IMG_DIRECTION_REF 0x0010 #define TAG_GPS_IMG_DIRECTION 0x0011 #define TAG_GPS_MAP_DATUM 0x0012 #define TAG_GPS_DEST_LATITUDE_REF 0x0013 #define TAG_GPS_DEST_LATITUDE 0x0014 #define TAG_GPS_DEST_LONGITUDE_REF 0x0015 #define TAG_GPS_DEST_LONGITUDE 0x0016 #define TAG_GPS_DEST_BEARING_REF 0x0017 #define TAG_GPS_DEST_BEARING 0x0018 #define TAG_GPS_DEST_DISTANCE_REF 0x0019 #define TAG_GPS_DEST_DISTANCE 0x001A #define TAG_GPS_PROCESSING_METHOD 0x001B #define TAG_GPS_AREA_INFORMATION 0x001C #define TAG_GPS_DATE_STAMP 0x001D #define TAG_GPS_DIFFERENTIAL 0x001E #define TAG_TIFF_COMMENT 0x00FE /* SHOUDLNT HAPPEN */ #define TAG_NEW_SUBFILE 0x00FE /* New version of subfile tag */ #define TAG_SUBFILE_TYPE 0x00FF /* Old version of subfile tag */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 #define TAG_BITS_PER_SAMPLE 0x0102 #define TAG_COMPRESSION 0x0103 #define TAG_PHOTOMETRIC_INTERPRETATION 0x0106 #define TAG_TRESHHOLDING 0x0107 #define TAG_CELL_WIDTH 0x0108 #define TAG_CELL_HEIGHT 0x0109 #define TAG_FILL_ORDER 0x010A #define TAG_DOCUMENT_NAME 0x010D #define TAG_IMAGE_DESCRIPTION 0x010E #define TAG_MAKE 0x010F #define TAG_MODEL 0x0110 #define TAG_STRIP_OFFSETS 0x0111 #define TAG_ORIENTATION 0x0112 #define TAG_SAMPLES_PER_PIXEL 0x0115 #define TAG_ROWS_PER_STRIP 0x0116 #define TAG_STRIP_BYTE_COUNTS 0x0117 #define TAG_MIN_SAMPPLE_VALUE 0x0118 #define TAG_MAX_SAMPLE_VALUE 0x0119 #define TAG_X_RESOLUTION 0x011A #define TAG_Y_RESOLUTION 0x011B #define TAG_PLANAR_CONFIGURATION 0x011C #define TAG_PAGE_NAME 0x011D #define TAG_X_POSITION 0x011E #define TAG_Y_POSITION 0x011F #define TAG_FREE_OFFSETS 0x0120 #define TAG_FREE_BYTE_COUNTS 0x0121 #define TAG_GRAY_RESPONSE_UNIT 0x0122 #define TAG_GRAY_RESPONSE_CURVE 0x0123 #define TAG_RESOLUTION_UNIT 0x0128 #define TAG_PAGE_NUMBER 0x0129 #define TAG_TRANSFER_FUNCTION 0x012D #define TAG_SOFTWARE 0x0131 #define TAG_DATETIME 0x0132 #define TAG_ARTIST 0x013B #define TAG_HOST_COMPUTER 0x013C #define TAG_PREDICTOR 0x013D #define TAG_WHITE_POINT 0x013E #define TAG_PRIMARY_CHROMATICITIES 0x013F #define TAG_COLOR_MAP 0x0140 #define TAG_HALFTONE_HINTS 0x0141 #define TAG_TILE_WIDTH 0x0142 #define TAG_TILE_LENGTH 0x0143 #define TAG_TILE_OFFSETS 0x0144 #define TAG_TILE_BYTE_COUNTS 0x0145 #define TAG_SUB_IFD 0x014A #define TAG_INK_SETMPUTER 0x014C #define TAG_INK_NAMES 0x014D #define TAG_NUMBER_OF_INKS 0x014E #define TAG_DOT_RANGE 0x0150 #define TAG_TARGET_PRINTER 0x0151 #define TAG_EXTRA_SAMPLE 0x0152 #define TAG_SAMPLE_FORMAT 0x0153 #define TAG_S_MIN_SAMPLE_VALUE 0x0154 #define TAG_S_MAX_SAMPLE_VALUE 0x0155 #define TAG_TRANSFER_RANGE 0x0156 #define TAG_JPEG_TABLES 0x015B #define TAG_JPEG_PROC 0x0200 #define TAG_JPEG_INTERCHANGE_FORMAT 0x0201 #define TAG_JPEG_INTERCHANGE_FORMAT_LEN 0x0202 #define TAG_JPEG_RESTART_INTERVAL 0x0203 #define TAG_JPEG_LOSSLESS_PREDICTOR 0x0205 #define TAG_JPEG_POINT_TRANSFORMS 0x0206 #define TAG_JPEG_Q_TABLES 0x0207 #define TAG_JPEG_DC_TABLES 0x0208 #define TAG_JPEG_AC_TABLES 0x0209 #define TAG_YCC_COEFFICIENTS 0x0211 #define TAG_YCC_SUB_SAMPLING 0x0212 #define TAG_YCC_POSITIONING 0x0213 #define TAG_REFERENCE_BLACK_WHITE 0x0214 /* 0x0301 - 0x0302 */ /* 0x0320 */ /* 0x0343 */ /* 0x5001 - 0x501B */ /* 0x5021 - 0x503B */ /* 0x5090 - 0x5091 */ /* 0x5100 - 0x5101 */ /* 0x5110 - 0x5113 */ /* 0x80E3 - 0x80E6 */ /* 0x828d - 0x828F */ #define TAG_COPYRIGHT 0x8298 #define TAG_EXPOSURETIME 0x829A #define TAG_FNUMBER 0x829D #define TAG_EXIF_IFD_POINTER 0x8769 #define TAG_ICC_PROFILE 0x8773 #define TAG_EXPOSURE_PROGRAM 0x8822 #define TAG_SPECTRAL_SENSITY 0x8824 #define TAG_GPS_IFD_POINTER 0x8825 #define TAG_ISOSPEED 0x8827 #define TAG_OPTOELECTRIC_CONVERSION_F 0x8828 /* 0x8829 - 0x882b */ #define TAG_EXIFVERSION 0x9000 #define TAG_DATE_TIME_ORIGINAL 0x9003 #define TAG_DATE_TIME_DIGITIZED 0x9004 #define TAG_COMPONENT_CONFIG 0x9101 #define TAG_COMPRESSED_BITS_PER_PIXEL 0x9102 #define TAG_SHUTTERSPEED 0x9201 #define TAG_APERTURE 0x9202 #define TAG_BRIGHTNESS_VALUE 0x9203 #define TAG_EXPOSURE_BIAS_VALUE 0x9204 #define TAG_MAX_APERTURE 0x9205 #define TAG_SUBJECT_DISTANCE 0x9206 #define TAG_METRIC_MODULE 0x9207 #define TAG_LIGHT_SOURCE 0x9208 #define TAG_FLASH 0x9209 #define TAG_FOCAL_LENGTH 0x920A /* 0x920B - 0x920D */ /* 0x9211 - 0x9216 */ #define TAG_SUBJECT_AREA 0x9214 #define TAG_MAKER_NOTE 0x927C #define TAG_USERCOMMENT 0x9286 #define TAG_SUB_SEC_TIME 0x9290 #define TAG_SUB_SEC_TIME_ORIGINAL 0x9291 #define TAG_SUB_SEC_TIME_DIGITIZED 0x9292 /* 0x923F */ /* 0x935C */ #define TAG_XP_TITLE 0x9C9B #define TAG_XP_COMMENTS 0x9C9C #define TAG_XP_AUTHOR 0x9C9D #define TAG_XP_KEYWORDS 0x9C9E #define TAG_XP_SUBJECT 0x9C9F #define TAG_FLASH_PIX_VERSION 0xA000 #define TAG_COLOR_SPACE 0xA001 #define TAG_COMP_IMAGE_WIDTH 0xA002 /* compressed images only */ #define TAG_COMP_IMAGE_HEIGHT 0xA003 #define TAG_RELATED_SOUND_FILE 0xA004 #define TAG_INTEROP_IFD_POINTER 0xA005 /* IFD pointer */ #define TAG_FLASH_ENERGY 0xA20B #define TAG_SPATIAL_FREQUENCY_RESPONSE 0xA20C #define TAG_FOCALPLANE_X_RES 0xA20E #define TAG_FOCALPLANE_Y_RES 0xA20F #define TAG_FOCALPLANE_RESOLUTION_UNIT 0xA210 #define TAG_SUBJECT_LOCATION 0xA214 #define TAG_EXPOSURE_INDEX 0xA215 #define TAG_SENSING_METHOD 0xA217 #define TAG_FILE_SOURCE 0xA300 #define TAG_SCENE_TYPE 0xA301 #define TAG_CFA_PATTERN 0xA302 #define TAG_CUSTOM_RENDERED 0xA401 #define TAG_EXPOSURE_MODE 0xA402 #define TAG_WHITE_BALANCE 0xA403 #define TAG_DIGITAL_ZOOM_RATIO 0xA404 #define TAG_FOCAL_LENGTH_IN_35_MM_FILM 0xA405 #define TAG_SCENE_CAPTURE_TYPE 0xA406 #define TAG_GAIN_CONTROL 0xA407 #define TAG_CONTRAST 0xA408 #define TAG_SATURATION 0xA409 #define TAG_SHARPNESS 0xA40A #define TAG_DEVICE_SETTING_DESCRIPTION 0xA40B #define TAG_SUBJECT_DISTANCE_RANGE 0xA40C #define TAG_IMAGE_UNIQUE_ID 0xA420 /* Olympus specific tags */ #define TAG_OLYMPUS_SPECIALMODE 0x0200 #define TAG_OLYMPUS_JPEGQUAL 0x0201 #define TAG_OLYMPUS_MACRO 0x0202 #define TAG_OLYMPUS_DIGIZOOM 0x0204 #define TAG_OLYMPUS_SOFTWARERELEASE 0x0207 #define TAG_OLYMPUS_PICTINFO 0x0208 #define TAG_OLYMPUS_CAMERAID 0x0209 /* end Olympus specific tags */ /* Internal */ #define TAG_NONE -1 /* note that -1 <> 0xFFFF */ #define TAG_COMPUTED_VALUE -2 #define TAG_END_OF_LIST 0xFFFD /* Values for TAG_PHOTOMETRIC_INTERPRETATION */ #define PMI_BLACK_IS_ZERO 0 #define PMI_WHITE_IS_ZERO 1 #define PMI_RGB 2 #define PMI_PALETTE_COLOR 3 #define PMI_TRANSPARENCY_MASK 4 #define PMI_SEPARATED 5 #define PMI_YCBCR 6 #define PMI_CIELAB 8 typedef const struct { unsigned short Tag; char *Desc; } tag_info_type; typedef tag_info_type tag_info_array[]; typedef tag_info_type *tag_table_type; #define TAG_TABLE_END \ {((unsigned short)TAG_NONE), "No tag value"},\ {((unsigned short)TAG_COMPUTED_VALUE), "Computed value"},\ {TAG_END_OF_LIST, ""} /* Important for exif_get_tagname() IF value != "" function result is != false */ static const tag_info_array tag_table_IFD = { { 0x000B, "ACDComment"}, { 0x00FE, "NewSubFile"}, /* better name it 'ImageType' ? */ { 0x00FF, "SubFile"}, { 0x0100, "ImageWidth"}, { 0x0101, "ImageLength"}, { 0x0102, "BitsPerSample"}, { 0x0103, "Compression"}, { 0x0106, "PhotometricInterpretation"}, { 0x010A, "FillOrder"}, { 0x010D, "DocumentName"}, { 0x010E, "ImageDescription"}, { 0x010F, "Make"}, { 0x0110, "Model"}, { 0x0111, "StripOffsets"}, { 0x0112, "Orientation"}, { 0x0115, "SamplesPerPixel"}, { 0x0116, "RowsPerStrip"}, { 0x0117, "StripByteCounts"}, { 0x0118, "MinSampleValue"}, { 0x0119, "MaxSampleValue"}, { 0x011A, "XResolution"}, { 0x011B, "YResolution"}, { 0x011C, "PlanarConfiguration"}, { 0x011D, "PageName"}, { 0x011E, "XPosition"}, { 0x011F, "YPosition"}, { 0x0120, "FreeOffsets"}, { 0x0121, "FreeByteCounts"}, { 0x0122, "GrayResponseUnit"}, { 0x0123, "GrayResponseCurve"}, { 0x0124, "T4Options"}, { 0x0125, "T6Options"}, { 0x0128, "ResolutionUnit"}, { 0x0129, "PageNumber"}, { 0x012D, "TransferFunction"}, { 0x0131, "Software"}, { 0x0132, "DateTime"}, { 0x013B, "Artist"}, { 0x013C, "HostComputer"}, { 0x013D, "Predictor"}, { 0x013E, "WhitePoint"}, { 0x013F, "PrimaryChromaticities"}, { 0x0140, "ColorMap"}, { 0x0141, "HalfToneHints"}, { 0x0142, "TileWidth"}, { 0x0143, "TileLength"}, { 0x0144, "TileOffsets"}, { 0x0145, "TileByteCounts"}, { 0x014A, "SubIFD"}, { 0x014C, "InkSet"}, { 0x014D, "InkNames"}, { 0x014E, "NumberOfInks"}, { 0x0150, "DotRange"}, { 0x0151, "TargetPrinter"}, { 0x0152, "ExtraSample"}, { 0x0153, "SampleFormat"}, { 0x0154, "SMinSampleValue"}, { 0x0155, "SMaxSampleValue"}, { 0x0156, "TransferRange"}, { 0x0157, "ClipPath"}, { 0x0158, "XClipPathUnits"}, { 0x0159, "YClipPathUnits"}, { 0x015A, "Indexed"}, { 0x015B, "JPEGTables"}, { 0x015F, "OPIProxy"}, { 0x0200, "JPEGProc"}, { 0x0201, "JPEGInterchangeFormat"}, { 0x0202, "JPEGInterchangeFormatLength"}, { 0x0203, "JPEGRestartInterval"}, { 0x0205, "JPEGLosslessPredictors"}, { 0x0206, "JPEGPointTransforms"}, { 0x0207, "JPEGQTables"}, { 0x0208, "JPEGDCTables"}, { 0x0209, "JPEGACTables"}, { 0x0211, "YCbCrCoefficients"}, { 0x0212, "YCbCrSubSampling"}, { 0x0213, "YCbCrPositioning"}, { 0x0214, "ReferenceBlackWhite"}, { 0x02BC, "ExtensibleMetadataPlatform"}, /* XAP: Extensible Authoring Publishing, obsoleted by XMP: Extensible Metadata Platform */ { 0x0301, "Gamma"}, { 0x0302, "ICCProfileDescriptor"}, { 0x0303, "SRGBRenderingIntent"}, { 0x0320, "ImageTitle"}, { 0x5001, "ResolutionXUnit"}, { 0x5002, "ResolutionYUnit"}, { 0x5003, "ResolutionXLengthUnit"}, { 0x5004, "ResolutionYLengthUnit"}, { 0x5005, "PrintFlags"}, { 0x5006, "PrintFlagsVersion"}, { 0x5007, "PrintFlagsCrop"}, { 0x5008, "PrintFlagsBleedWidth"}, { 0x5009, "PrintFlagsBleedWidthScale"}, { 0x500A, "HalftoneLPI"}, { 0x500B, "HalftoneLPIUnit"}, { 0x500C, "HalftoneDegree"}, { 0x500D, "HalftoneShape"}, { 0x500E, "HalftoneMisc"}, { 0x500F, "HalftoneScreen"}, { 0x5010, "JPEGQuality"}, { 0x5011, "GridSize"}, { 0x5012, "ThumbnailFormat"}, { 0x5013, "ThumbnailWidth"}, { 0x5014, "ThumbnailHeight"}, { 0x5015, "ThumbnailColorDepth"}, { 0x5016, "ThumbnailPlanes"}, { 0x5017, "ThumbnailRawBytes"}, { 0x5018, "ThumbnailSize"}, { 0x5019, "ThumbnailCompressedSize"}, { 0x501A, "ColorTransferFunction"}, { 0x501B, "ThumbnailData"}, { 0x5020, "ThumbnailImageWidth"}, { 0x5021, "ThumbnailImageHeight"}, { 0x5022, "ThumbnailBitsPerSample"}, { 0x5023, "ThumbnailCompression"}, { 0x5024, "ThumbnailPhotometricInterp"}, { 0x5025, "ThumbnailImageDescription"}, { 0x5026, "ThumbnailEquipMake"}, { 0x5027, "ThumbnailEquipModel"}, { 0x5028, "ThumbnailStripOffsets"}, { 0x5029, "ThumbnailOrientation"}, { 0x502A, "ThumbnailSamplesPerPixel"}, { 0x502B, "ThumbnailRowsPerStrip"}, { 0x502C, "ThumbnailStripBytesCount"}, { 0x502D, "ThumbnailResolutionX"}, { 0x502E, "ThumbnailResolutionY"}, { 0x502F, "ThumbnailPlanarConfig"}, { 0x5030, "ThumbnailResolutionUnit"}, { 0x5031, "ThumbnailTransferFunction"}, { 0x5032, "ThumbnailSoftwareUsed"}, { 0x5033, "ThumbnailDateTime"}, { 0x5034, "ThumbnailArtist"}, { 0x5035, "ThumbnailWhitePoint"}, { 0x5036, "ThumbnailPrimaryChromaticities"}, { 0x5037, "ThumbnailYCbCrCoefficients"}, { 0x5038, "ThumbnailYCbCrSubsampling"}, { 0x5039, "ThumbnailYCbCrPositioning"}, { 0x503A, "ThumbnailRefBlackWhite"}, { 0x503B, "ThumbnailCopyRight"}, { 0x5090, "LuminanceTable"}, { 0x5091, "ChrominanceTable"}, { 0x5100, "FrameDelay"}, { 0x5101, "LoopCount"}, { 0x5110, "PixelUnit"}, { 0x5111, "PixelPerUnitX"}, { 0x5112, "PixelPerUnitY"}, { 0x5113, "PaletteHistogram"}, { 0x1000, "RelatedImageFileFormat"}, { 0x800D, "ImageID"}, { 0x80E3, "Matteing"}, /* obsoleted by ExtraSamples */ { 0x80E4, "DataType"}, /* obsoleted by SampleFormat */ { 0x80E5, "ImageDepth"}, { 0x80E6, "TileDepth"}, { 0x828D, "CFARepeatPatternDim"}, { 0x828E, "CFAPattern"}, { 0x828F, "BatteryLevel"}, { 0x8298, "Copyright"}, { 0x829A, "ExposureTime"}, { 0x829D, "FNumber"}, { 0x83BB, "IPTC/NAA"}, { 0x84E3, "IT8RasterPadding"}, { 0x84E5, "IT8ColorTable"}, { 0x8649, "ImageResourceInformation"}, /* PhotoShop */ { 0x8769, "Exif_IFD_Pointer"}, { 0x8773, "ICC_Profile"}, { 0x8822, "ExposureProgram"}, { 0x8824, "SpectralSensity"}, { 0x8828, "OECF"}, { 0x8825, "GPS_IFD_Pointer"}, { 0x8827, "ISOSpeedRatings"}, { 0x8828, "OECF"}, { 0x9000, "ExifVersion"}, { 0x9003, "DateTimeOriginal"}, { 0x9004, "DateTimeDigitized"}, { 0x9101, "ComponentsConfiguration"}, { 0x9102, "CompressedBitsPerPixel"}, { 0x9201, "ShutterSpeedValue"}, { 0x9202, "ApertureValue"}, { 0x9203, "BrightnessValue"}, { 0x9204, "ExposureBiasValue"}, { 0x9205, "MaxApertureValue"}, { 0x9206, "SubjectDistance"}, { 0x9207, "MeteringMode"}, { 0x9208, "LightSource"}, { 0x9209, "Flash"}, { 0x920A, "FocalLength"}, { 0x920B, "FlashEnergy"}, /* 0xA20B in JPEG */ { 0x920C, "SpatialFrequencyResponse"}, /* 0xA20C - - */ { 0x920D, "Noise"}, { 0x920E, "FocalPlaneXResolution"}, /* 0xA20E - - */ { 0x920F, "FocalPlaneYResolution"}, /* 0xA20F - - */ { 0x9210, "FocalPlaneResolutionUnit"}, /* 0xA210 - - */ { 0x9211, "ImageNumber"}, { 0x9212, "SecurityClassification"}, { 0x9213, "ImageHistory"}, { 0x9214, "SubjectLocation"}, /* 0xA214 - - */ { 0x9215, "ExposureIndex"}, /* 0xA215 - - */ { 0x9216, "TIFF/EPStandardID"}, { 0x9217, "SensingMethod"}, /* 0xA217 - - */ { 0x923F, "StoNits"}, { 0x927C, "MakerNote"}, { 0x9286, "UserComment"}, { 0x9290, "SubSecTime"}, { 0x9291, "SubSecTimeOriginal"}, { 0x9292, "SubSecTimeDigitized"}, { 0x935C, "ImageSourceData"}, /* "Adobe Photoshop Document Data Block": 8BIM... */ { 0x9c9b, "Title" }, /* Win XP specific, Unicode */ { 0x9c9c, "Comments" }, /* Win XP specific, Unicode */ { 0x9c9d, "Author" }, /* Win XP specific, Unicode */ { 0x9c9e, "Keywords" }, /* Win XP specific, Unicode */ { 0x9c9f, "Subject" }, /* Win XP specific, Unicode, not to be confused with SubjectDistance and SubjectLocation */ { 0xA000, "FlashPixVersion"}, { 0xA001, "ColorSpace"}, { 0xA002, "ExifImageWidth"}, { 0xA003, "ExifImageLength"}, { 0xA004, "RelatedSoundFile"}, { 0xA005, "InteroperabilityOffset"}, { 0xA20B, "FlashEnergy"}, /* 0x920B in TIFF/EP */ { 0xA20C, "SpatialFrequencyResponse"}, /* 0x920C - - */ { 0xA20D, "Noise"}, { 0xA20E, "FocalPlaneXResolution"}, /* 0x920E - - */ { 0xA20F, "FocalPlaneYResolution"}, /* 0x920F - - */ { 0xA210, "FocalPlaneResolutionUnit"}, /* 0x9210 - - */ { 0xA211, "ImageNumber"}, { 0xA212, "SecurityClassification"}, { 0xA213, "ImageHistory"}, { 0xA214, "SubjectLocation"}, /* 0x9214 - - */ { 0xA215, "ExposureIndex"}, /* 0x9215 - - */ { 0xA216, "TIFF/EPStandardID"}, { 0xA217, "SensingMethod"}, /* 0x9217 - - */ { 0xA300, "FileSource"}, { 0xA301, "SceneType"}, { 0xA302, "CFAPattern"}, { 0xA401, "CustomRendered"}, { 0xA402, "ExposureMode"}, { 0xA403, "WhiteBalance"}, { 0xA404, "DigitalZoomRatio"}, { 0xA405, "FocalLengthIn35mmFilm"}, { 0xA406, "SceneCaptureType"}, { 0xA407, "GainControl"}, { 0xA408, "Contrast"}, { 0xA409, "Saturation"}, { 0xA40A, "Sharpness"}, { 0xA40B, "DeviceSettingDescription"}, { 0xA40C, "SubjectDistanceRange"}, { 0xA420, "ImageUniqueID"}, TAG_TABLE_END }; static const tag_info_array tag_table_GPS = { { 0x0000, "GPSVersion"}, { 0x0001, "GPSLatitudeRef"}, { 0x0002, "GPSLatitude"}, { 0x0003, "GPSLongitudeRef"}, { 0x0004, "GPSLongitude"}, { 0x0005, "GPSAltitudeRef"}, { 0x0006, "GPSAltitude"}, { 0x0007, "GPSTimeStamp"}, { 0x0008, "GPSSatellites"}, { 0x0009, "GPSStatus"}, { 0x000A, "GPSMeasureMode"}, { 0x000B, "GPSDOP"}, { 0x000C, "GPSSpeedRef"}, { 0x000D, "GPSSpeed"}, { 0x000E, "GPSTrackRef"}, { 0x000F, "GPSTrack"}, { 0x0010, "GPSImgDirectionRef"}, { 0x0011, "GPSImgDirection"}, { 0x0012, "GPSMapDatum"}, { 0x0013, "GPSDestLatitudeRef"}, { 0x0014, "GPSDestLatitude"}, { 0x0015, "GPSDestLongitudeRef"}, { 0x0016, "GPSDestLongitude"}, { 0x0017, "GPSDestBearingRef"}, { 0x0018, "GPSDestBearing"}, { 0x0019, "GPSDestDistanceRef"}, { 0x001A, "GPSDestDistance"}, { 0x001B, "GPSProcessingMode"}, { 0x001C, "GPSAreaInformation"}, { 0x001D, "GPSDateStamp"}, { 0x001E, "GPSDifferential"}, TAG_TABLE_END }; static const tag_info_array tag_table_IOP = { { 0x0001, "InterOperabilityIndex"}, /* should be 'R98' or 'THM' */ { 0x0002, "InterOperabilityVersion"}, { 0x1000, "RelatedFileFormat"}, { 0x1001, "RelatedImageWidth"}, { 0x1002, "RelatedImageHeight"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CANON = { { 0x0001, "ModeArray"}, /* guess */ { 0x0004, "ImageInfo"}, /* guess */ { 0x0006, "ImageType"}, { 0x0007, "FirmwareVersion"}, { 0x0008, "ImageNumber"}, { 0x0009, "OwnerName"}, { 0x000C, "Camera"}, { 0x000F, "CustomFunctions"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CASIO = { { 0x0001, "RecordingMode"}, { 0x0002, "Quality"}, { 0x0003, "FocusingMode"}, { 0x0004, "FlashMode"}, { 0x0005, "FlashIntensity"}, { 0x0006, "ObjectDistance"}, { 0x0007, "WhiteBalance"}, { 0x000A, "DigitalZoom"}, { 0x000B, "Sharpness"}, { 0x000C, "Contrast"}, { 0x000D, "Saturation"}, { 0x0014, "CCDSensitivity"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_FUJI = { { 0x0000, "Version"}, { 0x1000, "Quality"}, { 0x1001, "Sharpness"}, { 0x1002, "WhiteBalance"}, { 0x1003, "Color"}, { 0x1004, "Tone"}, { 0x1010, "FlashMode"}, { 0x1011, "FlashStrength"}, { 0x1020, "Macro"}, { 0x1021, "FocusMode"}, { 0x1030, "SlowSync"}, { 0x1031, "PictureMode"}, { 0x1100, "ContTake"}, { 0x1300, "BlurWarning"}, { 0x1301, "FocusWarning"}, { 0x1302, "AEWarning "}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON = { { 0x0003, "Quality"}, { 0x0004, "ColorMode"}, { 0x0005, "ImageAdjustment"}, { 0x0006, "CCDSensitivity"}, { 0x0007, "WhiteBalance"}, { 0x0008, "Focus"}, { 0x000a, "DigitalZoom"}, { 0x000b, "Converter"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON_990 = { { 0x0001, "Version"}, { 0x0002, "ISOSetting"}, { 0x0003, "ColorMode"}, { 0x0004, "Quality"}, { 0x0005, "WhiteBalance"}, { 0x0006, "ImageSharpening"}, { 0x0007, "FocusMode"}, { 0x0008, "FlashSetting"}, { 0x000F, "ISOSelection"}, { 0x0080, "ImageAdjustment"}, { 0x0082, "AuxiliaryLens"}, { 0x0085, "ManualFocusDistance"}, { 0x0086, "DigitalZoom"}, { 0x0088, "AFFocusPosition"}, { 0x0010, "DataDump"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_OLYMPUS = { { 0x0200, "SpecialMode"}, { 0x0201, "JPEGQuality"}, { 0x0202, "Macro"}, { 0x0204, "DigitalZoom"}, { 0x0207, "SoftwareRelease"}, { 0x0208, "PictureInfo"}, { 0x0209, "CameraId"}, { 0x0F00, "DataDump"}, TAG_TABLE_END }; typedef enum mn_byte_order_t { MN_ORDER_INTEL = 0, MN_ORDER_MOTOROLA = 1, MN_ORDER_NORMAL } mn_byte_order_t; typedef enum mn_offset_mode_t { MN_OFFSET_NORMAL, MN_OFFSET_MAKER, MN_OFFSET_GUESS } mn_offset_mode_t; typedef struct { tag_table_type tag_table; char *make; char *model; char *id_string; int id_string_len; int offset; mn_byte_order_t byte_order; mn_offset_mode_t offset_mode; } maker_note_type; static const maker_note_type maker_note_array[] = { { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_INTEL, MN_OFFSET_NORMAL}, /* { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL},*/ { tag_table_VND_CASIO, "CASIO", nullptr, nullptr, 0, 0, MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL}, { tag_table_VND_FUJI, "FUJIFILM", nullptr, "FUJIFILM\x0C\x00\x00\x00", 12, 12, MN_ORDER_INTEL, MN_OFFSET_MAKER}, { tag_table_VND_NIKON, "NIKON", nullptr, "Nikon\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_NIKON_990, "NIKON", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_OLYMPUS, "OLYMPUS OPTICAL CO.,LTD", nullptr, "OLYMP\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, }; /* Get headername for tag_num or nullptr if not defined */ static char * exif_get_tagname(int tag_num, char *ret, int len, tag_table_type tag_table) { int i, t; char tmp[32]; for (i = 0; (t = tag_table[i].Tag) != TAG_END_OF_LIST; i++) { if (t == tag_num) { if (ret && len) { string_copy(ret, tag_table[i].Desc, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return tag_table[i].Desc; } } if (ret && len) { snprintf(tmp, sizeof(tmp), "UndefinedTag:0x%04X", tag_num); string_copy(ret, tmp, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return ""; } #define MAX_IFD_NESTING_LEVEL 100 #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif typedef struct { int num; int den; } signed_rational; typedef struct { unsigned int num; unsigned int den; } unsigned_rational; typedef union _image_info_value { char *s; unsigned u; int i; float f; double d; signed_rational sr; unsigned_rational ur; union _image_info_value *list; } image_info_value; typedef struct { WORD tag; WORD format; DWORD length; DWORD dummy; /* value ptr of tiff directory entry */ char *name; image_info_value value; } image_info_data; typedef struct { int count; image_info_data *list; } image_info_list; #define SECTION_FILE 0 #define SECTION_COMPUTED 1 #define SECTION_ANY_TAG 2 #define SECTION_IFD0 3 #define SECTION_THUMBNAIL 4 #define SECTION_COMMENT 5 #define SECTION_APP0 6 #define SECTION_EXIF 7 #define SECTION_FPIX 8 #define SECTION_GPS 9 #define SECTION_INTEROP 10 #define SECTION_APP12 11 #define SECTION_WINXP 12 #define SECTION_MAKERNOTE 13 #define SECTION_COUNT 14 #define FOUND_FILE (1<<SECTION_FILE) #define FOUND_COMPUTED (1<<SECTION_COMPUTED) #define FOUND_ANY_TAG (1<<SECTION_ANY_TAG) #define FOUND_IFD0 (1<<SECTION_IFD0) #define FOUND_THUMBNAIL (1<<SECTION_THUMBNAIL) #define FOUND_COMMENT (1<<SECTION_COMMENT) #define FOUND_APP0 (1<<SECTION_APP0) #define FOUND_EXIF (1<<SECTION_EXIF) #define FOUND_FPIX (1<<SECTION_FPIX) #define FOUND_GPS (1<<SECTION_GPS) #define FOUND_INTEROP (1<<SECTION_INTEROP) #define FOUND_APP12 (1<<SECTION_APP12) #define FOUND_WINXP (1<<SECTION_WINXP) #define FOUND_MAKERNOTE (1<<SECTION_MAKERNOTE) const StaticString s_FILE("FILE"), s_COMPUTED("COMPUTED"), s_ANY_TAG("ANY_TAG"), s_IFD0("IFD0"), s_THUMBNAIL("THUMBNAIL"), s_COMMENT("COMMENT"), s_APP0("APP0"), s_EXIF("EXIF"), s_FPIX("FPIX"), s_GPS("GPS"), s_INTEROP("INTEROP"), s_APP12("APP12"), s_WINXP("WINXP"), s_MAKERNOTE("MAKERNOTE"); static String exif_get_sectionname(int section) { switch(section) { case SECTION_FILE: return s_FILE; case SECTION_COMPUTED: return s_COMPUTED; case SECTION_ANY_TAG: return s_ANY_TAG; case SECTION_IFD0: return s_IFD0; case SECTION_THUMBNAIL: return s_THUMBNAIL; case SECTION_COMMENT: return s_COMMENT; case SECTION_APP0: return s_APP0; case SECTION_EXIF: return s_EXIF; case SECTION_FPIX: return s_FPIX; case SECTION_GPS: return s_GPS; case SECTION_INTEROP: return s_INTEROP; case SECTION_APP12: return s_APP12; case SECTION_WINXP: return s_WINXP; case SECTION_MAKERNOTE: return s_MAKERNOTE; } return empty_string(); } static tag_table_type exif_get_tag_table(int section) { switch(section) { case SECTION_FILE: return &tag_table_IFD[0]; case SECTION_COMPUTED: return &tag_table_IFD[0]; case SECTION_ANY_TAG: return &tag_table_IFD[0]; case SECTION_IFD0: return &tag_table_IFD[0]; case SECTION_THUMBNAIL: return &tag_table_IFD[0]; case SECTION_COMMENT: return &tag_table_IFD[0]; case SECTION_APP0: return &tag_table_IFD[0]; case SECTION_EXIF: return &tag_table_IFD[0]; case SECTION_FPIX: return &tag_table_IFD[0]; case SECTION_GPS: return &tag_table_GPS[0]; case SECTION_INTEROP: return &tag_table_IOP[0]; case SECTION_APP12: return &tag_table_IFD[0]; case SECTION_WINXP: return &tag_table_IFD[0]; } return &tag_table_IFD[0]; } /* Return list of sectionnames specified by sectionlist. Return value must be freed */ static char *exif_get_sectionlist(int sectionlist) { int i, len, ml = 0; char *sections; for(i=0; i<SECTION_COUNT; i++) { ml += exif_get_sectionname(i).size() + 2; } sections = (char *)IM_MALLOC(ml + 1); CHECK_ALLOC_R(sections, ml + 1, nullptr); sections[0] = '\0'; len = 0; for(i=0; i<SECTION_COUNT; i++) { if (sectionlist&(1<<i)) { snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i).c_str()); len = strlen(sections); } } if (len>2) { sections[len-2] = '\0'; } return sections; } /* This structure stores Exif header image elements in a simple manner Used to store camera data as extracted from the various ways that it can be stored in a nexif header */ typedef struct { int type; size_t size; unsigned char *data; } file_section; typedef struct { int count; file_section *list; } file_section_list; typedef struct { image_filetype filetype; size_t width, height; size_t size; size_t offset; char *data; } thumbnail_data; typedef struct { char *value; size_t size; int tag; } xp_field_type; typedef struct { int count; xp_field_type *list; } xp_field_list; /* This structure is used to store a section of a Jpeg file. */ typedef struct { req::ptr<File> infile; String FileName; time_t FileDateTime; size_t FileSize; image_filetype FileType; int Height, Width; int IsColor; char *make; char *model; float ApertureFNumber; float ExposureTime; double FocalplaneUnits; float CCDWidth; double FocalplaneXRes; size_t ExifImageWidth; float FocalLength; float Distance; int motorola_intel; /* 1 Motorola; 0 Intel */ char *UserComment; int UserCommentLength; char *UserCommentEncoding; char *encode_unicode; char *decode_unicode_be; char *decode_unicode_le; char *encode_jis; char *decode_jis_be; char *decode_jis_le; /* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */ char *Copyright; char *CopyrightPhotographer; char *CopyrightEditor; xp_field_list xp_fields; thumbnail_data Thumbnail; /* other */ int sections_found; /* FOUND_<marker> */ image_info_list info_list[SECTION_COUNT]; /* for parsing */ bool read_thumbnail; bool read_all; int ifd_nesting_level; /* internal */ file_section_list file; } image_info_type; typedef struct { int bits_per_sample; size_t width; size_t height; int num_components; } jpeg_sof_info; /* forward declarations */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index); static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table); /* Add a file_section to image_info returns the used block or -1. if size>0 and data == nullptr buffer of size is allocated */ static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, unsigned char *data) { file_section *tmp; int count = ImageInfo->file.count; size_t realloc_size = (count+1) * sizeof(file_section); tmp = (file_section *)IM_REALLOC(ImageInfo->file.list, realloc_size); CHECK_ALLOC_R(tmp, realloc_size, -1); ImageInfo->file.list = tmp; ImageInfo->file.list[count].type = 0xFFFF; ImageInfo->file.list[count].data = nullptr; ImageInfo->file.list[count].size = 0; ImageInfo->file.count = count+1; if (!size) { data = nullptr; } else if (data == nullptr) { data = (unsigned char *)IM_MALLOC(size); if (data == nullptr) IM_FREE(tmp); CHECK_ALLOC_R(data, size, -1); } ImageInfo->file.list[count].type = type; ImageInfo->file.list[count].data = data; ImageInfo->file.list[count].size = size; return count; } /* get length of string if buffer if less than buffer size or buffer size */ static size_t php_strnlen(char* str, size_t maxlen) { size_t len = 0; if (str && maxlen && *str) { do { len++; } while (--maxlen && *(++str)); } return len; } /* Add a value to image_info */ static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data*) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; PHP_STRDUP(info_data->name, name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen((char*)value, length); // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { /* do not recompute length here */ // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = (image_info_value*)IM_CALLOC(length, sizeof(image_info_value)); CHECK_ALLOC(info_value->list, sizeof(image_info_value)); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + get_php_tiff_bytes_per_format(format)) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: info_value->f = *(float *)value; case TAG_FMT_DOUBLE: info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a tag from IFD to image_info */ static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value) { exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel); } /* Evaluate number, be it int, rational, or float from directory. */ static double exif_convert_any_format(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return (double)php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (double)php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return (signed short)php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (double)*(float *)value; case TAG_FMT_DOUBLE: return *(double *)value; } return 0; } /* Evaluate number, be it int, rational, or float from directory. */ static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den); } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (size_t)*(float *)value; case TAG_FMT_DOUBLE: return (size_t)*(double *)value; } return 0; } /* Get 16 bits motorola order (always) for jpeg header stuff. */ static int php_jpg_get16(void *value) { return (((unsigned char *)value)[0] << 8) | ((unsigned char *)value)[1]; } /* Write 16 bit unsigned value to data */ static void php_ifd_set16u(char *data, unsigned int value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF00) >> 8; data[1] = (value & 0x00FF); } else { data[1] = (value & 0xFF00) >> 8; data[0] = (value & 0x00FF); } } /* Convert a 32 bit unsigned value from file's native byte order */ static void php_ifd_set32u(char *data, size_t value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF000000) >> 24; data[1] = (value & 0x00FF0000) >> 16; data[2] = (value & 0x0000FF00) >> 8; data[3] = (value & 0x000000FF); } else { data[3] = (value & 0xFF000000) >> 24; data[2] = (value & 0x00FF0000) >> 16; data[1] = (value & 0x0000FF00) >> 8; data[0] = (value & 0x000000FF); } } /* Create a value for an ifd from an info_data pointer */ static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel) { size_t byte_count; char *value_ptr, *data_ptr; size_t i; image_info_value *info_value; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; size_t malloc_size = byte_count > 4 ? byte_count : 4; value_ptr = (char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(value_ptr, malloc_size, nullptr); memset(value_ptr, 0, 4); if (!info_data->length) { return value_ptr; } if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE))) { memmove(value_ptr, info_data->value.s, byte_count); return value_ptr; } else if (info_data->format == TAG_FMT_BYTE) { *value_ptr = info_data->value.u; return value_ptr; } else if (info_data->format == TAG_FMT_SBYTE) { *value_ptr = info_data->value.i; return value_ptr; } else { data_ptr = value_ptr; for(i=0; i<info_data->length; i++) { if (info_data->length==1) { info_value = &info_data->value; } else { info_value = &info_data->value.list[i]; } switch(info_data->format) { case TAG_FMT_USHORT: php_ifd_set16u(data_ptr, info_value->u, motorola_intel); data_ptr += 2; break; case TAG_FMT_ULONG: php_ifd_set32u(data_ptr, info_value->u, motorola_intel); data_ptr += 4; break; case TAG_FMT_SSHORT: php_ifd_set16u(data_ptr, info_value->i, motorola_intel); data_ptr += 2; break; case TAG_FMT_SLONG: php_ifd_set32u(data_ptr, info_value->i, motorola_intel); data_ptr += 4; break; case TAG_FMT_URATIONAL: php_ifd_set32u(data_ptr, info_value->sr.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SRATIONAL: php_ifd_set32u(data_ptr, info_value->ur.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SINGLE: memmove(data_ptr, &info_value->f, 4); data_ptr += 4; break; case TAG_FMT_DOUBLE: memmove(data_ptr, &info_value->d, 8); data_ptr += 8; break; } } } return value_ptr; } /* Process a COM marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ static void exif_process_COM(image_info_type *image_info, char *value, size_t length) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2); } /* Check and build thumbnail */ static void exif_thumbnail_build(image_info_type *ImageInfo) { size_t new_size, new_move, new_value; char *new_data; void *value_ptr; int i, byte_count; image_info_list *info_list; image_info_data *info_data; if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) { return; /* ignore this call */ } switch(ImageInfo->Thumbnail.filetype) { default: case IMAGE_FILETYPE_JPEG: /* done */ break; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: info_list = &ImageInfo->info_list[SECTION_THUMBNAIL]; new_size = 8 + 2 + info_list->count * 12 + 4; new_value= new_size; /* offset for ifd values outside ifd directory */ for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (byte_count > 4) { new_size += byte_count; } } new_move = new_size; new_data = (char *)IM_REALLOC(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size + new_size); CHECK_ALLOC(new_data, ImageInfo->Thumbnail.size + new_size); ImageInfo->Thumbnail.data = new_data; memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size); ImageInfo->Thumbnail.size += new_size; /* fill in data */ if (ImageInfo->motorola_intel) { memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8); } else { memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8); } new_data += 8; php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel); new_data += 2; for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, TAG_FMT_ULONG, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, 1, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 8, new_move, ImageInfo->motorola_intel); } else { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel); value_ptr = exif_ifd_make_value(info_data, ImageInfo->motorola_intel); if (byte_count <= 4) { memmove(new_data+8, value_ptr, 4); } else { php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel); memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count); new_value += byte_count; } if (value_ptr) IM_FREE(value_ptr); } new_data += 12; } memset(new_data, 0, 4); /* next ifd pointer */ break; } } /* Grab the thumbnail, corrected */ static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length) { if (ImageInfo->Thumbnail.data) { raise_warning("Multiple possible thumbnails"); return; /* Should not happen */ } if (!ImageInfo->read_thumbnail) { return; /* ignore this call */ } /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */ if (ImageInfo->Thumbnail.size >= 65536 || ImageInfo->Thumbnail.size <= 0 || ImageInfo->Thumbnail.offset <= 0) { raise_warning("Illegal thumbnail size/offset"); return; } /* Check to make sure we are not going to go past the ExifLength */ if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) { raise_warning("Thumbnail goes IFD boundary or end of file reached"); return; } PHP_STRNDUP(ImageInfo->Thumbnail.data, offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size); exif_thumbnail_build(ImageInfo); } /* Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */ static int exif_process_undefined(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ if (byte_count) { PHP_STRNDUP((*result), value, byte_count); /* NULL @ byte_count!!! */ if (*result) return byte_count+1; } return 0; } /* Copy a string in Exif header to a character string returns length of allocated buffer if any. */ #if !EXIF_USE_MBSTRING static int exif_process_string_raw(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ *result = 0; if (byte_count) { (*result) = (char*)IM_MALLOC(byte_count + 1); CHECK_ALLOC_R((*result), byte_count + 1, 0); memcpy(*result, value, byte_count); (*result)[byte_count] = '\0'; return byte_count+1; } return 0; } #endif /* * Copy a string in Exif header to a character string and return length of allocated buffer if any. In contrast to exif_process_string this function does always return a string buffer */ static int exif_process_string(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we cannot use strlen to * determin length of string and we cannot use strlcpy with len=byte_count+1 * because then we might get into an EXCEPTION if we exceed an allocated * memory page...so we use php_strnlen in conjunction with memcpy and add * the NUL char. */ if ((byte_count=php_strnlen(value, byte_count)) > 0) { return exif_process_undefined(result, value, byte_count); } PHP_STRNDUP((*result), "", 1); /* force empty string */ if (*result) return byte_count+1; return 0; } /* Process UserComment in IFD. */ static int exif_process_user_comment(image_info_type* /*ImageInfo*/, char** pszInfoPtr, char** pszEncoding, char* szValuePtr, int ByteCount) { int a; #if EXIF_USE_MBSTRING char *decode; size_t len; #endif *pszEncoding = nullptr; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, decode, &len); return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user */ PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING if (ImageInfo->motorola_intel) { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_be, &len); } else { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_le, &len); } return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ PHP_STRDUP(*pszEncoding, "UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount); return strlen(*pszInfoPtr); } /* Process unicode field in IFD. */ static int exif_process_unicode(image_info_type* /*ImageInfo*/, xp_field_type* xp_field, int tag, char* szValuePtr, int ByteCount) { xp_field->tag = tag; xp_field->value = nullptr; /* Copy the comment */ #if EXIF_USE_MBSTRING xp_field->value = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, ImageInfo->decode_unicode_le, &xp_field->size); return xp_field->size; #else xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount); return xp_field->size; #endif } /* Process nested IFDs directories in Maker Note. */ static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; char *value_end = value_ptr + value_len; for (unsigned int i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) return 0; maker_note = maker_note_array+i; if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) { continue; } if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) { continue; } if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, (maker_note->id_string_len < value_len ? maker_note->id_string_len : value_len))) { continue; } break; } if (maker_note->offset >= value_len) return 0; dir_start = value_ptr + maker_note->offset; ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } if (value_end - dir_start < 2) return 0; NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: if (value_end - (dir_start+10) < 4) return 0; offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); if (offset_diff < 0 || offset_diff >= value_len) return 0; offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { raise_warning("Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, value_end, IFDlength, displacement, section_index, 0, maker_note->tag_table)) { return 0; } } ImageInfo->motorola_intel = old_motorola_intel; return 0; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=nullptr; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { raise_warning("corrupt EXIF header: maximum directory " "nesting level reached"); return 0; } ImageInfo->ifd_nesting_level++; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ raise_warning("Process tag(x%04X=%s): Illegal format code 0x%04X, " "suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { raise_warning("Process tag(x%04X=%s): Illegal components(%d)", tag, exif_get_tagname(tag, tagname, -12, tag_table), components); return 1; } byte_count_signed = (int64_t)components * get_php_tiff_bytes_per_format(format); if (byte_count_signed < 0 || (byte_count_signed > 2147483648)) { raise_warning("Process tag(x%04X=%s): Illegal byte_count(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table), byte_count_signed); return 1; // ignore that field, but don't abort parsing } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* // It is important to check for IMAGE_FILETYPE_TIFF // JPEG does not use absolute pointers instead // its pointers are relative to the start // of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX < %04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, dir_entry-offset_base); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX + x%04lX = x%04lX > x%04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, byte_count, offset_val+byte_count, IFDlength); } return 0; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = (char *)IM_MALLOC(byte_count); CHECK_ALLOC_R(value_ptr, byte_count, 0); outside = value_ptr; } else { /* // in most cases we only access a small range so // it is faster to use a static buffer there // BUT it offers also the possibility to have // pointers read without the need to free them // explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = ImageInfo->infile->tell(); ImageInfo->infile->seek(displacement+offset_val, SEEK_SET); fgot = ImageInfo->infile->tell(); if (fgot!=displacement+offset_val) { if (outside) IM_FREE(outside); raise_warning("Wrong file pointer: 0x%08lX != 0x%08lX", fgot, displacement+offset_val); return 0; } String str = ImageInfo->infile->read(byte_count); fgot = str.length(); memcpy(value_ptr, str.c_str(), fgot); ImageInfo->infile->seek(fpos, SEEK_SET); if (fgot<byte_count) { if (outside) IM_FREE(outside); raise_warning("Unexpected end of file reached"); return 0; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ PHP_STRDUP(ImageInfo->CopyrightPhotographer, value_ptr); PHP_STRNDUP( ImageInfo->CopyrightEditor, value_ptr + length + 1, byte_count - length - 1 ); if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); php_vspprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, ImageInfo->CopyrightEditor); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { PHP_STRNDUP(ImageInfo->Copyright, value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: { size_t realloc_size = (ImageInfo->xp_fields.count+1) * sizeof(xp_field_type); tmp_xp = (xp_field_type*) IM_REALLOC(ImageInfo->xp_fields.list, realloc_size); if (!tmp_xp) { if (outside) IM_FREE(outside); } CHECK_ALLOC_R(tmp_xp, realloc_size, 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count); break; } case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ raise_notice("Skip SUB IFD"); } break; case TAG_MAKE: PHP_STRNDUP(ImageInfo->make, value_ptr, byte_count); break; case TAG_MODEL: PHP_STRNDUP(ImageInfo->model, value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } CHECK_BUFFER_R(value_ptr, end, 4, 0); Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { raise_warning("Illegal IFD Pointer"); return 0; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, end, IFDlength, displacement, sub_section_index)) { return 0; } } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table), tag, format, components, value_ptr); if (outside) IM_FREE(outside); return 1; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index) { int de; int NumDirEntries; int NextDirOffset; ImageInfo->sections_found |= FOUND_IFD0; CHECK_BUFFER_R(dir_start, end, 2, 0); NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { raise_warning("Illegal IFD size: x%04X + 2 + x%04X*12 = x%04X > x%04lX", (int)((size_t)dir_start+2-(size_t)offset_base), NumDirEntries, (int)((size_t)dir_start+2+ NumDirEntries*12-(size_t)offset_base), IFDlength); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, end, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index))) { return 0; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return true; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) * to the thumbnail */ CHECK_BUFFER_R(dir_start+2+12*de, end, 4, 0); NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ if (offset_base + NextDirOffset < offset_base || offset_base + NextDirOffset > offset_base+IFDlength) { raise_warning("Illegal IFD offset"); return 0; } /* That is the IFD for the first thumbnail */ if (exif_process_IFD_in_JPEG(ImageInfo, offset_base + NextDirOffset, offset_base, end, IFDlength, displacement, SECTION_THUMBNAIL)) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength); } return 1; } else { return 0; } } return 1; } /* Process a TIFF header in a JPEG file */ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { char *end = CharBuf + length; unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ CHECK_BUFFER(CharBuf, end, 2); if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { raise_warning("Invalid TIFF a lignment marker"); return; } /* Check the next two values for correctness. */ CHECK_BUFFER(CharBuf+4, end, 4); exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { raise_warning("Invalid TIFF start (1)"); return; } if (offset_of_ifd > length) { raise_warning("Invalid IFD start"); return; } ImageInfo->sections_found |= FOUND_IFD0; /* First directory starts at offset 8. Offsets starts at 0. */ exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, end, length/* -14*/, displacement, SECTION_IFD0); /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } /* Process an JPEG APP1 block marker Describes all the drivel that most digital cameras include... */ static void exif_process_APP1(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { /* Check the APP1 for Exif Identifier Code */ char *end = CharBuf + length; static const unsigned char ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00}; CHECK_BUFFER(CharBuf+2, end, 6); if (length <= 8 || memcmp(CharBuf+2, ExifHeader, 6)) { raise_warning("Incorrect APP1 Exif Identifier Code"); return; } exif_process_TIFF_in_JPEG(ImageInfo, CharBuf + 8, length - 8, displacement+8); } /* Process an JPEG APP12 block marker used by OLYMPUS */ static void exif_process_APP12(image_info_type *ImageInfo, char *buffer, size_t length) { size_t l1, l2=0; if ((l1 = php_strnlen(buffer+2, length-2)) > 0) { exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company", TAG_NONE, TAG_FMT_STRING, l1, buffer+2); if (length > 2+l1+1) { l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1); exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info", TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1); } } } /* Process a SOFn marker. This is useful for the image dimensions */ static void exif_process_SOFn(unsigned char* Data, int /*marker*/, jpeg_sof_info* result) { result->bits_per_sample = Data[2]; result->height = php_jpg_get16(Data+3); result->width = php_jpg_get16(Data+5); result->num_components = Data[7]; } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_JPEG_header(image_info_type *ImageInfo) { int section, sn; int marker = 0, last_marker = M_PSEUDO, comment_correction=1; int ll, lh; unsigned char *Data; size_t fpos, size, got, itemlen; jpeg_sof_info sof_info; for(section=0;;section++) { // get marker byte, swallowing possible padding // some software does not count the length bytes of COM section // one company doing so is very much envolved in JPEG... // so we accept too if (last_marker==M_COM && comment_correction) { comment_correction = 2; } do { if ((marker = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if (last_marker==M_COM && comment_correction>0) { if (marker!=0xFF) { marker = 0xff; comment_correction--; } else { last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */ } } } while (marker == 0xff); if (last_marker==M_COM && !comment_correction) { raise_notice("Image has corrupt COM section: some software set " "wrong length information"); } if (last_marker==M_COM && comment_correction) return M_EOI; /* ah illegal: char after COM section not 0xFF */ fpos = ImageInfo->infile->tell(); if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. raise_warning("To many padding bytes"); return 0; } /* Read the length of the section. */ if ((lh = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if ((ll = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } itemlen = (lh << 8) | ll; if (itemlen < 2) { raise_warning("File structure corrupted"); return 0; } sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; /* Store first two pre-read bytes. */ Data[0] = (unsigned char)lh; Data[1] = (unsigned char)ll; String str = ImageInfo->infile->read(itemlen-2); got = str.length(); if (got != itemlen-2) { raise_warning("Error reading from file: " "got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)", got, got, itemlen-2, itemlen-2); return 0; } memcpy(Data+2, str.c_str(), got); switch(marker) { case M_SOS: /* stop before hitting compressed data */ // If reading entire image is requested, read the rest of the data. if (ImageInfo->read_all) { /* Determine how much file is left. */ fpos = ImageInfo->infile->tell(); size = ImageInfo->FileSize - fpos; sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; str = ImageInfo->infile->read(size); got = str.length(); if (got != size) { raise_warning("Unexpected end of file reached"); return 0; } memcpy(Data, str.c_str(), got); } return 1; case M_EOI: /* in case it's a tables-only JPEG stream */ raise_warning("No image in jpeg!"); return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0; case M_COM: /* Comment section */ exif_process_COM(ImageInfo, (char *)Data, itemlen); break; case M_EXIF: if (!(ImageInfo->sections_found&FOUND_IFD0)) { /*ImageInfo->sections_found |= FOUND_EXIF;*/ /* Seen files from some 'U-lead' software with Vivitar scanner that uses marker 31 later in the file (no clue what for!) */ exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos); } break; case M_APP12: exif_process_APP12(ImageInfo, (char *)Data, itemlen); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: exif_process_SOFn(Data, marker, &sof_info); ImageInfo->Width = sof_info.width; ImageInfo->Height = sof_info.height; if (sof_info.num_components == 3) { ImageInfo->IsColor = 1; } else { ImageInfo->IsColor = 0; } break; default: /* skip any other marker silently. */ break; } /* keep track of last marker */ last_marker = marker; } return 1; } /* Reallocate a file section returns 0 on success and -1 on failure */ static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size) { void *tmp; /* This is not a malloc/realloc check. It is a plausibility check for the * function parameters (requirements engineering). */ if (section_index >= ImageInfo->file.count) { raise_warning("Illegal reallocating of undefined file section"); return -1; } tmp = IM_REALLOC(ImageInfo->file.list[section_index].data, size); CHECK_ALLOC_R(tmp, size, -1); ImageInfo->file.list[section_index].data = (unsigned char *)tmp; ImageInfo->file.list[section_index].size = size; return 0; } /* Parse the TIFF header; */ static int exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index) { int i, sn, num_entries, sub_section_index = 0; unsigned char *dir_entry; char tagname[64]; size_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot; int entry_tag , entry_type; tag_table_type tag_table = exif_get_tag_table(section_index); if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { return 0; } if (ImageInfo->FileSize >= dir_offset+2) { sn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, nullptr); if (sn == -1) return 0; /* we do not know the order of sections */ ImageInfo->infile->seek(dir_offset, SEEK_SET); String snData = ImageInfo->infile->read(2); memcpy(ImageInfo->file.list[sn].data, snData.c_str(), 2); num_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel); dir_size = 2/*num dir entries*/ + 12/*length of entry*/*num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; if (ImageInfo->FileSize >= dir_offset+dir_size) { if (exif_file_sections_realloc(ImageInfo, sn, dir_size)) { return 0; } snData = ImageInfo->infile->read(dir_size-2); memcpy(ImageInfo->file.list[sn].data+2, snData.c_str(), dir_size-2); next_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel); /* now we have the directory we can look how long it should be */ ifd_size = dir_size; char *end = (char*)ImageInfo->file.list[sn].data + dir_size; for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_type > NUM_FORMATS) { raise_notice("Read from TIFF: tag(0x%04X,%12s): " "Illegal format code 0x%04X, switching to BYTE", entry_tag, exif_get_tagname(entry_tag, tagname, -12, tag_table), entry_type); /* Since this is repeated in exif_process_IFD_TAG make it a notice here and make it a warning in the exif_process_IFD_TAG which is called elsewhere. */ entry_type = TAG_FMT_BYTE; } entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * get_php_tiff_bytes_per_format(entry_type); if (entry_length <= 4) { switch(entry_type) { case TAG_FMT_USHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SSHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_ULONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SLONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel); break; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Height = entry_value; break; case TAG_PHOTOMETRIC_INTERPRETATION: switch (entry_value) { case PMI_BLACK_IS_ZERO: case PMI_WHITE_IS_ZERO: case PMI_TRANSPARENCY_MASK: ImageInfo->IsColor = 0; break; case PMI_RGB: case PMI_PALETTE_COLOR: case PMI_SEPARATED: case PMI_YCBCR: case PMI_CIELAB: ImageInfo->IsColor = 1; break; } break; } } else { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* if entry needs expading ifd cache and entry is at end of current ifd cache. */ /* otherwise there may be huge holes between two entries */ if (entry_offset + entry_length > dir_offset + ifd_size && entry_offset == dir_offset + ifd_size) { ifd_size = entry_offset + entry_length - dir_offset; } } } if (ImageInfo->FileSize >= dir_offset + ImageInfo->file.list[sn].size) { if (ifd_size > dir_size) { if (dir_offset + ifd_size > ImageInfo->FileSize) { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX + x%04lX)", ImageInfo->FileSize, dir_offset, ifd_size); return 0; } if (exif_file_sections_realloc(ImageInfo, sn, ifd_size)) { return 0; } else { end = (char*)ImageInfo->file.list[sn].data + dir_size; } /* read values not stored in directory itself */ snData = ImageInfo->infile->read(ifd_size-dir_size); memcpy(ImageInfo->file.list[sn].data+dir_size, snData.c_str(), ifd_size-dir_size); } /* now process the tags */ for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+2, end, 2, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_tag == TAG_EXIF_IFD_POINTER || entry_tag == TAG_INTEROP_IFD_POINTER || entry_tag == TAG_GPS_IFD_POINTER || entry_tag == TAG_SUB_IFD) { switch(entry_tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; case TAG_SUB_IFD: ImageInfo->sections_found |= FOUND_THUMBNAIL; sub_section_index = SECTION_THUMBNAIL; break; } CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index); if (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { if (!ImageInfo->Thumbnail.data) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } } } else { if (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry, (char*)(ImageInfo->file.list[sn].data-dir_offset), (char*)(ImageInfo->file.list[sn].data + ifd_size), ifd_size, 0, section_index, 0, tag_table)) { return 0; } } } /* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */ if (next_offset && section_index != SECTION_THUMBNAIL) { /* this should be a thumbnail IFD */ /* the thumbnail itself is stored at Tag=StripOffsets */ ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL); if (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); CHECK_ALLOC_R(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size, 0); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } return 1; } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX)", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than size " "of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+dir_size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "start of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+2); return 0; } } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_FILE_header(image_info_type *ImageInfo) { unsigned char *file_header; int ret = 0; ImageInfo->FileType = IMAGE_FILETYPE_UNKNOWN; if (ImageInfo->FileSize >= 2) { ImageInfo->infile->seek(0, SEEK_SET); String fileHeader = ImageInfo->infile->read(2); if (fileHeader.length() != 2) { return 0; } file_header = (unsigned char *)fileHeader.c_str(); if ((file_header[0]==0xff) && (file_header[1]==M_SOI)) { ImageInfo->FileType = IMAGE_FILETYPE_JPEG; if (exif_scan_JPEG_header(ImageInfo)) { ret = 1; } else { raise_warning("Invalid JPEG file"); } } else if (ImageInfo->FileSize >= 8) { String str = ImageInfo->infile->read(6); if (str.length() != 6) { return 0; } fileHeader += str; file_header = (unsigned char *)fileHeader.c_str(); if (!memcmp(file_header, "II\x2A\x00", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_II; ImageInfo->motorola_intel = 0; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else if (!memcmp(file_header, "MM\x00\x2a", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_MM; ImageInfo->motorola_intel = 1; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else { raise_warning("File not supported"); return 0; } } } else { raise_warning("File too small (%lu)", ImageInfo->FileSize); } return ret; } static int exif_read_file(image_info_type *ImageInfo, String FileName, bool read_thumbnail, bool read_all) { struct stat st; /* Start with an empty image information structure. */ memset(ImageInfo, 0, sizeof(*ImageInfo)); ImageInfo->motorola_intel = -1; /* flag as unknown */ ImageInfo->infile = File::Open(FileName, "rb"); if (!ImageInfo->infile) { raise_warning("Unable to open file %s", FileName.c_str()); return 0; } auto plain_file = dyn_cast<PlainFile>(ImageInfo->infile); if (plain_file) { if (stat(FileName.c_str(), &st) >= 0) { if ((st.st_mode & S_IFMT) != S_IFREG) { raise_warning("Not a file"); return 0; } } /* Store file date/time. */ ImageInfo->FileDateTime = st.st_mtime; ImageInfo->FileSize = st.st_size; } else { if (!ImageInfo->FileSize) { ImageInfo->infile->seek(0, SEEK_END); ImageInfo->FileSize = ImageInfo->infile->tell(); ImageInfo->infile->seek(0, SEEK_SET); } } ImageInfo->FileName = HHVM_FN(basename)(FileName); ImageInfo->read_thumbnail = read_thumbnail; ImageInfo->read_all = read_all; ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_UNKNOWN; PHP_STRDUP(ImageInfo->encode_unicode, "ISO-8859-15"); PHP_STRDUP(ImageInfo->decode_unicode_be, "UCS-2BE"); PHP_STRDUP(ImageInfo->decode_unicode_le, "UCS-2LE"); PHP_STRDUP(ImageInfo->encode_jis, ""); PHP_STRDUP(ImageInfo->decode_jis_be, "JIS"); PHP_STRDUP(ImageInfo->decode_jis_le, "JIS"); ImageInfo->ifd_nesting_level = 0; /* Scan the JPEG headers. */ auto ret = exif_scan_FILE_header(ImageInfo); ImageInfo->infile->close(); return ret; } /* Free memory allocated for image_info */ static void exif_iif_free(image_info_type *image_info, int section_index) { int i; void *f; /* faster */ if (image_info->info_list[section_index].count) { for (i=0; i < image_info->info_list[section_index].count; i++) { if ((f=image_info->info_list[section_index].list[i].name) != nullptr) { IM_FREE(f); } switch(image_info->info_list[section_index].list[i].format) { case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (image_info->info_list[section_index].list[i].length<1) break; default: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: if ((f=image_info->info_list[section_index].list[i].value.s) != nullptr) { IM_FREE(f); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: /* nothing to do here */ if (image_info->info_list[section_index].list[i].length > 1) { if ((f=image_info->info_list[section_index].list[i].value.list) != nullptr) { IM_FREE(f); } } break; } } } if (image_info->info_list[section_index].list) { IM_FREE(image_info->info_list[section_index].list); } } /* Discard all file_sections in ImageInfo */ static int exif_file_sections_free(image_info_type *ImageInfo) { int i; if (ImageInfo->file.count) { for (i=0; i<ImageInfo->file.count; i++) { if (ImageInfo->file.list[i].data) { IM_FREE(ImageInfo->file.list[i].data); } } } if (ImageInfo->file.list) IM_FREE(ImageInfo->file.list); ImageInfo->file.count = 0; return 1; } /* Discard data scanned by exif_read_file. */ static int exif_discard_imageinfo(image_info_type *ImageInfo) { int i; if (ImageInfo->UserComment) IM_FREE(ImageInfo->UserComment); if (ImageInfo->UserCommentEncoding) { IM_FREE(ImageInfo->UserCommentEncoding); } if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); if (ImageInfo->CopyrightPhotographer) { IM_FREE(ImageInfo->CopyrightPhotographer); } if (ImageInfo->CopyrightEditor) IM_FREE(ImageInfo->CopyrightEditor); if (ImageInfo->Thumbnail.data) IM_FREE(ImageInfo->Thumbnail.data); if (ImageInfo->encode_unicode) IM_FREE(ImageInfo->encode_unicode); if (ImageInfo->decode_unicode_be) { IM_FREE(ImageInfo->decode_unicode_be); } if (ImageInfo->decode_unicode_le) { IM_FREE(ImageInfo->decode_unicode_le); } if (ImageInfo->encode_jis) IM_FREE(ImageInfo->encode_jis); if (ImageInfo->decode_jis_be) IM_FREE(ImageInfo->decode_jis_be); if (ImageInfo->decode_jis_le) IM_FREE(ImageInfo->decode_jis_le); if (ImageInfo->make) IM_FREE(ImageInfo->make); if (ImageInfo->model) IM_FREE(ImageInfo->model); for (i=0; i<ImageInfo->xp_fields.count; i++) { if (ImageInfo->xp_fields.list[i].value) { IM_FREE(ImageInfo->xp_fields.list[i].value); } } if (ImageInfo->xp_fields.list) IM_FREE(ImageInfo->xp_fields.list); for (i=0; i<SECTION_COUNT; i++) { exif_iif_free(ImageInfo, i); } exif_file_sections_free(ImageInfo); memset(ImageInfo, 0, sizeof(*ImageInfo)); return 1; } /* Add an int value to image_info */ static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value) { image_info_data *info_data; image_info_data *list; size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_SLONG; info_data->length = 1; PHP_STRDUP(info_data->name, name); info_data->value.i = value; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_STRING; info_data->length = 1; PHP_STRDUP(info_data->name, name); // TODO // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, strlen(value), nullptr, 0); // } else { PHP_STRDUP(info_data->value.s, value); image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* Add a format string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name, char *value, ...) { va_list arglist; va_start(arglist, value); if (value) { char *tmp = 0; php_vspprintf_ap(&tmp, 0, value, arglist); exif_iif_add_str(image_info, section_index, name, tmp); if (tmp) IM_FREE(tmp); } va_end(arglist); } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_UNDEFINED; info_data->length = length; PHP_STRDUP(info_data->name, name); // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, length, &length, 0); // info_data->length = length; // } else { info_data->value.s = (char *)IM_MALLOC(length + 1); if (!info_data->value.s) info_data->length = 0; CHECK_ALLOC(info_data->value.s, length + 1); memcpy(info_data->value.s, value, length); info_data->value.s[length] = 0; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* scan JPEG in thumbnail (memory) */ static int exif_scan_thumbnail(image_info_type *ImageInfo) { unsigned char c, *data = (unsigned char*)ImageInfo->Thumbnail.data; int n, marker; size_t length=2, pos=0; jpeg_sof_info sof_info; if (!data) { return 0; /* nothing to do here */ } if (memcmp(data, "\xFF\xD8\xFF", 3)) { if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) { raise_warning("Thumbnail is not a JPEG image"); } return 0; } for (;;) { pos += length; if (pos>=ImageInfo->Thumbnail.size) return 0; c = data[pos++]; if (pos>=ImageInfo->Thumbnail.size) return 0; if (c != 0xFF) { return 0; } n = 8; while ((c = data[pos++]) == 0xFF && n--) { if (pos+3>=ImageInfo->Thumbnail.size) return 0; /* +3 = pos++ of next check when reaching marker + 2 bytes for length */ } if (c == 0xFF) return 0; marker = c; length = php_jpg_get16(data+pos); if (pos+length>=ImageInfo->Thumbnail.size) { return 0; } switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: /* handle SOFn block */ exif_process_SOFn(data+pos, marker, &sof_info); ImageInfo->Thumbnail.height = sof_info.height; ImageInfo->Thumbnail.width = sof_info.width; return 1; case M_SOS: case M_EOI: raise_warning("Could not compute size of thumbnail"); return 0; break; default: /* just skip */ break; } } raise_warning("Could not compute size of thumbnail"); return 0; } /* Add image_info to associative array value. */ static void add_assoc_image_info(Array &value, bool sub_array, image_info_type *image_info, int section_index) { char buffer[64], *val, *name, uname[64]; int i, ap, l, b, idx=0, unknown=0; image_info_value *info_value; image_info_data *info_data; Array tmp; Array *tmpi = &tmp; Array array; if (image_info->info_list[section_index].count) { if (!sub_array) { tmpi = &value; } for(i=0; i<image_info->info_list[section_index].count; i++) { info_data = &image_info->info_list[section_index].list[i]; info_value = &info_data->value; if (!(name = info_data->name)) { snprintf(uname, sizeof(uname), "%d", unknown++); name = uname; } if (info_data->length==0) { tmpi->set(String(name, CopyString), uninit_null()); } else { switch (info_data->format) { default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ case TAG_FMT_BYTE: case TAG_FMT_SBYTE: case TAG_FMT_UNDEFINED: if (!info_value->s) { tmpi->set(String(name, CopyString), ""); } else { tmpi->set(String(name, CopyString), String(info_value->s, info_data->length, CopyString)); } break; case TAG_FMT_STRING: if (!(val = info_value->s)) { val = ""; } if (section_index==SECTION_COMMENT) { tmpi->set(idx++, String(val, CopyString)); } else { tmpi->set(String(name, CopyString), String(val, CopyString)); } break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: /*case TAG_FMT_BYTE: case TAG_FMT_SBYTE:*/ case TAG_FMT_USHORT: case TAG_FMT_SSHORT: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: case TAG_FMT_ULONG: case TAG_FMT_SLONG: /* now the rest, first see if it becomes an array */ if ((l = info_data->length) > 1) { array.clear(); } for(ap=0; ap<l; ap++) { if (l>1) { info_value = &info_data->value.list[ap]; } switch (info_data->format) { case TAG_FMT_BYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(b, (int)(info_value->s[b])); } break; } case TAG_FMT_USHORT: case TAG_FMT_ULONG: if (l==1) { tmpi->set(String(name, CopyString), (int)info_value->u); } else { array.set(ap, (int)info_value->u); } break; case TAG_FMT_URATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SBYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(ap, (int)info_value->s[b]); } break; } case TAG_FMT_SSHORT: case TAG_FMT_SLONG: if (l==1) { tmpi->set(String(name, CopyString), info_value->i); } else { array.set(ap, info_value->i); } break; case TAG_FMT_SRATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SINGLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->f); } else { array.set(ap, info_value->f); } break; case TAG_FMT_DOUBLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->d); } else { array.set(ap, info_value->d); } break; } info_value = &info_data->value.list[ap]; } if (l>1) { tmpi->set(String(name, CopyString), array); } break; } } } if (sub_array) { value.set(exif_get_sectionname(section_index), tmp); } } } Variant HHVM_FUNCTION(exif_tagname, int64_t index) { char *szTemp; szTemp = exif_get_tagname(index, nullptr, 0, tag_table_IFD); if (index <0 || !szTemp || !szTemp[0]) { return false; } else { return String(szTemp, CopyString); } } Variant HHVM_FUNCTION(exif_read_data, const String& filename, const String& sections /*="" */, bool arrays /*=false */, bool thumbnail /*=false */) { int i, ret, sections_needed=0; image_info_type ImageInfo; char tmp[64], *sections_str, *s; memset(&ImageInfo, 0, sizeof(ImageInfo)); if (!sections.empty()) { php_vspprintf(&sections_str, 0, ",%s,", sections.c_str()); /* sections_str DOES start with , and SPACES are NOT allowed in names */ s = sections_str; while(*++s) { if (*s==' ') { *s = ','; } } for (i=0; i<SECTION_COUNT; i++) { snprintf(tmp, sizeof(tmp), ",%s,", exif_get_sectionname(i).c_str()); if (strstr(sections_str, tmp)) { sections_needed |= 1<<i; } } if (sections_str) IM_FREE(sections_str); } ret = exif_read_file(&ImageInfo, filename, thumbnail, 0); sections_str = exif_get_sectionlist(ImageInfo.sections_found); /* do not inform about in debug*/ ImageInfo.sections_found |= FOUND_COMPUTED|FOUND_FILE; if (ret==0|| (sections_needed && !(sections_needed&ImageInfo.sections_found))) { exif_discard_imageinfo(&ImageInfo); if (sections_str) IM_FREE(sections_str); return false; } /* now we can add our information */ exif_iif_add_str(&ImageInfo, SECTION_FILE, "FileName", (char *)ImageInfo.FileName.c_str()); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileDateTime", ImageInfo.FileDateTime); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileSize", ImageInfo.FileSize); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileType", ImageInfo.FileType); exif_iif_add_str(&ImageInfo, SECTION_FILE, "MimeType", (char*)php_image_type_to_mime_type(ImageInfo.FileType)); exif_iif_add_str(&ImageInfo, SECTION_FILE, "SectionsFound", sections_str ? sections_str : (char *)"NONE"); if (ImageInfo.Width>0 && ImageInfo.Height>0) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "html", "width=\"%d\" height=\"%d\"", ImageInfo.Width, ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Height", ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Width", ImageInfo.Width); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "IsColor", ImageInfo.IsColor); if (ImageInfo.motorola_intel != -1) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "ByteOrderMotorola", ImageInfo.motorola_intel); } if (ImageInfo.FocalLength) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocalLength", "%4.1Fmm", ImageInfo.FocalLength); if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "35mmFocalLength", "%dmm", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5)); } } if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "CCDWidth", "%dmm", (int)ImageInfo.CCDWidth); } if (ImageInfo.ExposureTime>0) { if (ImageInfo.ExposureTime <= 0.5) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s (1/%d)", ImageInfo.ExposureTime, (int)(0.5 + 1/ImageInfo.ExposureTime)); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s", ImageInfo.ExposureTime); } } if (ImageInfo.ApertureFNumber) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ApertureFNumber", "f/%.1F", ImageInfo.ApertureFNumber); } if (ImageInfo.Distance) { if (ImageInfo.Distance<0) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "Infinite"); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "%0.2Fm", ImageInfo.Distance); } } if (ImageInfo.UserComment) { exif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, "UserComment", ImageInfo.UserCommentLength, ImageInfo.UserComment); if (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "UserCommentEncoding", ImageInfo.UserCommentEncoding); } } exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright", ImageInfo.Copyright); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Photographer", ImageInfo.CopyrightPhotographer); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Editor", ImageInfo.CopyrightEditor); for (i=0; i<ImageInfo.xp_fields.count; i++) { exif_iif_add_str(&ImageInfo, SECTION_WINXP, exif_get_tagname(ImageInfo.xp_fields.list[i].tag, nullptr, 0, exif_get_tag_table(SECTION_WINXP)), ImageInfo.xp_fields.list[i].value); } if (ImageInfo.Thumbnail.size) { if (thumbnail) { /* not exif_iif_add_str : this is a buffer */ exif_iif_add_tag(&ImageInfo, SECTION_THUMBNAIL, "THUMBNAIL", TAG_NONE, TAG_FMT_UNDEFINED, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.data); } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { /* try to evaluate if thumbnail data is present */ exif_scan_thumbnail(&ImageInfo); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.FileType", ImageInfo.Thumbnail.filetype); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Thumbnail.MimeType", (char*)php_image_type_to_mime_type(ImageInfo.Thumbnail.filetype)); } if (ImageInfo.Thumbnail.width && ImageInfo.Thumbnail.height) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Height", ImageInfo.Thumbnail.height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Width", ImageInfo.Thumbnail.width); } if (sections_str) IM_FREE(sections_str); Array retarr; add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FILE); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMPUTED); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_ANY_TAG); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_IFD0); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_THUMBNAIL); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMMENT); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_EXIF); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_GPS); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_INTEROP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FPIX); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_APP12); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_WINXP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_MAKERNOTE); exif_discard_imageinfo(&ImageInfo); return retarr; } Variant HHVM_FUNCTION(exif_thumbnail, const String& filename, VRefParam width /* = null */, VRefParam height /* = null */, VRefParam imagetype /* = null */) { image_info_type ImageInfo; memset(&ImageInfo, 0, sizeof(ImageInfo)); int ret = exif_read_file(&ImageInfo, filename.c_str(), 1, 0); if (ret==0) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.data || !ImageInfo.Thumbnail.size) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { exif_scan_thumbnail(&ImageInfo); } width.assignIfRef((int64_t)ImageInfo.Thumbnail.width); height.assignIfRef((int64_t)ImageInfo.Thumbnail.height); imagetype.assignIfRef(ImageInfo.Thumbnail.filetype); String str(ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, CopyString); exif_discard_imageinfo(&ImageInfo); return str; } Variant HHVM_FUNCTION(exif_imagetype, const String& filename) { auto stream = File::Open(filename, "rb"); if (!stream) { return false; } int itype = php_getimagetype(stream); stream->close(); if (itype == IMAGE_FILETYPE_UNKNOWN) return false; return itype; } /////////////////////////////////////////////////////////////////////////////// struct ExifExtension final : Extension { ExifExtension() : Extension("exif", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(exif_imagetype); HHVM_FE(exif_read_data); HHVM_FE(exif_tagname); HHVM_FE(exif_thumbnail); HHVM_RC_INT(EXIF_USE_MBSTRING, 0); loadSystemlib(); } } s_exif_extension; struct GdExtension final : Extension { GdExtension() : Extension("gd", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(gd_info); HHVM_FE(getimagesize); HHVM_FE(getimagesizefromstring); HHVM_FE(image_type_to_extension); HHVM_FE(image_type_to_mime_type); HHVM_FE(image2wbmp); HHVM_FE(imageaffine); HHVM_FE(imageaffinematrixconcat); HHVM_FE(imageaffinematrixget); HHVM_FE(imagealphablending); HHVM_FE(imageantialias); HHVM_FE(imagearc); HHVM_FE(imagechar); HHVM_FE(imagecharup); HHVM_FE(imagecolorallocate); HHVM_FE(imagecolorallocatealpha); HHVM_FE(imagecolorat); HHVM_FE(imagecolorclosest); HHVM_FE(imagecolorclosestalpha); HHVM_FE(imagecolorclosesthwb); HHVM_FE(imagecolordeallocate); HHVM_FE(imagecolorexact); HHVM_FE(imagecolorexactalpha); HHVM_FE(imagecolormatch); HHVM_FE(imagecolorresolve); HHVM_FE(imagecolorresolvealpha); HHVM_FE(imagecolorset); HHVM_FE(imagecolorsforindex); HHVM_FE(imagecolorstotal); HHVM_FE(imagecolortransparent); HHVM_FE(imageconvolution); HHVM_FE(imagecopy); HHVM_FE(imagecopymerge); HHVM_FE(imagecopymergegray); HHVM_FE(imagecopyresampled); HHVM_FE(imagecopyresized); HHVM_FE(imagecreate); HHVM_FE(imagecreatefromgd2part); HHVM_FE(imagecreatefromgd); HHVM_FE(imagecreatefromgd2); HHVM_FE(imagecreatefromgif); #ifdef HAVE_GD_JPG HHVM_FE(imagecreatefromjpeg); #endif #ifdef HAVE_GD_PNG HHVM_FE(imagecreatefrompng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagecreatefromwebp); #endif HHVM_FE(imagecreatefromstring); HHVM_FE(imagecreatefromwbmp); HHVM_FE(imagecreatefromxbm); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) HHVM_FE(imagecreatefromxpm); #endif HHVM_FE(imagecreatetruecolor); HHVM_FE(imagecrop); HHVM_FE(imagecropauto); HHVM_FE(imagedashedline); HHVM_FE(imagedestroy); HHVM_FE(imageellipse); HHVM_FE(imagefill); HHVM_FE(imagefilledarc); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilter); HHVM_FE(imageflip); HHVM_FE(imagefontheight); HHVM_FE(imagefontwidth); #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE HHVM_FE(imageftbbox); HHVM_FE(imagefttext); #endif HHVM_FE(imagegammacorrect); HHVM_FE(imagegd2); HHVM_FE(imagegd); HHVM_FE(imagegif); HHVM_FE(imageinterlace); HHVM_FE(imageistruecolor); #ifdef HAVE_GD_JPG HHVM_FE(imagejpeg); #endif HHVM_FE(imagelayereffect); HHVM_FE(imageline); HHVM_FE(imageloadfont); #ifdef HAVE_GD_PNG HHVM_FE(imagepng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagewebp); #endif HHVM_FE(imagepolygon); HHVM_FE(imagerectangle); HHVM_FE(imagerotate); HHVM_FE(imagesavealpha); HHVM_FE(imagescale); HHVM_FE(imagesetbrush); HHVM_FE(imagesetinterpolation); HHVM_FE(imagesetpixel); HHVM_FE(imagesetstyle); HHVM_FE(imagesetthickness); HHVM_FE(imagesettile); HHVM_FE(imagestring); HHVM_FE(imagestringup); HHVM_FE(imagesx); HHVM_FE(imagesy); HHVM_FE(imagetruecolortopalette); #ifdef ENABLE_GD_TTF HHVM_FE(imagettfbbox); HHVM_FE(imagettftext); #endif HHVM_FE(imagetypes); HHVM_FE(imagewbmp); HHVM_FE(iptcembed); HHVM_FE(iptcparse); HHVM_FE(jpeg2wbmp); HHVM_FE(png2wbmp); HHVM_FE(imagepalettecopy); HHVM_RC_INT(IMG_GIF, IMAGE_TYPE_GIF); HHVM_RC_INT(IMG_JPG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_JPEG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_PNG, IMAGE_TYPE_PNG); HHVM_RC_INT(IMG_WBMP, IMAGE_TYPE_WBMP); HHVM_RC_INT(IMG_XPM, IMAGE_TYPE_XPM); /* special colours for gd */ HHVM_RC_INT(IMG_COLOR_TILED, gdTiled); HHVM_RC_INT(IMG_COLOR_STYLED, gdStyled); HHVM_RC_INT(IMG_COLOR_BRUSHED, gdBrushed); HHVM_RC_INT(IMG_COLOR_STYLEDBRUSHED, gdStyledBrushed); HHVM_RC_INT(IMG_COLOR_TRANSPARENT, gdTransparent); /* for imagefilledarc */ HHVM_RC_INT(IMG_ARC_ROUNDED, gdArc); HHVM_RC_INT(IMG_ARC_PIE, gdPie); HHVM_RC_INT(IMG_ARC_CHORD, gdChord); HHVM_RC_INT(IMG_ARC_NOFILL, gdNoFill); HHVM_RC_INT(IMG_ARC_EDGED, gdEdged); /* GD2 image format types */ HHVM_RC_INT(IMG_GD2_RAW, GD2_FMT_RAW); HHVM_RC_INT(IMG_GD2_COMPRESSED, GD2_FMT_COMPRESSED); HHVM_RC_INT(IMG_FLIP_HORIZONTAL, GD_FLIP_HORINZONTAL); HHVM_RC_INT(IMG_FLIP_VERTICAL, GD_FLIP_VERTICAL); HHVM_RC_INT(IMG_FLIP_BOTH, GD_FLIP_BOTH); HHVM_RC_INT(IMG_EFFECT_REPLACE, gdEffectReplace); HHVM_RC_INT(IMG_EFFECT_ALPHABLEND, gdEffectAlphaBlend); HHVM_RC_INT(IMG_EFFECT_NORMAL, gdEffectNormal); HHVM_RC_INT(IMG_EFFECT_OVERLAY, gdEffectOverlay); HHVM_RC_INT(IMG_CROP_DEFAULT, GD_CROP_DEFAULT); HHVM_RC_INT(IMG_CROP_TRANSPARENT, GD_CROP_TRANSPARENT); HHVM_RC_INT(IMG_CROP_BLACK, GD_CROP_BLACK); HHVM_RC_INT(IMG_CROP_WHITE, GD_CROP_WHITE); HHVM_RC_INT(IMG_CROP_SIDES, GD_CROP_SIDES); HHVM_RC_INT(IMG_CROP_THRESHOLD, GD_CROP_THRESHOLD); HHVM_RC_INT(IMG_BELL, GD_BELL); HHVM_RC_INT(IMG_BESSEL, GD_BESSEL); HHVM_RC_INT(IMG_BILINEAR_FIXED, GD_BILINEAR_FIXED); HHVM_RC_INT(IMG_BICUBIC, GD_BICUBIC); HHVM_RC_INT(IMG_BICUBIC_FIXED, GD_BICUBIC_FIXED); HHVM_RC_INT(IMG_BLACKMAN, GD_BLACKMAN); HHVM_RC_INT(IMG_BOX, GD_BOX); HHVM_RC_INT(IMG_BSPLINE, GD_BSPLINE); HHVM_RC_INT(IMG_CATMULLROM, GD_CATMULLROM); HHVM_RC_INT(IMG_GAUSSIAN, GD_GAUSSIAN); HHVM_RC_INT(IMG_GENERALIZED_CUBIC, GD_GENERALIZED_CUBIC); HHVM_RC_INT(IMG_HERMITE, GD_HERMITE); HHVM_RC_INT(IMG_HAMMING, GD_HAMMING); HHVM_RC_INT(IMG_HANNING, GD_HANNING); HHVM_RC_INT(IMG_MITCHELL, GD_MITCHELL); HHVM_RC_INT(IMG_POWER, GD_POWER); HHVM_RC_INT(IMG_QUADRATIC, GD_QUADRATIC); HHVM_RC_INT(IMG_SINC, GD_SINC); HHVM_RC_INT(IMG_NEAREST_NEIGHBOUR, GD_NEAREST_NEIGHBOUR); HHVM_RC_INT(IMG_WEIGHTED4, GD_WEIGHTED4); HHVM_RC_INT(IMG_TRIANGLE, GD_TRIANGLE); HHVM_RC_INT(IMG_AFFINE_TRANSLATE, GD_AFFINE_TRANSLATE); HHVM_RC_INT(IMG_AFFINE_SCALE, GD_AFFINE_SCALE); HHVM_RC_INT(IMG_AFFINE_ROTATE, GD_AFFINE_ROTATE); HHVM_RC_INT(IMG_AFFINE_SHEAR_HORIZONTAL, GD_AFFINE_SHEAR_HORIZONTAL); HHVM_RC_INT(IMG_AFFINE_SHEAR_VERTICAL, GD_AFFINE_SHEAR_VERTICAL); HHVM_RC_INT(IMG_FILTER_BRIGHTNESS, IMAGE_FILTER_BRIGHTNESS); HHVM_RC_INT(IMG_FILTER_COLORIZE, IMAGE_FILTER_COLORIZE); HHVM_RC_INT(IMG_FILTER_CONTRAST, IMAGE_FILTER_CONTRAST); HHVM_RC_INT(IMG_FILTER_EDGEDETECT, IMAGE_FILTER_EDGEDETECT); HHVM_RC_INT(IMG_FILTER_EMBOSS, IMAGE_FILTER_EMBOSS); HHVM_RC_INT(IMG_FILTER_GAUSSIAN_BLUR, IMAGE_FILTER_GAUSSIAN_BLUR); HHVM_RC_INT(IMG_FILTER_GRAYSCALE, IMAGE_FILTER_GRAYSCALE); HHVM_RC_INT(IMG_FILTER_MEAN_REMOVAL, IMAGE_FILTER_MEAN_REMOVAL); HHVM_RC_INT(IMG_FILTER_NEGATE, IMAGE_FILTER_NEGATE); HHVM_RC_INT(IMG_FILTER_SELECTIVE_BLUR, IMAGE_FILTER_SELECTIVE_BLUR); HHVM_RC_INT(IMG_FILTER_SMOOTH, IMAGE_FILTER_SMOOTH); HHVM_RC_INT(IMG_FILTER_PIXELATE, IMAGE_FILTER_PIXELATE); HHVM_RC_INT(IMAGETYPE_GIF, IMAGE_FILETYPE_GIF); HHVM_RC_INT(IMAGETYPE_JPEG, IMAGE_FILETYPE_JPEG); HHVM_RC_INT(IMAGETYPE_PNG, IMAGE_FILETYPE_PNG); HHVM_RC_INT(IMAGETYPE_SWF, IMAGE_FILETYPE_SWF); HHVM_RC_INT(IMAGETYPE_PSD, IMAGE_FILETYPE_PSD); HHVM_RC_INT(IMAGETYPE_BMP, IMAGE_FILETYPE_BMP); HHVM_RC_INT(IMAGETYPE_TIFF_II, IMAGE_FILETYPE_TIFF_II); HHVM_RC_INT(IMAGETYPE_TIFF_MM, IMAGE_FILETYPE_TIFF_MM); HHVM_RC_INT(IMAGETYPE_JPC, IMAGE_FILETYPE_JPC); HHVM_RC_INT(IMAGETYPE_JP2, IMAGE_FILETYPE_JP2); HHVM_RC_INT(IMAGETYPE_JPX, IMAGE_FILETYPE_JPX); HHVM_RC_INT(IMAGETYPE_JB2, IMAGE_FILETYPE_JB2); HHVM_RC_INT(IMAGETYPE_IFF, IMAGE_FILETYPE_IFF); HHVM_RC_INT(IMAGETYPE_WBMP, IMAGE_FILETYPE_WBMP); HHVM_RC_INT(IMAGETYPE_XBM, IMAGE_FILETYPE_XBM); HHVM_RC_INT(IMAGETYPE_ICO, IMAGE_FILETYPE_ICO); HHVM_RC_INT(IMAGETYPE_UNKNOWN, IMAGE_FILETYPE_UNKNOWN); HHVM_RC_INT(IMAGETYPE_COUNT, IMAGE_FILETYPE_COUNT); HHVM_RC_INT(IMAGETYPE_SWC, IMAGE_FILETYPE_SWC); HHVM_RC_INT(IMAGETYPE_JPEG2000, IMAGE_FILETYPE_JPC); #ifdef GD_VERSION_STRING HHVM_RC_STR(GD_VERSION, GD_VERSION_STRING); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && \ defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) HHVM_RC_INT_SAME(GD_MAJOR_VERSION); HHVM_RC_INT_SAME(GD_MINOR_VERSION); HHVM_RC_INT_SAME(GD_RELEASE_VERSION); HHVM_RC_STR_SAME(GD_EXTRA_VERSION); #endif #ifdef HAVE_GD_PNG HHVM_RC_INT(PNG_NO_FILTER, 0x00); HHVM_RC_INT(PNG_FILTER_NONE, 0x08); HHVM_RC_INT(PNG_FILTER_SUB, 0x10); HHVM_RC_INT(PNG_FILTER_UP, 0x20); HHVM_RC_INT(PNG_FILTER_AVG, 0x40); HHVM_RC_INT(PNG_FILTER_PAETH, 0x80); HHVM_RC_INT(PNG_ALL_FILTERS, 0x08 | 0x10 | 0x20 | 0x40 | 0x80); #endif HHVM_RC_BOOL(GD_BUNDLED, true); loadSystemlib(); } } s_gd_extension; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_845_0
crossvul-cpp_data_good_4253_0
/* JSON_parser.c */ /* 2005-12-30 */ /* Copyright (c) 2005 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // If we have json-c then don't use this library since that one has a more // permissive licence #ifndef HAVE_JSONC #include "hphp/runtime/ext/json/JSON_parser.h" #include <folly/FBVector.h> #include "hphp/runtime/base/array-provenance.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/collections.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-info.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/base/init-fini-node.h" #include "hphp/runtime/base/utf8-decode.h" #include "hphp/runtime/ext/json/ext_json.h" #include "hphp/runtime/ext/collections/ext_collections-map.h" #include "hphp/runtime/ext/collections/ext_collections-vector.h" #include "hphp/system/systemlib.h" #include "hphp/util/fast_strtoll_base10.h" #include "hphp/zend/zend-strtod.h" #define MAX_LENGTH_OF_LONG 20 static const char long_min_digits[] = "9223372036854775808"; namespace HPHP { /* Characters are mapped into these 32 symbol classes. This allows for significant reductions in the size of the state transition table. */ /* error */ #define S_ERR -1 /* space */ #define S_SPA 0 /* other whitespace */ #define S_WSP 1 /* { */ #define S_LBE 2 /* } */ #define S_RBE 3 /* [ */ #define S_LBT 4 /* ] */ #define S_RBT 5 /* : */ #define S_COL 6 /* , */ #define S_COM 7 /* " */ #define S_QUO 8 /* \ */ #define S_BAC 9 /* / */ #define S_SLA 10 /* + */ #define S_PLU 11 /* - */ #define S_MIN 12 /* . */ #define S_DOT 13 /* 0 */ #define S_ZER 14 /* 123456789 */ #define S_DIG 15 /* a */ #define S__A_ 16 /* b */ #define S__B_ 17 /* c */ #define S__C_ 18 /* d */ #define S__D_ 19 /* e */ #define S__E_ 20 /* f */ #define S__F_ 21 /* l */ #define S__L_ 22 /* n */ #define S__N_ 23 /* r */ #define S__R_ 24 /* s */ #define S__S_ 25 /* t */ #define S__T_ 26 /* u */ #define S__U_ 27 /* ABCDF */ #define S_A_F 28 /* E */ #define S_E 29 /* everything else */ #define S_ETC 30 /* This table maps the 128 ASCII characters into the 32 character classes. The remaining Unicode characters should be mapped to S_ETC. */ alignas(64) static const int8_t ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*<fb>*/ alignas(64) static const int8_t loose_ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*</fb>*/ /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. A new state is a number between 0 and 29. An action is a negative number between -1 and -9. A JSON text is accepted if the end of the text is in state 9 and mode is Mode::DONE. */ alignas(64) static const int8_t state_transition_table[30][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} }; /*<fb>*/ /* Alternate "loose" transition table to support unquoted keys. Note: State 3 has same outgoing transitions in both transition tables. This is used below in the fast-case for appending simple characters (3 -> 3). */ alignas(64) static const int8_t loose_state_transition_table[31][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-7,-1,-1,-1,-7, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /*30*/ {30,-1,30,30,30,30,-10,30,-4,4,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30} }; /*</fb>*/ /** * These modes can be pushed on the PDA stack. */ enum class Mode { INVALID = 0, DONE = 1, KEY = 2, OBJECT = 3, ARRAY = 4 }; namespace { int dehexchar(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - ('A' - 10); if (c >= 'a' && c <= 'f') return c - ('a' - 10); return -1; } NEVER_INLINE static void tvDecRefRange(TypedValue* begin, TypedValue* end) { assertx(begin <= end); for (auto tv = begin; tv != end; ++tv) { tvDecRefGen(tv); } } /* * Parses a subset of JSON. Currently unsupported: * - Non-ASCII * - Character escape sequences * - Non-string array keys * - Arrays nested > 255 levels */ struct SimpleParser { static constexpr int kMaxArrayDepth = 255; /* * Returns buffer size in bytes needed to handle any input up to given length. */ static size_t BufferBytesForLength(int length) { return (length + 1) * sizeof(TypedValue) / 2; // Worst case: "[0,0,...,0]" } /* * Returns false for unsupported or malformed input (does not distinguish). */ static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); if (!ok || (parser.skipSpace(), parser.p != inp + length)) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; } private: SimpleParser(const char* input, int length, TypedValue* buffer, JSONContainerType container_type, bool is_tsimplejson) : p(input) , top(buffer) , array_depth(-kMaxArrayDepth) /* Start negative to simplify check. */ , container_type(container_type) , is_tsimplejson(is_tsimplejson) { assertx(input[length] == 0); // Parser relies on sentinel to avoid checks. } /* * Skip whitespace, then if next char is 'ch', consume it and return true, * otherwise let it be and return false. */ bool matchSeparator(char ch) { if (LIKELY(*p++ == ch)) return true; return matchSeparatorSlow(ch); } NEVER_INLINE bool matchSeparatorSlow(char ch) { --p; skipSpace(); if (LIKELY(*p++ == ch)) return true; --p; return false; } NEVER_INLINE void skipSpace() { while (isSpace(*p)) p++; } bool isSpace(char ch) const { return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\f'; } /* * Variant parser. * * JSON arrays don't permit leading 0's in numbers, so we have to thread that * context through here to parseNumber(). */ bool parseValue(bool array_elem = false) { auto const ch = *p++; if (ch == '{') return parseMixed(); else if (ch == '[') return parsePacked(); else if (ch == '\"') return parseString(); else if ((ch >= '0' && ch <= '9') || ch == '-') return parseNumber(ch, array_elem); else if (ch == 't') return parseRue(); else if (ch == 'f') return parseAlse(); else if (ch == 'n') return parseUll(); else if (isSpace(ch)) { skipSpace(); return parseValue(array_elem); } else return false; } bool parseRue() { if (*p++ != 'r') return false; if (*p++ != 'u') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = true; return true; } bool parseAlse() { if (*p++ != 'a') return false; if (*p++ != 'l') return false; if (*p++ != 's') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = false; return true; } bool parseUll() { if (*p++ != 'u') return false; if (*p++ != 'l') return false; if (*p++ != 'l') return false; top++->m_type = KindOfNull; return true; } bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } } bool parseRawString(int* len) { assertx(p[-1] == '"'); // SimpleParser only handles "-quoted strings *len = 0; auto const charTop = reinterpret_cast<signed char*>(top); for (signed char ch = *p++; ch != '\"'; ch = *p++) { charTop[(*len)++] = ch; // overwritten later if `ch == '\\'` if (ch < ' ') { // `ch < ' '` catches null and also non-ASCII (since signed char) return false; } else if (ch == '\\') { if (!handleBackslash(charTop[*len - 1])) return false; } } return true; } bool parseString() { int len; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); pushStringData(StringData::Make(start, len, CopyString)); return true; } bool parseMixedKey() { int len; int64_t num; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); auto const slice = folly::StringPiece(start, len); start[len] = '\0'; if (container_type != JSONContainerType::HACK_ARRAYS && container_type != JSONContainerType::LEGACY_HACK_ARRAYS && is_strictly_integer(start, len, num)) { pushInt64(num); } else if (auto const str = lookupStaticString(slice)) { auto const tv = top++; tv->m_type = KindOfPersistentString; tv->m_data.pstr = str; } else { pushStringData(StringData::Make(start, len, CopyString)); } return true; } bool parsePacked() { auto const fp = top; if (!matchSeparator(']')) { if (++array_depth >= 0) return false; do { if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator(']')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateVec() : PackedArray::MakeVecNatural(top - fp, fp); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyVecArray()->copy() : PackedArray::MakeVecNatural(top - fp, fp); ret->setLegacyArray(true); return ret; } if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { return top == fp ? ArrayData::CreateVArray() : PackedArray::MakeVArrayNatural(top - fp, fp); } assertx(container_type == JSONContainerType::DARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArrayNatural(top - fp, fp); }(); top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } bool parseMixed() { auto const fp = top; if (!matchSeparator('}')) { if (++array_depth >= 0) return false; do { if (!matchSeparator('\"')) return false; // Only support string keys. if (!parseMixedKey()) return false; // TODO(14491721): Precompute and save hash to avoid deref in MakeMixed. if (!matchSeparator(':')) return false; if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator('}')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateDict() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyDictArray()->copy() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); ret->setLegacyArray(true); return ret; } assertx(container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArray((top - fp) >> 1, fp)->asArrayData(); }(); // MixedArray::MakeMixed can return nullptr if there are duplicate keys if (!arr) return false; top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } /* * Parse remainder of number after initial character firstChar (maybe '-'). */ bool parseNumber(char firstChar, bool array_elem = false) { uint64_t x = 0; bool neg = false; const char* begin = p - 1; if (firstChar == '-') { neg = true; } else { x = firstChar - '0'; // first digit } // Parse maximal digit sequence into x (non-negative). while (*p >= '0' && *p <= '9') { x = (x * 10) + (*p - '0'); ++p; } if (*p == '.' || *p == 'e' || *p == 'E') { pushDouble(zend_strtod(begin, &p)); return true; } auto len = p - begin; // JSON arrays don't permit leading 0's in numbers. if (UNLIKELY(len > 1 && firstChar == '0' && array_elem)) { return false; } // Now 'x' is the usigned absolute value of a naively parsed integer, but // potentially overflowed mod 2^64. if (LIKELY(len < 19) || (len == 19 && firstChar <= '8')) { int64_t sx = x; pushInt64(neg ? -sx : sx); } else { parseBigInt(len); } return true; } /* * Assuming 'len' characters ('0'-'9', maybe prefix '-') have been read, * re-parse and push as an int64_t if possible, otherwise as a double. */ void parseBigInt(int len) { assertx(*p > '9' || *p < '0'); // Aleady read maximal digit sequence. errno = 0; const int64_t sx = strtoll(p - len, nullptr, 10); if (errno == ERANGE) { const double dval = zend_strtod(p - len, nullptr); assertx(dval == floor(dval)); pushDouble(dval); } else { pushInt64(sx); } } void pushDouble(double data) { auto const tv = top++; tv->m_type = KindOfDouble; tv->m_data.dbl = data; } void pushInt64(int64_t data) { auto const tv = top++; tv->m_type = KindOfInt64; tv->m_data.num = data; } void pushStringData(StringData* data) { auto const tv = top++; tv->m_type = KindOfString; tv->m_data.pstr = data; } void pushArrayData(ArrayData* data) { auto const tv = top++; tv->m_type = data->toDataType(); tv->m_data.parr = data; assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } const char* p; TypedValue* top; int array_depth; JSONContainerType container_type; bool is_tsimplejson; }; /* * String buffer wrapper that does NOT check its capacity in release mode. User * supplies the allocation and must ensure to never append past the end. */ struct UncheckedBuffer { void clear() { p = begin; } // Use given buffer with space for 'cap' chars, including '\0'. void setBuf(char* buf, size_t cap) { begin = p = buf; #ifndef NDEBUG end = begin + cap; #endif } void append(char c) { assertx(p < end); *p++ = c; } void shrinkBy(int decrease) { p -= decrease; assertx(p >= begin); } int size() { return p - begin; } // NUL-terminates the output before returning it, for backward-compatibility. char* data() { assertx(p < end); *p = 0; return begin; } String copy() { return String(data(), size(), CopyString); } char* p{nullptr}; char* begin{nullptr}; #ifndef NDEBUG char* end{nullptr}; #endif }; } /** * A stack maintains the states of nested structures. */ struct json_parser { struct json_state { Mode mode; String key; Variant val; }; folly::fbvector<json_state> stack; // check_non_safepoint_surprise() above will not trigger gc TYPE_SCAN_IGNORE_FIELD(stack); int top; int mark; // the watermark int depth; json_error_codes error_code; // Thread-local buffer; reused on each call. JSON parsing cannot lead to code // execution and is not re-entrant. SimpleParser assumes no surprise checks. union { TypedValue* tv{nullptr}; // SimpleParser's stack. char* raw; // sb_buf/key } tl_buffer; TYPE_SCAN_IGNORE_FIELD(tv); UncheckedBuffer sb_buf; UncheckedBuffer sb_key; int sb_cap{0}; // Capacity of each of sb_buf/key. void initSb(int length) { if (UNLIKELY(length >= sb_cap)) { // No decoded string in the output can use more bytes than input size. const auto new_cap = length + 1; size_t bufSize = length <= RuntimeOption::EvalSimpleJsonMaxLength ? SimpleParser::BufferBytesForLength(length) : new_cap * 2; if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; if (!tl_heap->preAllocOOM(bufSize)) { tl_buffer.raw = (char*)json_malloc(bufSize); if (!tl_buffer.raw) tl_heap->forceOOM(); } check_non_safepoint_surprise(); always_assert(tl_buffer.raw); sb_buf.setBuf(tl_buffer.raw, new_cap); sb_key.setBuf(tl_buffer.raw + new_cap, new_cap); // Set new capacity if and ony if allocations succeed. sb_cap = new_cap; } else { sb_buf.clear(); sb_key.clear(); } } void flushSb() { if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; sb_buf.setBuf(nullptr, 0); sb_key.setBuf(nullptr, 0); } private: static void* json_malloc(size_t size) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_malloc(size); } else { return malloc(size); } } static void json_free(void* ptr) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_free(ptr); } else { return free(ptr); } } }; RDS_LOCAL(json_parser, s_json_parser); // In Zend, the json_parser struct is publicly // accessible. Thus the fields could be accessed // directly. Just using setter/accessor functions // to get around that. json_error_codes json_get_last_error_code() { return s_json_parser->error_code; } void json_set_last_error_code(json_error_codes ec) { s_json_parser->error_code = ec; } const char *json_get_last_error_msg() { switch (s_json_parser->error_code) { case JSON_ERROR_NONE: return "No error"; case JSON_ERROR_DEPTH: return "Maximum stack depth exceeded"; case JSON_ERROR_STATE_MISMATCH: return "State mismatch (invalid or malformed JSON)"; case JSON_ERROR_CTRL_CHAR: return "Control character error, possibly incorrectly encoded"; case JSON_ERROR_SYNTAX: return "Syntax error"; case JSON_ERROR_UTF8: return "Malformed UTF-8 characters, possibly incorrectly encoded"; case json_error_codes::JSON_ERROR_RECURSION: return "Recursion detected"; case json_error_codes::JSON_ERROR_INF_OR_NAN: return "Inf and NaN cannot be JSON encoded"; case json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE: return "Type is not supported"; default: return "Unknown error"; } } // For each request, make sure we start with the default error code. void json_parser_init() { s_json_parser->error_code = JSON_ERROR_NONE; } void json_parser_flush_caches() { s_json_parser->flushSb(); } /** * Push a mode onto the stack. Return false if there is overflow. */ static int push(json_parser *json, Mode mode) { if (json->top + 1 >= json->depth) { return false; } json->top += 1; json->stack[json->top].mode = mode; if (json->top > json->mark) { json->mark = json->top; } return true; } /** * Pop the stack, assuring that the current mode matches the expectation. * Return false if there is underflow or if the modes mismatch. */ static int pop(json_parser *json, Mode mode) { if (json->top < 0 || json->stack[json->top].mode != mode) { return false; } json->stack[json->top].mode = Mode::INVALID; json->top -= 1; return true; } static String copy_and_clear(UncheckedBuffer &buf) { auto ret = buf.size() > 0 ? buf.copy() : empty_string(); buf.clear(); return ret; } static Variant to_double(UncheckedBuffer &buf) { auto data = buf.data(); auto ret = data ? zend_strtod(data, nullptr) : 0.0; buf.clear(); return ret; } static void json_create_zval(Variant &z, UncheckedBuffer &buf, DataType type, int64_t options) { switch (type) { case KindOfBoolean: z = (buf.data() && (*buf.data() == 't')); return; case KindOfInt64: { bool bigint = false; const char *p = buf.data(); assertx(p); if (p == NULL) { z = int64_t(0); return; } bool neg = *buf.data() == '-'; int len = buf.size(); if (neg) len--; if (len >= MAX_LENGTH_OF_LONG - 1) { if (len == MAX_LENGTH_OF_LONG - 1) { int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits); if (!(cmp < 0 || (cmp == 0 && neg))) { bigint = true; } } else { bigint = true; } } if (bigint) { if (!(options & k_JSON_BIGINT_AS_STRING)) { // See KindOfDouble (below) z = to_double(buf); } else { z = copy_and_clear(buf); } } else { z = fast_strtoll_base10(buf.data()); } return; } case KindOfDouble: // Use zend_strtod() instead of strtod() here since JSON specifies using // a '.' for decimal separators regardless of locale. z = to_double(buf); return; case KindOfString: z = copy_and_clear(buf); return; case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfPersistentArray: case KindOfArray: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfObject: case KindOfResource: case KindOfFunc: case KindOfClass: case KindOfClsMeth: case KindOfRecord: z = uninit_null(); return; } not_reached(); } NEVER_INLINE void utf16_to_utf8_tail(UncheckedBuffer &buf, unsigned short utf16) { if (utf16 < 0x800) { buf.append((char)(0xc0 | (utf16 >> 6))); buf.append((char)(0x80 | (utf16 & 0x3f))); } else if ((utf16 & 0xfc00) == 0xdc00 && buf.size() >= 3 && ((unsigned char)buf.data()[buf.size() - 3]) == 0xed && ((unsigned char)buf.data()[buf.size() - 2] & 0xf0) == 0xa0 && ((unsigned char)buf.data()[buf.size() - 1] & 0xc0) == 0x80) { /* found surrogate pair */ unsigned long utf32; utf32 = (((buf.data()[buf.size() - 2] & 0xf) << 16) | ((buf.data()[buf.size() - 1] & 0x3f) << 10) | (utf16 & 0x3ff)) + 0x10000; buf.shrinkBy(3); buf.append((char)(0xf0 | (utf32 >> 18))); buf.append((char)(0x80 | ((utf32 >> 12) & 0x3f))); buf.append((char)(0x80 | ((utf32 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf32 & 0x3f))); } else { buf.append((char)(0xe0 | (utf16 >> 12))); buf.append((char)(0x80 | ((utf16 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf16 & 0x3f))); } } ALWAYS_INLINE void utf16_to_utf8(UncheckedBuffer &buf, unsigned short utf16) { if (LIKELY(utf16 < 0x80)) { buf.append((char)utf16); return; } return utf16_to_utf8_tail(buf, utf16); } StaticString s__empty_("_empty_"); static void object_set(const json_parser* json, Variant &var, const String& key, const Variant& value, int assoc, JSONContainerType container_type) { if (!assoc) { // We know it is stdClass, and everything is public (and dynamic). if (key.empty()) { var.getObjectData()->setProp(nullptr, s__empty_.get(), *value.asTypedValue()); } else { var.getObjectData()->o_set(key, value); } } else { if (container_type == JSONContainerType::COLLECTIONS) { auto keyTV = make_tv<KindOfString>(key.get()); collections::set(var.getObjectData(), &keyTV, value.asTypedValue()); } else if (container_type == JSONContainerType::HACK_ARRAYS || container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { forceToDict(var).set(key, value); } else { int64_t i; if (key.get()->isStrictlyInteger(i)) { forceToDArray(var).set(i, value); } else { forceToDArray(var).set(key, value); } } if (var.isArray()) { DEBUG_ONLY auto const data = var.getArrayData(); assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } } } static void attach_zval(json_parser *json, const String& key, int assoc, JSONContainerType container_type) { if (json->top < 1) { return; } auto& root = json->stack[json->top - 1].val; auto& child = json->stack[json->top].val; auto up_mode = json->stack[json->top - 1].mode; if (up_mode == Mode::ARRAY) { if (container_type == JSONContainerType::COLLECTIONS) { collections::append(root.getObjectData(), child.asTypedValue()); } else { root.asArrRef().append(child); } } else if (up_mode == Mode::OBJECT) { object_set(json, root, key, child, assoc, container_type); } } JSONContainerType get_container_type_from_options(int64_t options) { if ((options & k_JSON_FB_STABLE_MAPS) || (options & k_JSON_FB_COLLECTIONS)) { return JSONContainerType::COLLECTIONS; } if (options & k_JSON_FB_HACK_ARRAYS) { return JSONContainerType::HACK_ARRAYS; } if (options & k_JSON_FB_DARRAYS) { return JSONContainerType::DARRAYS; } if (options & k_JSON_FB_DARRAYS_AND_VARRAYS) { return JSONContainerType::DARRAYS_AND_VARRAYS; } if (options & k_JSON_FB_LEGACY_HACK_ARRAYS) { return JSONContainerType::LEGACY_HACK_ARRAYS; } return JSONContainerType::DARRAYS; } /** * The JSON_parser takes a UTF-8 encoded string and determines if it is a * syntactically correct JSON text. Along the way, it creates a PHP variable. * * It is implemented as a Pushdown Automaton; that means it is a finite state * machine with a stack. * * The behavior is as follows: * Container Type | is_assoc | JSON input => output type * * COLLECTIONS | true | "{}" => c_Map * COLLECTIONS | false | "{}" => c_Map * COLLECTIONS | true | "[]" => c_Vector * COLLECTIONS | false | "[]" => c_Vector * * HACK_ARRAYS | true | "{}" => dict * HACK_ARRAYS | false | "{}" => stdClass * HACK_ARRAYS | true | "[]" => vec * HACK_ARRAYS | false | "[]" => stdClass * * DARRAYS | true | "{}" => darray * DARRAYS | false | "{}" => stdClass * DARRAYS | true | "[]" => darray * DARRAYS | false | "[]" => stdClass * * DARRAYS_AND_VARRAYS | true | "{}" => darray * DARRAYS_AND_VARRAYS | false | "{}" => stdClass * DARRAYS_AND_VARRAYS | true | "[]" => varray * DARRAYS_AND_VARRAYS | false | "[]" => stdClass */ bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } #endif /* HAVE_JSONC */
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_4253_0
crossvul-cpp_data_bad_849_1
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/io/async/test/AsyncSSLSocketTest.h> #include <folly/SocketAddress.h> #include <folly/String.h> #include <folly/io/Cursor.h> #include <folly/io/async/AsyncPipe.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/EventBase.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <folly/net/NetOps.h> #include <folly/net/NetworkSocket.h> #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <folly/portability/OpenSSL.h> #include <folly/portability/Unistd.h> #include <folly/ssl/Init.h> #include <folly/io/async/test/BlockingSocket.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <fstream> #include <iostream> #include <list> #include <set> #include <thread> #ifdef __linux__ #include <dlfcn.h> #endif #if FOLLY_OPENSSL_IS_110 #include <openssl/async.h> #endif #ifdef FOLLY_HAVE_MSG_ERRQUEUE #include <sys/utsname.h> #endif using std::cerr; using std::endl; using std::list; using std::min; using std::string; using std::vector; using namespace testing; #if defined __linux__ namespace { // to store libc's original setsockopt() typedef int (*setsockopt_ptr)(int, int, int, const void*, socklen_t); setsockopt_ptr real_setsockopt_ = nullptr; // global struct to initialize before main runs. we can init within a test, // or in main, but this method seems to be least intrsive and universal struct GlobalStatic { GlobalStatic() { real_setsockopt_ = (setsockopt_ptr)dlsym(RTLD_NEXT, "setsockopt"); } void reset() noexcept { ttlsDisabledSet.clear(); } // for each fd, tracks whether TTLS is disabled or not std::unordered_set<folly::NetworkSocket /* fd */> ttlsDisabledSet; }; // the constructor will be called before main() which is all we care about GlobalStatic globalStatic; } // namespace // we intercept setsoctopt to test setting NO_TRANSPARENT_TLS opt // this name has to be global int setsockopt( int sockfd, int level, int optname, const void* optval, socklen_t optlen) { if (optname == SO_NO_TRANSPARENT_TLS) { globalStatic.ttlsDisabledSet.insert(folly::NetworkSocket::fromFd(sockfd)); return 0; } return real_setsockopt_(sockfd, level, optname, optval, optlen); } #endif namespace folly { constexpr size_t SSLClient::kMaxReadBufferSz; constexpr size_t SSLClient::kMaxReadsPerEvent; void getfds(NetworkSocket fds[2]) { if (netops::socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) { FAIL() << "failed to create socketpair: " << errnoStr(errno); } for (int idx = 0; idx < 2; ++idx) { if (netops::set_socket_non_blocking(fds[idx]) != 0) { FAIL() << "failed to put socket " << idx << " in non-blocking mode: " << errnoStr(errno); } } } void getctx( std::shared_ptr<folly::SSLContext> clientCtx, std::shared_ptr<folly::SSLContext> serverCtx) { clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadPrivateKey(kTestKey); } void sslsocketpair( EventBase* eventBase, AsyncSSLSocket::UniquePtr* clientSock, AsyncSSLSocket::UniquePtr* serverSock) { auto clientCtx = std::make_shared<folly::SSLContext>(); auto serverCtx = std::make_shared<folly::SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, serverCtx); clientSock->reset(new AsyncSSLSocket(clientCtx, eventBase, fds[0], false)); serverSock->reset(new AsyncSSLSocket(serverCtx, eventBase, fds[1], true)); // (*clientSock)->setSendTimeout(100); // (*serverSock)->setSendTimeout(100); } // client protocol filters bool clientProtoFilterPickPony( unsigned char** client, unsigned int* client_len, const unsigned char*, unsigned int) { // the protocol string in length prefixed byte string. the // length byte is not included in the length static unsigned char p[7] = {6, 'p', 'o', 'n', 'i', 'e', 's'}; *client = p; *client_len = 7; return true; } bool clientProtoFilterPickNone( unsigned char**, unsigned int*, const unsigned char*, unsigned int) { return false; } std::string getFileAsBuf(const char* fileName) { std::string buffer; folly::readFile(fileName, buffer); return buffer; } /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server. */ TEST(AsyncSSLSocketTest, ConnectWriteReadClose) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem"); // sslContext->authenticate(true, false); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(std::chrono::milliseconds(10000)); // write() uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); // read() uint8_t readbuf[128]; uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf)); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0); // close() socket->close(); cerr << "ConnectWriteReadClose test completed" << endl; EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000); } /** * Same as above simple test, but with a large read len to test * clamping behavior. */ TEST(AsyncSSLSocketTest, ConnectWriteReadLargeClose) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem"); // sslContext->authenticate(true, false); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(std::chrono::milliseconds(10000)); // write() uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); // read() uint8_t readbuf[128]; // we will fake the read len but that should be fine size_t readLen = 1L << 33; uint32_t bytesRead = socket->read(readbuf, readLen); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0); // close() socket->close(); cerr << "ConnectWriteReadClose test completed" << endl; EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000); } /** * Test reading after server close. */ TEST(AsyncSSLSocketTest, ReadAfterClose) { // Start listening on a local port WriteCallbackBase writeCallback; ReadEOFCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); auto server = std::make_unique<TestSSLServer>(&acceptCallback); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); auto socket = std::make_shared<BlockingSocket>(server->getAddress(), sslContext); socket->open(); // This should trigger an EOF on the client. auto evb = handshakeCallback.getSocket()->getEventBase(); evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); }); std::array<uint8_t, 128> readbuf; auto bytesRead = socket->read(readbuf.data(), readbuf.size()); EXPECT_EQ(0, bytesRead); } /** * Test bad renegotiation */ #if !defined(OPENSSL_IS_BORINGSSL) TEST(AsyncSSLSocketTest, Renegotiate) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); std::array<NetworkSocket, 2> fds; getfds(fds.data()); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); RenegotiatingServer server(std::move(serverSock)); while (!client.handshakeSuccess_ && !client.handshakeError_) { eventBase.loopOnce(); } ASSERT_TRUE(client.handshakeSuccess_); auto sslSock = std::move(client).moveSocket(); sslSock->detachEventBase(); // This is nasty, however we don't want to add support for // renegotiation in AsyncSSLSocket. SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL())); auto socket = std::make_shared<BlockingSocket>(std::move(sslSock)); std::thread t([&]() { eventBase.loopForever(); }); // Trigger the renegotiation. std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); try { socket->write(buf.data(), buf.size()); } catch (AsyncSocketException& e) { LOG(INFO) << "client got error " << e.what(); } eventBase.terminateLoopSoon(); t.join(); eventBase.loop(); ASSERT_TRUE(server.renegotiationError_); } #endif /** * Negative test for handshakeError(). */ TEST(AsyncSSLSocketTest, HandshakeError) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); HandshakeErrorCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); // read() bool ex = false; try { socket->open(); uint8_t readbuf[128]; uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf)); LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing"; } catch (AsyncSocketException&) { ex = true; } EXPECT_TRUE(ex); // close() socket->close(); cerr << "HandshakeError test completed" << endl; } /** * Negative test for readError(). */ TEST(AsyncSSLSocketTest, ReadError) { // Start listening on a local port WriteCallbackBase writeCallback; ReadErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // write something to trigger ssl handshake uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); socket->close(); cerr << "ReadError test completed" << endl; } /** * Negative test for writeError(). */ TEST(AsyncSSLSocketTest, WriteError) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // write something to trigger ssl handshake uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); socket->close(); cerr << "WriteError test completed" << endl; } /** * Test a socket with TCP_NODELAY unset. */ TEST(AsyncSSLSocketTest, SocketWithDelay) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // write() uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); // read() uint8_t readbuf[128]; uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf)); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0); // close() socket->close(); cerr << "SocketWithDelay test completed" << endl; } #if FOLLY_OPENSSL_HAS_ALPN class NextProtocolTest : public Test { // For matching protos public: void SetUp() override { getctx(clientCtx, serverCtx); } void connect(bool unset = false) { getfds(fds); if (unset) { // unsetting NPN for any of [client, server] is enough to make NPN not // work clientCtx->unsetNextProtocols(); } AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); client = std::make_unique<AlpnClient>(std::move(clientSock)); server = std::make_unique<AlpnServer>(std::move(serverSock)); eventBase.loop(); } void expectProtocol(const std::string& proto) { expectHandshakeSuccess(); EXPECT_NE(client->nextProtoLength, 0); EXPECT_EQ(client->nextProtoLength, server->nextProtoLength); EXPECT_EQ( memcmp(client->nextProto, server->nextProto, server->nextProtoLength), 0); string selected((const char*)client->nextProto, client->nextProtoLength); EXPECT_EQ(proto, selected); } void expectNoProtocol() { expectHandshakeSuccess(); EXPECT_EQ(client->nextProtoLength, 0); EXPECT_EQ(server->nextProtoLength, 0); EXPECT_EQ(client->nextProto, nullptr); EXPECT_EQ(server->nextProto, nullptr); } void expectHandshakeSuccess() { EXPECT_FALSE(client->except.hasValue()) << "client handshake error: " << client->except->what(); EXPECT_FALSE(server->except.hasValue()) << "server handshake error: " << server->except->what(); } void expectHandshakeError() { EXPECT_TRUE(client->except.hasValue()) << "Expected client handshake error!"; EXPECT_TRUE(server->except.hasValue()) << "Expected server handshake error!"; } EventBase eventBase; std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()}; std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()}; NetworkSocket fds[2]; std::unique_ptr<AlpnClient> client; std::unique_ptr<AlpnServer> server; }; TEST_F(NextProtocolTest, AlpnTestOverlap) { clientCtx->setAdvertisedNextProtocols({"blub", "baz"}); serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); connect(); expectProtocol("baz"); } TEST_F(NextProtocolTest, AlpnTestUnset) { // Identical to above test, except that we want unset NPN before // looping. clientCtx->setAdvertisedNextProtocols({"blub", "baz"}); serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); connect(true /* unset */); expectNoProtocol(); } TEST_F(NextProtocolTest, AlpnTestNoOverlap) { clientCtx->setAdvertisedNextProtocols({"blub"}); serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); connect(); expectNoProtocol(); } TEST_F(NextProtocolTest, RandomizedAlpnTest) { // Probability that this test will fail is 2^-64, which could be considered // as negligible. const int kTries = 64; clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}}); std::set<string> selectedProtocols; for (int i = 0; i < kTries; ++i) { connect(); EXPECT_NE(client->nextProtoLength, 0); EXPECT_EQ(client->nextProtoLength, server->nextProtoLength); EXPECT_EQ( memcmp(client->nextProto, server->nextProto, server->nextProtoLength), 0); string selected((const char*)client->nextProto, client->nextProtoLength); selectedProtocols.insert(selected); expectHandshakeSuccess(); } EXPECT_EQ(selectedProtocols.size(), 2); } #endif #ifndef OPENSSL_NO_TLSEXT /** * 1. Client sends TLSEXT_HOSTNAME in client hello. * 2. Server found a match SSL_CTX and use this SSL_CTX to * continue the SSL handshake. * 3. Server sends back TLSEXT_HOSTNAME in server hello. */ TEST(AsyncSSLSocketTest, SNITestMatch) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string serverName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverName); eventBase.loop(); EXPECT_TRUE(client.serverNameMatch); EXPECT_TRUE(server.serverNameMatch); } /** * 1. Client sends TLSEXT_HOSTNAME in client hello. * 2. Server cannot find a matching SSL_CTX and continue to use * the current SSL_CTX to do the handshake. * 3. Server does not send back TLSEXT_HOSTNAME in server hello. */ TEST(AsyncSSLSocketTest, SNITestNotMatch) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string clientRequestingServerName("foo.com"); const std::string serverExpectedServerName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock(new AsyncSSLSocket( clientCtx, &eventBase, fds[0], clientRequestingServerName)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverExpectedServerName); eventBase.loop(); EXPECT_TRUE(!client.serverNameMatch); EXPECT_TRUE(!server.serverNameMatch); } /** * 1. Client sends TLSEXT_HOSTNAME in client hello. * 2. We then change the serverName. * 3. We expect that we get 'false' as the result for serNameMatch. */ TEST(AsyncSSLSocketTest, SNITestChangeServerName) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string serverName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName)); // Change the server name std::string newName("new.com"); clientSock->setServerName(newName); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverName); eventBase.loop(); EXPECT_TRUE(!client.serverNameMatch); } /** * 1. Client does not send TLSEXT_HOSTNAME in client hello. * 2. Server does not send back TLSEXT_HOSTNAME in server hello. */ TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string serverExpectedServerName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverExpectedServerName); eventBase.loop(); EXPECT_TRUE(!client.serverNameMatch); EXPECT_TRUE(!server.serverNameMatch); } #endif /** * Test SSL client socket */ TEST(AsyncSSLSocketTest, SSLClientTest) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL client EventBase eventBase; auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1); client->connect(); EventBaseAborter eba(&eventBase, 3000); eventBase.loop(); EXPECT_EQ(client->getMiss(), 1); EXPECT_EQ(client->getHit(), 0); cerr << "SSLClientTest test completed" << endl; } /** * Test SSL client socket session re-use */ TEST(AsyncSSLSocketTest, SSLClientTestReuse) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL client EventBase eventBase; auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10); client->connect(); EventBaseAborter eba(&eventBase, 3000); eventBase.loop(); EXPECT_EQ(client->getMiss(), 1); EXPECT_EQ(client->getHit(), 9); cerr << "SSLClientTestReuse test completed" << endl; } /** * Test SSL client socket timeout */ TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) { // Start listening on a local port EmptyReadCallback readCallback; HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); HandshakeTimeoutCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL client EventBase eventBase; auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10); client->connect(true /* write before connect completes */); EventBaseAborter eba(&eventBase, 3000); eventBase.loop(); usleep(100000); // This is checking that the connectError callback precedes any queued // writeError callbacks. This matches AsyncSocket's behavior EXPECT_EQ(client->getWriteAfterConnectErrors(), 1); EXPECT_EQ(client->getErrors(), 1); EXPECT_EQ(client->getMiss(), 0); EXPECT_EQ(client->getHit(), 0); cerr << "SSLClientTimeoutTest test completed" << endl; } /** * Verify Client Ciphers obtained using SSL MSG Callback. */ TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("AES256-SHA:AES128-SHA"); clientCtx->loadPrivateKey(kTestKey); clientCtx->loadCertificate(kTestCert); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true); eventBase.loop(); #if defined(OPENSSL_IS_BORINGSSL) EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA"); #else EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff"); #endif EXPECT_EQ(server.chosenCipher_, "AES256-SHA"); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_TRUE(server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); } /** * Verify that server is able to get client cert by getPeerCert() API. */ TEST(AsyncSSLSocketTest, GetClientCertificate) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kClientTestCA); serverCtx->loadClientCAList(kClientTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("AES256-SHA:AES128-SHA"); clientCtx->loadPrivateKey(kClientTestKey); clientCtx->loadCertificate(kClientTestCert); clientCtx->loadTrustedCertificates(kTestCA); std::array<NetworkSocket, 2> fds; getfds(fds.data()); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true); eventBase.loop(); // Handshake should succeed. EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(server.handshakeSuccess_); // Reclaim the sockets from SSLHandshakeBase. auto cliSocket = std::move(client).moveSocket(); auto srvSocket = std::move(server).moveSocket(); // Client cert retrieved from server side. auto serverPeerCert = srvSocket->getPeerCertificate(); CHECK(serverPeerCert); // Client cert retrieved from client side. auto clientSelfCert = cliSocket->getSelfCertificate(); CHECK(clientSelfCert); auto serverX509 = serverPeerCert->getX509(); auto clientX509 = clientSelfCert->getX509(); CHECK(serverX509); CHECK(clientX509); // The two certs should be the same. EXPECT_EQ(0, X509_cmp(clientX509.get(), serverX509.get())); } TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) { EventBase eventBase; auto ctx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); int bufLen = 42; uint8_t majorVersion = 18; uint8_t minorVersion = 25; // Create callback buf auto buf = IOBuf::create(bufLen); buf->append(bufLen); folly::io::RWPrivateCursor cursor(buf.get()); cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO); cursor.write<uint16_t>(0); cursor.write<uint8_t>(38); cursor.write<uint8_t>(majorVersion); cursor.write<uint8_t>(minorVersion); cursor.skip(32); cursor.write<uint32_t>(0); SSL* ssl = ctx->createSSL(); SCOPE_EXIT { SSL_free(ssl); }; AsyncSSLSocket::UniquePtr sock( new AsyncSSLSocket(ctx, &eventBase, fds[0], true)); sock->enableClientHelloParsing(); // Test client hello parsing in one packet AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get()); buf.reset(); auto parsedClientHello = sock->getClientHelloInfo(); EXPECT_TRUE(parsedClientHello != nullptr); EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion); EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion); } TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) { EventBase eventBase; auto ctx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); int bufLen = 42; uint8_t majorVersion = 18; uint8_t minorVersion = 25; // Create callback buf auto buf = IOBuf::create(bufLen); buf->append(bufLen); folly::io::RWPrivateCursor cursor(buf.get()); cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO); cursor.write<uint16_t>(0); cursor.write<uint8_t>(38); cursor.write<uint8_t>(majorVersion); cursor.write<uint8_t>(minorVersion); cursor.skip(32); cursor.write<uint32_t>(0); SSL* ssl = ctx->createSSL(); SCOPE_EXIT { SSL_free(ssl); }; AsyncSSLSocket::UniquePtr sock( new AsyncSSLSocket(ctx, &eventBase, fds[0], true)); sock->enableClientHelloParsing(); // Test parsing with two packets with first packet size < 3 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2); AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(), ssl, sock.get()); bufCopy.reset(); bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2); AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(), ssl, sock.get()); bufCopy.reset(); auto parsedClientHello = sock->getClientHelloInfo(); EXPECT_TRUE(parsedClientHello != nullptr); EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion); EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion); } TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) { EventBase eventBase; auto ctx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); int bufLen = 42; uint8_t majorVersion = 18; uint8_t minorVersion = 25; // Create callback buf auto buf = IOBuf::create(bufLen); buf->append(bufLen); folly::io::RWPrivateCursor cursor(buf.get()); cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO); cursor.write<uint16_t>(0); cursor.write<uint8_t>(38); cursor.write<uint8_t>(majorVersion); cursor.write<uint8_t>(minorVersion); cursor.skip(32); cursor.write<uint32_t>(0); SSL* ssl = ctx->createSSL(); SCOPE_EXIT { SSL_free(ssl); }; AsyncSSLSocket::UniquePtr sock( new AsyncSSLSocket(ctx, &eventBase, fds[0], true)); sock->enableClientHelloParsing(); // Test parsing with multiple small packets for (std::size_t i = 0; i < buf->length(); i += 3) { auto bufCopy = folly::IOBuf::copyBuffer( buf->data() + i, std::min((std::size_t)3, buf->length() - i)); AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(), ssl, sock.get()); bufCopy.reset(); } auto parsedClientHello = sock->getClientHelloInfo(); EXPECT_TRUE(parsedClientHello != nullptr); EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion); EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion); } /** * Verify sucessful behavior of SSL certificate validation. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); clientCtx->loadTrustedCertificates(kTestCA); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the client's verification callback is able to fail SSL * connection establishment. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, false); clientCtx->loadTrustedCertificates(kTestCA); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(!client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(!server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the options in SSLContext can be overridden in * sslConnect/Accept.i.e specifying that no validation should be performed * allows an otherwise-invalid certificate to be accepted and doesn't fire * the validation callback. */ TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClientNoVerify client(std::move(clientSock), false, false); clientCtx->loadTrustedCertificates(kTestCA); SSLHandshakeServerNoVerify server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(!client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the options in SSLContext can be overridden in * sslConnect/Accept. Enable verification even if context says otherwise. * Test requireClientCert with client cert */ TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadPrivateKey(kTestKey); clientCtx->loadCertificate(kTestCert); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClientDoVerify client(std::move(clientSock), true, true); SSLHandshakeServerDoVerify server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the client's verification callback is able to override * the preverification failure and allow a successful connection. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that specifying that no validation should be performed allows an * otherwise-invalid certificate to be accepted and doesn't fire the validation * callback. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(!client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Test requireClientCert with client cert */ TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption( SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadPrivateKey(kTestKey); clientCtx->loadCertificate(kTestCert); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); // check certificates auto clientSsl = std::move(client).moveSocket(); auto serverSsl = std::move(server).moveSocket(); auto clientPeer = clientSsl->getPeerCertificate(); auto clientSelf = clientSsl->getSelfCertificate(); auto serverPeer = serverSsl->getPeerCertificate(); auto serverSelf = serverSsl->getSelfCertificate(); EXPECT_NE(clientPeer, nullptr); EXPECT_NE(clientSelf, nullptr); EXPECT_NE(serverPeer, nullptr); EXPECT_NE(serverSelf, nullptr); EXPECT_EQ(clientPeer->getIdentity(), serverSelf->getIdentity()); EXPECT_EQ(clientSelf->getIdentity(), serverPeer->getIdentity()); } /** * Test requireClientCert with no client cert */ TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption( SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_FALSE(server.handshakeVerify_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_LE(0, server.handshakeTime.count()); } /** * Test OpenSSL 1.1.0's async functionality */ #if FOLLY_OPENSSL_IS_110 static void makeNonBlockingPipe(int pipefds[2]) { if (pipe(pipefds) != 0) { throw std::runtime_error("Cannot create pipe"); } if (::fcntl(pipefds[0], F_SETFL, O_NONBLOCK) != 0) { throw std::runtime_error("Cannot set pipe to nonblocking"); } if (::fcntl(pipefds[1], F_SETFL, O_NONBLOCK) != 0) { throw std::runtime_error("Cannot set pipe to nonblocking"); } } // Custom RSA private key encryption method static int kRSAExIndex = -1; static int kRSAEvbExIndex = -1; static int kRSASocketExIndex = -1; static constexpr StringPiece kEngineId = "AsyncSSLSocketTest"; static int customRsaPrivEnc( int flen, const unsigned char* from, unsigned char* to, RSA* rsa, int padding) { LOG(INFO) << "rsa_priv_enc"; EventBase* asyncJobEvb = reinterpret_cast<EventBase*>(RSA_get_ex_data(rsa, kRSAEvbExIndex)); CHECK(asyncJobEvb); RSA* actualRSA = reinterpret_cast<RSA*>(RSA_get_ex_data(rsa, kRSAExIndex)); CHECK(actualRSA); AsyncSSLSocket* socket = reinterpret_cast<AsyncSSLSocket*>( RSA_get_ex_data(rsa, kRSASocketExIndex)); ASYNC_JOB* job = ASYNC_get_current_job(); if (job == nullptr) { throw std::runtime_error("Expected call in job context"); } ASYNC_WAIT_CTX* waitctx = ASYNC_get_wait_ctx(job); OSSL_ASYNC_FD pipefds[2] = {0, 0}; makeNonBlockingPipe(pipefds); if (!ASYNC_WAIT_CTX_set_wait_fd( waitctx, kEngineId.data(), pipefds[0], nullptr, nullptr)) { throw std::runtime_error("Cannot set wait fd"); } int ret = 0; int* retptr = &ret; auto hand = folly::NetworkSocket::native_handle_type(pipefds[1]); auto asyncPipeWriter = folly::AsyncPipeWriter::newWriter( asyncJobEvb, folly::NetworkSocket(hand)); asyncJobEvb->runInEventBaseThread([retptr = retptr, flen = flen, from = from, to = to, padding = padding, actualRSA = actualRSA, writer = std::move(asyncPipeWriter), socket = socket]() { LOG(INFO) << "Running job"; if (socket) { LOG(INFO) << "Got a socket passed in, closing it..."; socket->closeNow(); } *retptr = RSA_meth_get_priv_enc(RSA_PKCS1_OpenSSL())( flen, from, to, actualRSA, padding); LOG(INFO) << "Finished job, writing to pipe"; uint8_t byte = *retptr > 0 ? 1 : 0; writer->write(nullptr, &byte, 1); }); LOG(INFO) << "About to pause job"; ASYNC_pause_job(); LOG(INFO) << "Resumed job with ret: " << ret; return ret; } void rsaFree(void*, void* ptr, CRYPTO_EX_DATA*, int, long, void*) { LOG(INFO) << "RSA_free is called with ptr " << std::hex << ptr; if (ptr == nullptr) { LOG(INFO) << "Returning early from rsaFree because ptr is null"; return; } RSA* rsa = (RSA*)ptr; auto meth = RSA_get_method(rsa); if (meth != RSA_get_default_method()) { auto nonconst = const_cast<RSA_METHOD*>(meth); RSA_meth_free(nonconst); RSA_set_method(rsa, RSA_get_default_method()); } RSA_free(rsa); } struct RSAPointers { RSA* actualrsa{nullptr}; RSA* dummyrsa{nullptr}; RSA_METHOD* meth{nullptr}; }; inline void RSAPointersFree(RSAPointers* p) { if (p->meth && p->dummyrsa && RSA_get_method(p->dummyrsa) == p->meth) { RSA_set_method(p->dummyrsa, RSA_get_default_method()); } if (p->meth) { LOG(INFO) << "Freeing meth"; RSA_meth_free(p->meth); } if (p->actualrsa) { LOG(INFO) << "Freeing actualrsa"; RSA_free(p->actualrsa); } if (p->dummyrsa) { LOG(INFO) << "Freeing dummyrsa"; RSA_free(p->dummyrsa); } delete p; } using RSAPointersDeleter = folly::static_function_deleter<RSAPointers, RSAPointersFree>; std::unique_ptr<RSAPointers, RSAPointersDeleter> setupCustomRSA(const char* certPath, const char* keyPath, EventBase* jobEvb) { auto certPEM = getFileAsBuf(certPath); auto keyPEM = getFileAsBuf(keyPath); ssl::BioUniquePtr certBio( BIO_new_mem_buf((void*)certPEM.data(), certPEM.size())); ssl::BioUniquePtr keyBio( BIO_new_mem_buf((void*)keyPEM.data(), keyPEM.size())); ssl::X509UniquePtr cert( PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr)); ssl::EvpPkeyUniquePtr evpPkey( PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr)); ssl::EvpPkeyUniquePtr publicEvpPkey(X509_get_pubkey(cert.get())); std::unique_ptr<RSAPointers, RSAPointersDeleter> ret(new RSAPointers()); RSA* actualrsa = EVP_PKEY_get1_RSA(evpPkey.get()); LOG(INFO) << "actualrsa ptr " << std::hex << (void*)actualrsa; RSA* dummyrsa = EVP_PKEY_get1_RSA(publicEvpPkey.get()); if (dummyrsa == nullptr) { throw std::runtime_error("Couldn't get RSA cert public factors"); } RSA_METHOD* meth = RSA_meth_dup(RSA_get_default_method()); if (meth == nullptr || RSA_meth_set1_name(meth, "Async RSA method") == 0 || RSA_meth_set_priv_enc(meth, customRsaPrivEnc) == 0 || RSA_meth_set_flags(meth, RSA_METHOD_FLAG_NO_CHECK) == 0) { throw std::runtime_error("Cannot create async RSA_METHOD"); } RSA_set_method(dummyrsa, meth); RSA_set_flags(dummyrsa, RSA_FLAG_EXT_PKEY); kRSAExIndex = RSA_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); kRSAEvbExIndex = RSA_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); kRSASocketExIndex = RSA_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); CHECK_NE(kRSAExIndex, -1); CHECK_NE(kRSAEvbExIndex, -1); CHECK_NE(kRSASocketExIndex, -1); RSA_set_ex_data(dummyrsa, kRSAExIndex, actualrsa); RSA_set_ex_data(dummyrsa, kRSAEvbExIndex, jobEvb); ret->actualrsa = actualrsa; ret->dummyrsa = dummyrsa; ret->meth = meth; return ret; } // TODO: disabled with ASAN doesn't play nice with ASYNC for some reason #ifndef FOLLY_SANITIZE_ADDRESS TEST(AsyncSSLSocketTest, OpenSSL110AsyncTest) { ASYNC_init_thread(1, 1); EventBase eventBase; ScopedEventBaseThread jobEvbThread; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); auto rsaPointers = setupCustomRSA(kTestCert, kTestKey, jobEvbThread.getEventBase()); CHECK(rsaPointers->dummyrsa); // up-refs dummyrsa SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa); SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(client.handshakeSuccess_); ASYNC_cleanup_thread(); } TEST(AsyncSSLSocketTest, OpenSSL110AsyncTestFailure) { ASYNC_init_thread(1, 1); EventBase eventBase; ScopedEventBaseThread jobEvbThread; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); // Set the wrong key for the cert auto rsaPointers = setupCustomRSA(kTestCert, kClientTestKey, jobEvbThread.getEventBase()); CHECK(rsaPointers->dummyrsa); SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa); SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(server.handshakeError_); EXPECT_TRUE(client.handshakeError_); ASYNC_cleanup_thread(); } TEST(AsyncSSLSocketTest, OpenSSL110AsyncTestClosedWithCallbackPending) { ASYNC_init_thread(1, 1); EventBase eventBase; ScopedEventBaseThread jobEvbThread; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); auto rsaPointers = setupCustomRSA(kTestCert, kTestKey, jobEvbThread.getEventBase()); CHECK(rsaPointers->dummyrsa); // up-refs dummyrsa SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa); SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); RSA_set_ex_data(rsaPointers->dummyrsa, kRSASocketExIndex, serverSock.get()); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(server.handshakeError_); EXPECT_TRUE(client.handshakeError_); ASYNC_cleanup_thread(); } #endif // FOLLY_SANITIZE_ADDRESS #endif // FOLLY_OPENSSL_IS_110 TEST(AsyncSSLSocketTest, LoadCertFromMemory) { using folly::ssl::OpenSSLUtils; auto cert = getFileAsBuf(kTestCert); auto key = getFileAsBuf(kTestKey); ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem())); BIO_write(certBio.get(), cert.data(), cert.size()); ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem())); BIO_write(keyBio.get(), key.data(), key.size()); // Create SSL structs from buffers to get properties ssl::X509UniquePtr certStruct( PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr)); ssl::EvpPkeyUniquePtr keyStruct( PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr)); certBio = nullptr; keyBio = nullptr; auto origCommonName = OpenSSLUtils::getCommonName(certStruct.get()); auto origKeySize = EVP_PKEY_bits(keyStruct.get()); certStruct = nullptr; keyStruct = nullptr; auto ctx = std::make_shared<SSLContext>(); ctx->loadPrivateKeyFromBufferPEM(key); ctx->loadCertificateFromBufferPEM(cert); ctx->loadTrustedCertificates(kTestCA); ssl::SSLUniquePtr ssl(ctx->createSSL()); auto newCert = SSL_get_certificate(ssl.get()); auto newKey = SSL_get_privatekey(ssl.get()); // Get properties from SSL struct auto newCommonName = OpenSSLUtils::getCommonName(newCert); auto newKeySize = EVP_PKEY_bits(newKey); // Check that the key and cert have the expected properties EXPECT_EQ(origCommonName, newCommonName); EXPECT_EQ(origKeySize, newKeySize); } TEST(AsyncSSLSocketTest, MinWriteSizeTest) { EventBase eb; // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // create SSL socket AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb)); EXPECT_EQ(1500, socket->getMinWriteSize()); socket->setMinWriteSize(0); EXPECT_EQ(0, socket->getMinWriteSize()); socket->setMinWriteSize(50000); EXPECT_EQ(50000, socket->getMinWriteSize()); } class ReadCallbackTerminator : public ReadCallback { public: ReadCallbackTerminator(EventBase* base, WriteCallbackBase* wcb) : ReadCallback(wcb), base_(base) {} // Do not write data back, terminate the loop. void readDataAvailable(size_t len) noexcept override { std::cerr << "readDataAvailable, len " << len << std::endl; currentBuffer.length = len; buffers.push_back(currentBuffer); currentBuffer.reset(); state = STATE_SUCCEEDED; socket_->setReadCB(nullptr); base_->terminateLoopSoon(); } private: EventBase* base_; }; /** * Test a full unencrypted codepath */ TEST(AsyncSSLSocketTest, UnencryptedTest) { EventBase base; auto clientCtx = std::make_shared<folly::SSLContext>(); auto serverCtx = std::make_shared<folly::SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, serverCtx); auto client = AsyncSSLSocket::newSocket(clientCtx, &base, fds[0], false, true); auto server = AsyncSSLSocket::newSocket(serverCtx, &base, fds[1], true, true); ReadCallbackTerminator readCallback(&base, nullptr); server->setReadCB(&readCallback); readCallback.setSocket(server); uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); client->write(nullptr, buf, sizeof(buf)); // Check that bytes are unencrypted char c; EXPECT_EQ(1, netops::recv(fds[1], &c, 1, MSG_PEEK)); EXPECT_EQ('a', c); EventBaseAborter eba(&base, 3000); base.loop(); EXPECT_EQ(1, readCallback.buffers.size()); EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState()); server->setReadCB(&readCallback); // Unencrypted server->sslAccept(nullptr); client->sslConn(nullptr); // Do NOT wait for handshake, writing should be queued and happen after client->write(nullptr, buf, sizeof(buf)); // Check that bytes are *not* unencrypted char c2; EXPECT_EQ(1, netops::recv(fds[1], &c2, 1, MSG_PEEK)); EXPECT_NE('a', c2); base.loop(); EXPECT_EQ(2, readCallback.buffers.size()); EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState()); } TEST(AsyncSSLSocketTest, ConnectUnencryptedTest) { auto clientCtx = std::make_shared<folly::SSLContext>(); auto serverCtx = std::make_shared<folly::SSLContext>(); getctx(clientCtx, serverCtx); WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); EventBase evb; std::shared_ptr<AsyncSSLSocket> socket = AsyncSSLSocket::newSocket(clientCtx, &evb, true); socket->connect(nullptr, server.getAddress(), 0); evb.loop(); EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, socket->getSSLState()); socket->sslConn(nullptr); evb.loop(); EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, socket->getSSLState()); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(nullptr, buf.data(), buf.size()); socket->close(); } /** * Test acceptrunner in various situations */ TEST(AsyncSSLSocketTest, SSLAcceptRunnerBasic) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); serverCtx->sslAcceptRunner(std::make_unique<SSLAcceptEvbRunner>(&eventBase)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptError) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptErrorRunner>(&eventBase)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_FALSE(client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptClose) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptCloseRunner>(&eventBase, serverSock.get())); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_FALSE(client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptDestroy) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptDestroyRunner>(&eventBase, &server)); eventBase.loop(); EXPECT_FALSE(client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerFiber) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptFiberRunner>(&eventBase)); eventBase.loop(); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); } static int newCloseCb(SSL* ssl, SSL_SESSION*) { AsyncSSLSocket::getFromSSL(ssl)->closeNow(); return 1; } #if FOLLY_OPENSSL_IS_110 static SSL_SESSION* getCloseCb(SSL* ssl, const unsigned char*, int, int*) { #else static SSL_SESSION* getCloseCb(SSL* ssl, unsigned char*, int, int*) { #endif AsyncSSLSocket::getFromSSL(ssl)->closeNow(); return nullptr; } // namespace folly TEST(AsyncSSLSocketTest, SSLAcceptRunnerFiberCloseSessionCb) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); SSL_CTX_set_session_cache_mode( serverCtx->getSSLCtx(), SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_new_cb(serverCtx->getSSLCtx(), &newCloseCb); SSL_CTX_sess_set_get_cb(serverCtx->getSSLCtx(), &getCloseCb); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptFiberRunner>(&eventBase)); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("AES128-SHA256"); clientCtx->loadTrustedCertificates(kTestCA); clientCtx->setOptions(SSL_OP_NO_TICKET); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); // As close() is called during session callbacks, client sees it as a // successful connection EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, ConnResetErrorString) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr); socket->open(); uint8_t buf[3] = {0x16, 0x03, 0x01}; socket->write(buf, sizeof(buf)); socket->closeWithReset(); handshakeCallback.waitForHandshake(); EXPECT_NE( handshakeCallback.errorString_.find("Network error"), std::string::npos); EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos); } TEST(AsyncSSLSocketTest, ConnEOFErrorString) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr); socket->open(); uint8_t buf[3] = {0x16, 0x03, 0x01}; socket->write(buf, sizeof(buf)); socket->close(); handshakeCallback.waitForHandshake(); #if FOLLY_OPENSSL_IS_110 EXPECT_NE( handshakeCallback.errorString_.find("Network error"), std::string::npos); #else EXPECT_NE( handshakeCallback.errorString_.find("Connection EOF"), std::string::npos); #endif } TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr); socket->open(); uint8_t buf[256] = {0x16, 0x03}; memset(buf + 2, 'a', sizeof(buf) - 2); socket->write(buf, sizeof(buf)); socket->close(); handshakeCallback.waitForHandshake(); EXPECT_NE( handshakeCallback.errorString_.find("SSL routines"), std::string::npos); #if defined(OPENSSL_IS_BORINGSSL) EXPECT_NE( handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"), std::string::npos); #elif FOLLY_OPENSSL_IS_110 EXPECT_NE( handshakeCallback.errorString_.find("packet length too long"), std::string::npos); #else EXPECT_NE( handshakeCallback.errorString_.find("unknown protocol"), std::string::npos); #endif } TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) { using folly::ssl::OpenSSLUtils; EXPECT_EQ( OpenSSLUtils::getCipherName(0xc02c), "ECDHE-ECDSA-AES256-GCM-SHA384"); // TLS_DHE_RSA_WITH_DES_CBC_SHA - We shouldn't be building with this EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015), ""); // This indicates TLS_EMPTY_RENEGOTIATION_INFO_SCSV, no name expected EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff), ""); } #if defined __linux__ /** * Ensure TransparentTLS flag is disabled with AsyncSSLSocket */ TEST(AsyncSSLSocketTest, TTLSDisabled) { // clear all setsockopt tracking history globalStatic.reset(); // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, false); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); EXPECT_EQ(1, globalStatic.ttlsDisabledSet.count(socket->getNetworkSocket())); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // close() socket->close(); } #endif #if FOLLY_ALLOW_TFO class MockAsyncTFOSSLSocket : public AsyncSSLSocket { public: using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>; explicit MockAsyncTFOSSLSocket( std::shared_ptr<folly::SSLContext> sslCtx, EventBase* evb) : AsyncSocket(evb), AsyncSSLSocket(sslCtx, evb) {} MOCK_METHOD3( tfoSendMsg, ssize_t(NetworkSocket fd, struct msghdr* msg, int msg_flags)); }; #if defined __linux__ /** * Ensure TransparentTLS flag is disabled with AsyncSSLSocket + TFO */ TEST(AsyncSSLSocketTest, TTLSDisabledWithTFO) { // clear all setsockopt tracking history globalStatic.reset(); // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); socket->open(); EXPECT_EQ(1, globalStatic.ttlsDisabledSet.count(socket->getNetworkSocket())); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // close() socket->close(); } #endif /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server with TFO. */ TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); socket->open(); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // read() std::array<uint8_t, 128> readbuf; uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0); // close() socket->close(); } /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server with TFO. */ TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, false); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); socket->open(); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // read() std::array<uint8_t, 128> readbuf; uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0); // close() socket->close(); } class ConnCallback : public AsyncSocket::ConnectCallback { public: void connectSuccess() noexcept override { state = State::SUCCESS; } void connectErr(const AsyncSocketException& ex) noexcept override { state = State::ERROR; error = ex.what(); } enum class State { WAITING, SUCCESS, ERROR }; State state{State::WAITING}; std::string error; }; template <class Cardinality> MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback( EventBase* evb, const SocketAddress& address, Cardinality cardinality) { // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = MockAsyncTFOSSLSocket::UniquePtr( new MockAsyncTFOSSLSocket(sslContext, evb)); socket->enableTFO(); EXPECT_CALL(*socket, tfoSendMsg(_, _, _)) .Times(cardinality) .WillOnce(Invoke([&](NetworkSocket fd, struct msghdr*, int) { sockaddr_storage addr; auto len = address.getAddress(&addr); return netops::connect(fd, (const struct sockaddr*)&addr, len); })); return socket; } TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); EventBase evb; auto socket = setupSocketWithFallback(&evb, server.getAddress(), 1); ConnCallback ccb; socket->connect(&ccb, server.getAddress(), 30); evb.loop(); EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state); evb.runInEventBaseThread([&] { socket->detachEventBase(); }); evb.loop(); BlockingSocket sock(std::move(socket)); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); sock.write(buf.data(), buf.size()); // read() std::array<uint8_t, 128> readbuf; uint32_t bytesRead = sock.readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0); // close() sock.close(); } #if !defined(OPENSSL_IS_BORINGSSL) TEST(AsyncSSLSocketTest, ConnectTFOTimeout) { // Start listening on a local port ConnectTimeoutCallback acceptCallback; TestSSLServer server(&acceptCallback, true); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); EXPECT_THROW( socket->open(std::chrono::milliseconds(20)), AsyncSocketException); } #endif #if !defined(OPENSSL_IS_BORINGSSL) TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) { // Start listening on a local port ConnectTimeoutCallback acceptCallback; TestSSLServer server(&acceptCallback, true); EventBase evb; auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1)); ConnCallback ccb; // Set a short timeout socket->connect(&ccb, server.getAddress(), 1); evb.loop(); EXPECT_EQ(ConnCallback::State::ERROR, ccb.state); } #endif TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) { // Start listening on a local port EmptyReadCallback readCallback; HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); HandshakeTimeoutCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); EventBase evb; auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1)); ConnCallback ccb; socket->connect(&ccb, server.getAddress(), 100); evb.loop(); EXPECT_EQ(ConnCallback::State::ERROR, ccb.state); EXPECT_THAT(ccb.error, testing::HasSubstr("SSL connect timed out")); } TEST(AsyncSSLSocketTest, HandshakeTFORefused) { // Start listening on a local port EventBase evb; // Hopefully nothing is listening on this address SocketAddress addr("127.0.0.1", 65535); auto socket = setupSocketWithFallback(&evb, addr, AtMost(1)); ConnCallback ccb; socket->connect(&ccb, addr, 100); evb.loop(); EXPECT_EQ(ConnCallback::State::ERROR, ccb.state); EXPECT_THAT(ccb.error, testing::HasSubstr("refused")); } TEST(AsyncSSLSocketTest, TestPreReceivedData) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); std::array<NetworkSocket, 2> fds; getfds(fds.data()); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSockPtr( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSockPtr( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); auto clientSock = clientSockPtr.get(); auto serverSock = serverSockPtr.get(); SSLHandshakeClient client(std::move(clientSockPtr), true, true); // Steal some data from the server. std::array<uint8_t, 10> buf; auto bytesReceived = netops::recv(fds[1], buf.data(), buf.size(), 0); checkUnixError(bytesReceived, "recv failed"); serverSock->setPreReceivedData( IOBuf::wrapBuffer(ByteRange(buf.data(), bytesReceived))); SSLHandshakeServer server(std::move(serverSockPtr), true, true); while (!client.handshakeSuccess_ && !client.handshakeError_) { eventBase.loopOnce(); } EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_EQ( serverSock->getRawBytesReceived(), clientSock->getRawBytesWritten()); } TEST(AsyncSSLSocketTest, TestMoveFromAsyncSocket) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); std::array<NetworkSocket, 2> fds; getfds(fds.data()); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSockPtr( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSocket::UniquePtr serverSockPtr(new AsyncSocket(&eventBase, fds[1])); auto clientSock = clientSockPtr.get(); auto serverSock = serverSockPtr.get(); SSLHandshakeClient client(std::move(clientSockPtr), true, true); // Steal some data from the server. std::array<uint8_t, 10> buf; auto bytesReceived = netops::recv(fds[1], buf.data(), buf.size(), 0); checkUnixError(bytesReceived, "recv failed"); serverSock->setPreReceivedData( IOBuf::wrapBuffer(ByteRange(buf.data(), bytesReceived))); AsyncSSLSocket::UniquePtr serverSSLSockPtr( new AsyncSSLSocket(dfServerCtx, std::move(serverSockPtr), true)); auto serverSSLSock = serverSSLSockPtr.get(); SSLHandshakeServer server(std::move(serverSSLSockPtr), true, true); while (!client.handshakeSuccess_ && !client.handshakeError_) { eventBase.loopOnce(); } EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_EQ( serverSSLSock->getRawBytesReceived(), clientSock->getRawBytesWritten()); } /** * Test overriding the flags passed to "sendmsg()" system call, * and verifying that write requests fail properly. */ TEST(AsyncSSLSocketTest, SendMsgParamsCallback) { // Start listening on a local port SendMsgFlagsCallback msgCallback; ExpectWriteErrorCallback writeCallback(&msgCallback); ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // Setting flags to "-1" to trigger "Invalid argument" error // on attempt to use this flags in sendmsg() system call. msgCallback.resetFlags(-1); // write() std::vector<uint8_t> buf(128, 'a'); ASSERT_EQ(socket->write(buf.data(), buf.size()), buf.size()); // close() socket->close(); cerr << "SendMsgParamsCallback test completed" << endl; } #ifdef FOLLY_HAVE_MSG_ERRQUEUE /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server with ancillary data from the application. */ TEST(AsyncSSLSocketTest, SendMsgDataCallback) { // This test requires Linux kernel v4.6 or later struct utsname s_uname; memset(&s_uname, 0, sizeof(s_uname)); ASSERT_EQ(uname(&s_uname), 0); int major, minor; folly::StringPiece extra; if (folly::split<false>( '.', std::string(s_uname.release) + ".", major, minor, extra)) { if (major < 4 || (major == 4 && minor < 6)) { LOG(INFO) << "Kernel version: 4.6 and newer required for this test (" << "kernel ver. " << s_uname.release << " detected)."; return; } } // Start listening on a local port SendMsgAncillaryDataCallback msgCallback; WriteCheckTimestampCallback writeCallback(&msgCallback); ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // we'll pass the EOR and TIMESTAMP_TX flags with the write back // EOR tracking must be enabled for WriteFlags be passed const auto writeFlags = folly::WriteFlags::EOR | folly::WriteFlags::TIMESTAMP_TX; readCallback.setWriteFlags(writeFlags); msgCallback.setEorTracking(true); // Init ancillary data buffer to trigger timestamp notification // // We generate the same ancillary data regardless of the specific WriteFlags, // we verify that the WriteFlags are observed as expected below. union { uint8_t ctrl_data[CMSG_LEN(sizeof(uint32_t))]; struct cmsghdr cmsg; } u; u.cmsg.cmsg_level = SOL_SOCKET; u.cmsg.cmsg_type = SO_TIMESTAMPING; u.cmsg.cmsg_len = CMSG_LEN(sizeof(uint32_t)); uint32_t flags = SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_TX_ACK; memcpy(CMSG_DATA(&u.cmsg), &flags, sizeof(uint32_t)); std::vector<char> ctrl(CMSG_LEN(sizeof(uint32_t))); memcpy(ctrl.data(), u.ctrl_data, CMSG_LEN(sizeof(uint32_t))); msgCallback.resetData(std::move(ctrl)); // write(), including flags std::vector<uint8_t> buf(128, 'a'); socket->write(buf.data(), buf.size(), writeFlags); // read() std::vector<uint8_t> readbuf(buf.size()); uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, buf.size()); EXPECT_TRUE(std::equal(buf.begin(), buf.end(), readbuf.begin())); // should receive three timestamps (schedule, TX/SND, ACK) // may take some time for all to arrive, so loop to wait // // socket error queue does not have the equivalent of an EOF, so we must // loop on it unless we want to use libevent for this test... const std::vector<int32_t> timestampsExpected = { SCM_TSTAMP_SCHED, SCM_TSTAMP_SND, SCM_TSTAMP_ACK}; std::vector<int32_t> timestampsReceived; while (timestampsExpected.size() != timestampsReceived.size()) { const auto timestamps = writeCallback.getTimestampNotifications(); timestampsReceived.insert( timestampsReceived.end(), timestamps.begin(), timestamps.end()); } EXPECT_THAT(timestampsReceived, ElementsAreArray(timestampsExpected)); // check the observed write flags EXPECT_EQ( static_cast<std::underlying_type<folly::WriteFlags>::type>( msgCallback.getObservedWriteFlags()), static_cast<std::underlying_type<folly::WriteFlags>::type>(writeFlags)); // close() socket->close(); cerr << "SendMsgDataCallback test completed" << endl; } #endif // FOLLY_HAVE_MSG_ERRQUEUE #endif TEST(AsyncSSLSocketTest, TestSNIClientHelloBehavior) { EventBase eventBase; auto serverCtx = std::make_shared<SSLContext>(); auto clientCtx = std::make_shared<SSLContext>(); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setSessionCacheContext("test context"); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); SSL_SESSION* resumptionSession = nullptr; { std::array<NetworkSocket, 2> fds; getfds(fds.data()); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); // Client sends SNI that doesn't match anything the server cert advertises clientSock->setServerName("Foobar"); SSLHandshakeServerParseClientHello server( std::move(serverSock), true, true); SSLHandshakeClient client(std::move(clientSock), true, true); eventBase.loop(); serverSock = std::move(server).moveSocket(); auto chi = serverSock->getClientHelloInfo(); ASSERT_NE(chi, nullptr); EXPECT_EQ( std::string("Foobar"), std::string(serverSock->getSSLServerName())); // create another client, resuming with the prior session, but under a // different common name. clientSock = std::move(client).moveSocket(); resumptionSession = clientSock->getSSLSession(); } { std::array<NetworkSocket, 2> fds; getfds(fds.data()); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); clientSock->setSSLSession(resumptionSession, true); clientSock->setServerName("Baz"); SSLHandshakeServerParseClientHello server( std::move(serverSock), true, true); SSLHandshakeClient client(std::move(clientSock), true, true); eventBase.loop(); serverSock = std::move(server).moveSocket(); clientSock = std::move(client).moveSocket(); EXPECT_TRUE(clientSock->getSSLSessionReused()); // OpenSSL 1.1.1 changes the semantics of SSL_get_servername // in // https://github.com/openssl/openssl/commit/1c4aa31d79821dee9be98e915159d52cc30d8403 // // Previously, the SNI would be taken from the ClientHello. // Now, the SNI will be taken from the established session. // // But the session that was established with the client (prior handshake) // would not have set the server name field because the SNI that the client // requested ("Foobar") did not match any of the SANs that the server was // presenting ("127.0.0.1") // // To preserve this 1.1.0 behavior, getSSLServerName() should return the // parsed ClientHello servername. This test asserts this behavior. auto sni = serverSock->getSSLServerName(); ASSERT_NE(sni, nullptr); std::string sniStr(sni); EXPECT_EQ(sniStr, std::string("Baz")); } } } // namespace folly #ifdef SIGPIPE /////////////////////////////////////////////////////////////////////////// // init_unit_test_suite /////////////////////////////////////////////////////////////////////////// namespace { struct Initializer { Initializer() { signal(SIGPIPE, SIG_IGN); } }; Initializer initializer; } // namespace #endif
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_849_1
crossvul-cpp_data_good_93_0
/* -*- C++ -*- * File: libraw_cxx.cpp * Copyright 2008-2018 LibRaw LLC (info@libraw.org) * Created: Sat Mar 8 , 2008 * * LibRaw C++ interface (implementation) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). */ #include <math.h> #include <errno.h> #include <float.h> #include <new> #include <exception> #include <sys/types.h> #include <sys/stat.h> #if !defined(_WIN32) && !defined(__MINGW32__) #include <netinet/in.h> #else #include <winsock2.h> #endif #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #ifdef USE_ZLIB #include <zlib.h> #endif #ifdef USE_RAWSPEED #include "../RawSpeed/rawspeed_xmldata.cpp" #include <RawSpeed/StdAfx.h> #include <RawSpeed/FileMap.h> #include <RawSpeed/RawParser.h> #include <RawSpeed/RawDecoder.h> #include <RawSpeed/CameraMetaData.h> #include <RawSpeed/ColorFilterArray.h> #endif #ifdef USE_DNGSDK #include "dng_host.h" #include "dng_negative.h" #include "dng_simple_image.h" #include "dng_info.h" #endif #include "libraw_fuji_compressed.cpp" #ifdef __cplusplus extern "C" { #endif void default_memory_callback(void *, const char *file, const char *where) { fprintf(stderr, "%s: Out of memory in %s\n", file ? file : "unknown file", where); } void default_data_callback(void *, const char *file, const int offset) { if (offset < 0) fprintf(stderr, "%s: Unexpected end of file\n", file ? file : "unknown file"); else fprintf(stderr, "%s: data corrupted at %d\n", file ? file : "unknown file", offset); } const char *libraw_strerror(int e) { enum LibRaw_errors errorcode = (LibRaw_errors)e; switch (errorcode) { case LIBRAW_SUCCESS: return "No error"; case LIBRAW_UNSPECIFIED_ERROR: return "Unspecified error"; case LIBRAW_FILE_UNSUPPORTED: return "Unsupported file format or not RAW file"; case LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE: return "Request for nonexisting image number"; case LIBRAW_OUT_OF_ORDER_CALL: return "Out of order call of libraw function"; case LIBRAW_NO_THUMBNAIL: return "No thumbnail in file"; case LIBRAW_UNSUPPORTED_THUMBNAIL: return "Unsupported thumbnail format"; case LIBRAW_INPUT_CLOSED: return "No input stream, or input stream closed"; case LIBRAW_UNSUFFICIENT_MEMORY: return "Unsufficient memory"; case LIBRAW_DATA_ERROR: return "Corrupted data or unexpected EOF"; case LIBRAW_IO_ERROR: return "Input/output error"; case LIBRAW_CANCELLED_BY_CALLBACK: return "Cancelled by user callback"; case LIBRAW_BAD_CROP: return "Bad crop box"; default: return "Unknown error code"; } } #ifdef __cplusplus } #endif #define Sigma_X3F 22 const double LibRaw_constants::xyz_rgb[3][3] = { {0.4124564, 0.3575761, 0.1804375}, {0.2126729, 0.7151522, 0.0721750}, {0.0193339, 0.1191920, 0.9503041}}; const float LibRaw_constants::d65_white[3] = {0.95047f, 1.0f, 1.08883f}; #define P1 imgdata.idata #define S imgdata.sizes #define O imgdata.params #define C imgdata.color #define T imgdata.thumbnail #define IO libraw_internal_data.internal_output_params #define ID libraw_internal_data.internal_data #define EXCEPTION_HANDLER(e) \ do \ { \ /* fprintf(stderr,"Exception %d caught\n",e);*/ \ switch (e) \ { \ case LIBRAW_EXCEPTION_ALLOC: \ recycle(); \ return LIBRAW_UNSUFFICIENT_MEMORY; \ case LIBRAW_EXCEPTION_DECODE_RAW: \ case LIBRAW_EXCEPTION_DECODE_JPEG: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_DECODE_JPEG2000: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_IO_EOF: \ case LIBRAW_EXCEPTION_IO_CORRUPT: \ recycle(); \ return LIBRAW_IO_ERROR; \ case LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK: \ recycle(); \ return LIBRAW_CANCELLED_BY_CALLBACK; \ case LIBRAW_EXCEPTION_BAD_CROP: \ recycle(); \ return LIBRAW_BAD_CROP; \ default: \ return LIBRAW_UNSPECIFIED_ERROR; \ } \ } while (0) const char *LibRaw::version() { return LIBRAW_VERSION_STR; } int LibRaw::versionNumber() { return LIBRAW_VERSION; } const char *LibRaw::strerror(int p) { return libraw_strerror(p); } unsigned LibRaw::capabilities() { unsigned ret = 0; #ifdef USE_RAWSPEED ret |= LIBRAW_CAPS_RAWSPEED; #endif #ifdef USE_DNGSDK ret |= LIBRAW_CAPS_DNGSDK; #endif return ret; } unsigned LibRaw::parse_custom_cameras(unsigned limit, libraw_custom_camera_t table[], char **list) { if (!list) return 0; unsigned index = 0; for (int i = 0; i < limit; i++) { if (!list[i]) break; if (strlen(list[i]) < 10) continue; char *string = (char *)malloc(strlen(list[i]) + 1); strcpy(string, list[i]); char *start = string; memset(&table[index], 0, sizeof(table[0])); for (int j = 0; start && j < 14; j++) { char *end = strchr(start, ','); if (end) { *end = 0; end++; } // move to next char while (isspace(*start) && *start) start++; // skip leading spaces? unsigned val = strtol(start, 0, 10); switch (j) { case 0: table[index].fsize = val; break; case 1: table[index].rw = val; break; case 2: table[index].rh = val; break; case 3: table[index].lm = val; break; case 4: table[index].tm = val; break; case 5: table[index].rm = val; break; case 6: table[index].bm = val; break; case 7: table[index].lf = val; break; case 8: table[index].cf = val; break; case 9: table[index].max = val; break; case 10: table[index].flags = val; break; case 11: strncpy(table[index].t_make, start, sizeof(table[index].t_make) - 1); break; case 12: strncpy(table[index].t_model, start, sizeof(table[index].t_model) - 1); break; case 13: table[index].offset = val; break; default: break; } start = end; } free(string); if (table[index].t_make[0]) index++; } return index; } void LibRaw::derror() { if (!libraw_internal_data.unpacker_data.data_error && libraw_internal_data.internal_data.input) { if (libraw_internal_data.internal_data.input->eof()) { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), -1); throw LIBRAW_EXCEPTION_IO_EOF; } else { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), libraw_internal_data.internal_data.input->tell()); // throw LIBRAW_EXCEPTION_IO_CORRUPT; } } libraw_internal_data.unpacker_data.data_error++; } void LibRaw::dcraw_clear_mem(libraw_processed_image_t *p) { if (p) ::free(p); } int LibRaw::is_sraw() { return load_raw == &LibRaw::canon_sraw_load_raw || load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::is_coolscan_nef() { return load_raw == &LibRaw::nikon_coolscan_load_raw; } int LibRaw::is_jpeg_thumb() { return thumb_load_raw == 0 && write_thumb == &LibRaw::jpeg_thumb; } int LibRaw::is_nikon_sraw() { return load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::sraw_midpoint() { if (load_raw == &LibRaw::canon_sraw_load_raw) return 8192; else if (load_raw == &LibRaw::nikon_load_sraw) return 2048; else return 0; } #ifdef USE_RAWSPEED using namespace RawSpeed; class CameraMetaDataLR : public CameraMetaData { public: CameraMetaDataLR() : CameraMetaData() {} CameraMetaDataLR(char *filename) : CameraMetaData(filename) {} CameraMetaDataLR(char *data, int sz); }; CameraMetaDataLR::CameraMetaDataLR(char *data, int sz) : CameraMetaData() { ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { ThrowCME("CameraMetaData:Could not initialize context."); } xmlResetLastError(); doc = xmlCtxtReadMemory(ctxt, data, sz, "", NULL, XML_PARSE_DTDVALID); if (doc == NULL) { ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s", ctxt->lastError.message); } if (ctxt->valid == 0) { if (ctxt->lastError.code == 0x5e) { // printf("CameraMetaData: Unable to locate DTD, attempting to ignore."); } else { ThrowCME("CameraMetaData: XML file does not validate. DTD Error was: %s", ctxt->lastError.message); } } xmlNodePtr cur; cur = xmlDocGetRootElement(doc); if (xmlStrcmp(cur->name, (const xmlChar *)"Cameras")) { ThrowCME("CameraMetaData: XML document of the wrong type, root node is not cameras."); return; } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"Camera"))) { Camera *camera = new Camera(doc, cur); addCamera(camera); // Create cameras for aliases. for (unsigned int i = 0; i < camera->aliases.size(); i++) { addCamera(new Camera(camera, i)); } } cur = cur->next; } if (doc) xmlFreeDoc(doc); doc = 0; if (ctxt) xmlFreeParserCtxt(ctxt); ctxt = 0; } #define RAWSPEED_DATA_COUNT (sizeof(_rawspeed_data_xml) / sizeof(_rawspeed_data_xml[0])) static CameraMetaDataLR *make_camera_metadata() { int len = 0, i; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { len += strlen(_rawspeed_data_xml[i]); } char *rawspeed_xml = (char *)calloc(len + 1, sizeof(_rawspeed_data_xml[0][0])); if (!rawspeed_xml) return NULL; int offt = 0; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { int ll = strlen(_rawspeed_data_xml[i]); if (offt + ll > len) break; memmove(rawspeed_xml + offt, _rawspeed_data_xml[i], ll); offt += ll; } rawspeed_xml[offt] = 0; CameraMetaDataLR *ret = NULL; try { ret = new CameraMetaDataLR(rawspeed_xml, offt); } catch (...) { // Mask all exceptions } free(rawspeed_xml); return ret; } #endif #define ZERO(a) memset(&a, 0, sizeof(a)) static void cleargps(libraw_gps_info_t *q) { for (int i = 0; i < 3; i++) q->latitude[i] = q->longtitude[i] = q->gpstimestamp[i] = 0.f; q->altitude = 0.f; q->altref = q->latref = q->longref = q->gpsstatus = q->gpsparsed = 0; } LibRaw::LibRaw(unsigned int flags) : memmgr(1024) { double aber[4] = {1, 1, 1, 1}; double gamm[6] = {0.45, 4.5, 0, 0, 0, 0}; unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX}; unsigned cropbox[4] = {0, 0, UINT_MAX, UINT_MAX}; #ifdef DCRAW_VERBOSE verbose = 1; #else verbose = 0; #endif ZERO(imgdata); cleargps(&imgdata.other.parsed_gps); ZERO(libraw_internal_data); ZERO(callbacks); _rawspeed_camerameta = _rawspeed_decoder = NULL; dnghost = NULL; _x3f_data = NULL; #ifdef USE_RAWSPEED CameraMetaDataLR *camerameta = make_camera_metadata(); // May be NULL in case of exception in make_camera_metadata() _rawspeed_camerameta = static_cast<void *>(camerameta); #endif callbacks.mem_cb = (flags & LIBRAW_OPIONS_NO_MEMERR_CALLBACK) ? NULL : &default_memory_callback; callbacks.data_cb = (flags & LIBRAW_OPIONS_NO_DATAERR_CALLBACK) ? NULL : &default_data_callback; callbacks.exif_cb = NULL; // no default callback callbacks.pre_identify_cb = NULL; callbacks.post_identify_cb = NULL; callbacks.pre_subtractblack_cb = callbacks.pre_scalecolors_cb = callbacks.pre_preinterpolate_cb = callbacks.pre_interpolate_cb = callbacks.interpolate_bayer_cb = callbacks.interpolate_xtrans_cb = callbacks.post_interpolate_cb = callbacks.pre_converttorgb_cb = callbacks.post_converttorgb_cb = NULL; memmove(&imgdata.params.aber, &aber, sizeof(aber)); memmove(&imgdata.params.gamm, &gamm, sizeof(gamm)); memmove(&imgdata.params.greybox, &greybox, sizeof(greybox)); memmove(&imgdata.params.cropbox, &cropbox, sizeof(cropbox)); imgdata.params.bright = 1; imgdata.params.use_camera_matrix = 1; imgdata.params.user_flip = -1; imgdata.params.user_black = -1; imgdata.params.user_cblack[0] = imgdata.params.user_cblack[1] = imgdata.params.user_cblack[2] = imgdata.params.user_cblack[3] = -1000001; imgdata.params.user_sat = -1; imgdata.params.user_qual = -1; imgdata.params.output_color = 1; imgdata.params.output_bps = 8; imgdata.params.use_fuji_rotate = 1; imgdata.params.exp_shift = 1.0; imgdata.params.auto_bright_thr = LIBRAW_DEFAULT_AUTO_BRIGHTNESS_THRESHOLD; imgdata.params.adjust_maximum_thr = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; imgdata.params.use_rawspeed = 1; imgdata.params.use_dngsdk = LIBRAW_DNG_DEFAULT; imgdata.params.no_auto_scale = 0; imgdata.params.no_interpolation = 0; imgdata.params.raw_processing_options = LIBRAW_PROCESSING_DP2Q_INTERPOLATERG | LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF | LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT; imgdata.params.sony_arw2_posterization_thr = 0; imgdata.params.green_matching = 0; imgdata.params.custom_camera_strings = 0; imgdata.params.coolscan_nef_gamma = 1.0f; imgdata.parent_class = this; imgdata.progress_flags = 0; imgdata.color.baseline_exposure = -999.f; _exitflag = 0; tls = new LibRaw_TLS; tls->init(); } int LibRaw::set_rawspeed_camerafile(char *filename) { #ifdef USE_RAWSPEED try { CameraMetaDataLR *camerameta = new CameraMetaDataLR(filename); if (_rawspeed_camerameta) { CameraMetaDataLR *d = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete d; } _rawspeed_camerameta = static_cast<void *>(camerameta); } catch (...) { // just return error code return -1; } #endif return 0; } LibRaw::~LibRaw() { recycle(); delete tls; #ifdef USE_RAWSPEED if (_rawspeed_camerameta) { CameraMetaDataLR *cmeta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete cmeta; _rawspeed_camerameta = NULL; } #endif } void *LibRaw::malloc(size_t t) { void *p = memmgr.malloc(t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::realloc(void *q, size_t t) { void *p = memmgr.realloc(q, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::calloc(size_t n, size_t t) { void *p = memmgr.calloc(n, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void LibRaw::free(void *p) { memmgr.free(p); } void LibRaw::recycle_datastream() { if (libraw_internal_data.internal_data.input && libraw_internal_data.internal_data.input_internal) { delete libraw_internal_data.internal_data.input; libraw_internal_data.internal_data.input = NULL; } libraw_internal_data.internal_data.input_internal = 0; } void x3f_clear(void *); void LibRaw::recycle() { recycle_datastream(); #define FREE(a) \ do \ { \ if (a) \ { \ free(a); \ a = NULL; \ } \ } while (0) FREE(imgdata.image); FREE(imgdata.thumbnail.thumb); FREE(libraw_internal_data.internal_data.meta_data); FREE(libraw_internal_data.output_data.histogram); FREE(libraw_internal_data.output_data.oprof); FREE(imgdata.color.profile); FREE(imgdata.rawdata.ph1_cblack); FREE(imgdata.rawdata.ph1_rblack); FREE(imgdata.rawdata.raw_alloc); FREE(imgdata.idata.xmpdata); #undef FREE ZERO(imgdata.sizes); imgdata.sizes.raw_crop.cleft = 0xffff; imgdata.sizes.raw_crop.ctop = 0xffff; ZERO(imgdata.idata); ZERO(imgdata.makernotes); ZERO(imgdata.color); ZERO(imgdata.other); ZERO(imgdata.thumbnail); ZERO(imgdata.rawdata); imgdata.makernotes.olympus.OlympusCropID = -1; imgdata.makernotes.sony.raw_crop.cleft = 0xffff; imgdata.makernotes.sony.raw_crop.ctop = 0xffff; cleargps(&imgdata.other.parsed_gps); imgdata.color.baseline_exposure = -999.f; imgdata.makernotes.fuji.FujiExpoMidPointShift = -999.f; imgdata.makernotes.fuji.FujiDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiFilmMode = 0xffff; imgdata.makernotes.fuji.FujiDynamicRangeSetting = 0xffff; imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiAutoDynamicRange = 0xffff; imgdata.makernotes.fuji.FocusMode = 0xffff; imgdata.makernotes.fuji.AFMode = 0xffff; imgdata.makernotes.fuji.FocusPixel[0] = imgdata.makernotes.fuji.FocusPixel[1] = 0xffff; imgdata.makernotes.fuji.ImageStabilization[0] = imgdata.makernotes.fuji.ImageStabilization[1] = imgdata.makernotes.fuji.ImageStabilization[2] = 0xffff; imgdata.makernotes.sony.SonyCameraType = 0xffff; imgdata.makernotes.sony.real_iso_offset = 0xffff; imgdata.makernotes.sony.ImageCount3_offset = 0xffff; imgdata.makernotes.sony.ElectronicFrontCurtainShutter = 0xffff; imgdata.makernotes.kodak.BlackLevelTop = 0xffff; imgdata.makernotes.kodak.BlackLevelBottom = 0xffff; imgdata.color.dng_color[0].illuminant = imgdata.color.dng_color[1].illuminant = 0xffff; for (int i = 0; i < 4; i++) imgdata.color.dng_levels.analogbalance[i] = 1.0f; ZERO(libraw_internal_data); ZERO(imgdata.lens); imgdata.lens.makernotes.CanonFocalUnits = 1; imgdata.lens.makernotes.LensID = 0xffffffffffffffffULL; ZERO(imgdata.shootinginfo); imgdata.shootinginfo.DriveMode = -1; imgdata.shootinginfo.FocusMode = -1; imgdata.shootinginfo.MeteringMode = -1; imgdata.shootinginfo.AFPoint = -1; imgdata.shootinginfo.ExposureMode = -1; imgdata.shootinginfo.ImageStabilization = -1; _exitflag = 0; #ifdef USE_RAWSPEED if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); delete d; } _rawspeed_decoder = 0; #endif if (_x3f_data) { x3f_clear(_x3f_data); _x3f_data = 0; } memmgr.cleanup(); imgdata.thumbnail.tformat = LIBRAW_THUMBNAIL_UNKNOWN; imgdata.progress_flags = 0; load_raw = thumb_load_raw = 0; tls->init(); } const char *LibRaw::unpack_function_name() { libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); return decoder_info.decoder_name; } int LibRaw::get_decoder_info(libraw_decoder_info_t *d_info) { if (!d_info) return LIBRAW_UNSPECIFIED_ERROR; d_info->decoder_name = 0; d_info->decoder_flags = 0; if (!load_raw) return LIBRAW_OUT_OF_ORDER_CALL; int rawdata = (imgdata.idata.filters || P1.colors == 1); // dcraw.c names order if (load_raw == &LibRaw::android_tight_load_raw) { d_info->decoder_name = "android_tight_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::android_loose_load_raw) { d_info->decoder_name = "android_loose_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_600_load_raw) { d_info->decoder_name = "canon_600_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::fuji_compressed_load_raw) { d_info->decoder_name = "fuji_compressed_load_raw()"; } else if (load_raw == &LibRaw::fuji_14bit_load_raw) { d_info->decoder_name = "fuji_14bit_load_raw()"; } else if (load_raw == &LibRaw::canon_load_raw) { d_info->decoder_name = "canon_load_raw()"; } else if (load_raw == &LibRaw::lossless_jpeg_load_raw) { d_info->decoder_name = "lossless_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::canon_sraw_load_raw) { d_info->decoder_name = "canon_sraw_load_raw()"; // d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::lossless_dng_load_raw) { d_info->decoder_name = "lossless_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::packed_dng_load_raw) { d_info->decoder_name = "packed_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::pentax_load_raw) { d_info->decoder_name = "pentax_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_load_raw) { d_info->decoder_name = "nikon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_coolscan_load_raw) { d_info->decoder_name = "nikon_coolscan_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_load_sraw) { d_info->decoder_name = "nikon_load_sraw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_yuv_load_raw) { d_info->decoder_name = "nikon_load_yuv_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::rollei_load_raw) { // UNTESTED d_info->decoder_name = "rollei_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::phase_one_load_raw) { d_info->decoder_name = "phase_one_load_raw()"; } else if (load_raw == &LibRaw::phase_one_load_raw_c) { d_info->decoder_name = "phase_one_load_raw_c()"; } else if (load_raw == &LibRaw::hasselblad_load_raw) { d_info->decoder_name = "hasselblad_load_raw()"; } else if (load_raw == &LibRaw::leaf_hdr_load_raw) { d_info->decoder_name = "leaf_hdr_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw) { d_info->decoder_name = "unpacked_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw_reversed) { d_info->decoder_name = "unpacked_load_raw_reversed()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sinar_4shot_load_raw) { // UNTESTED d_info->decoder_name = "sinar_4shot_load_raw()"; } else if (load_raw == &LibRaw::imacon_full_load_raw) { d_info->decoder_name = "imacon_full_load_raw()"; } else if (load_raw == &LibRaw::hasselblad_full_load_raw) { d_info->decoder_name = "hasselblad_full_load_raw()"; } else if (load_raw == &LibRaw::packed_load_raw) { d_info->decoder_name = "packed_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::broadcom_load_raw) { // UNTESTED d_info->decoder_name = "broadcom_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nokia_load_raw) { // UNTESTED d_info->decoder_name = "nokia_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_rmf_load_raw) { // UNTESTED d_info->decoder_name = "canon_rmf_load_raw()"; } else if (load_raw == &LibRaw::panasonic_load_raw) { d_info->decoder_name = "panasonic_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::olympus_load_raw) { d_info->decoder_name = "olympus_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::minolta_rd175_load_raw) { // UNTESTED d_info->decoder_name = "minolta_rd175_load_raw()"; } else if (load_raw == &LibRaw::quicktake_100_load_raw) { // UNTESTED d_info->decoder_name = "quicktake_100_load_raw()"; } else if (load_raw == &LibRaw::kodak_radc_load_raw) { d_info->decoder_name = "kodak_radc_load_raw()"; } else if (load_raw == &LibRaw::kodak_jpeg_load_raw) { // UNTESTED + RBAYER d_info->decoder_name = "kodak_jpeg_load_raw()"; } else if (load_raw == &LibRaw::lossy_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossy_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_dc120_load_raw) { d_info->decoder_name = "kodak_dc120_load_raw()"; } else if (load_raw == &LibRaw::eight_bit_load_raw) { d_info->decoder_name = "eight_bit_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c330_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c603_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_262_load_raw) { d_info->decoder_name = "kodak_262_load_raw()"; // UNTESTED! d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_65000_load_raw) { d_info->decoder_name = "kodak_65000_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { // UNTESTED d_info->decoder_name = "kodak_ycbcr_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_rgb_load_raw) { // UNTESTED d_info->decoder_name = "kodak_rgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sony_load_raw) { d_info->decoder_name = "sony_load_raw()"; } else if (load_raw == &LibRaw::sony_arw_load_raw) { d_info->decoder_name = "sony_arw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::sony_arw2_load_raw) { d_info->decoder_name = "sony_arw2_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_SONYARW2; } else if (load_raw == &LibRaw::sony_arq_load_raw) { d_info->decoder_name = "sony_arq_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::samsung_load_raw) { d_info->decoder_name = "samsung_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::samsung2_load_raw) { d_info->decoder_name = "samsung2_load_raw()"; } else if (load_raw == &LibRaw::samsung3_load_raw) { d_info->decoder_name = "samsung3_load_raw()"; } else if (load_raw == &LibRaw::smal_v6_load_raw) { // UNTESTED d_info->decoder_name = "smal_v6_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::smal_v9_load_raw) { // UNTESTED d_info->decoder_name = "smal_v9_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::redcine_load_raw) { d_info->decoder_name = "redcine_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::x3f_load_raw) { d_info->decoder_name = "x3f_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC | LIBRAW_DECODER_FIXEDMAXC | LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::pentax_4shot_load_raw) { d_info->decoder_name = "pentax_4shot_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::deflate_dng_load_raw) { d_info->decoder_name = "deflate_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::nikon_load_striped_packed_raw) { d_info->decoder_name = "nikon_load_striped_packed_raw()"; } else { d_info->decoder_name = "Unknown unpack function"; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; } return LIBRAW_SUCCESS; } int LibRaw::adjust_maximum() { ushort real_max; float auto_threshold; if (O.adjust_maximum_thr < 0.00001) return LIBRAW_SUCCESS; else if (O.adjust_maximum_thr > 0.99999) auto_threshold = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; else auto_threshold = O.adjust_maximum_thr; real_max = C.data_maximum; if (real_max > 0 && real_max < C.maximum && real_max > C.maximum * auto_threshold) { C.maximum = real_max; } return LIBRAW_SUCCESS; } void LibRaw::merror(void *ptr, const char *where) { if (ptr) return; if (callbacks.mem_cb) (*callbacks.mem_cb)( callbacks.memcb_data, libraw_internal_data.internal_data.input ? libraw_internal_data.internal_data.input->fname() : NULL, where); throw LIBRAW_EXCEPTION_ALLOC; } int LibRaw::open_file(const char *fname, INT64 max_buf_size) { #ifndef WIN32 struct stat st; if (stat(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #else struct _stati64 st; if (_stati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #endif LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) int LibRaw::open_file(const wchar_t *fname, INT64 max_buf_size) { struct _stati64 st; if (_wstati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #endif int LibRaw::open_buffer(void *buffer, size_t size) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, size); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } int LibRaw::open_bayer(unsigned char *buffer, unsigned datalen, ushort _raw_width, ushort _raw_height, ushort _left_margin, ushort _top_margin, ushort _right_margin, ushort _bottom_margin, unsigned char procflags, unsigned char bayer_pattern, unsigned unused_bits, unsigned otherflags, unsigned black_level) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, datalen); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); // From identify initdata(); strcpy(imgdata.idata.make, "BayerDump"); snprintf(imgdata.idata.model, sizeof(imgdata.idata.model) - 1, "%u x %u pixels", _raw_width, _raw_height); S.flip = procflags >> 2; libraw_internal_data.internal_output_params.zero_is_bad = procflags & 2; libraw_internal_data.unpacker_data.data_offset = 0; S.raw_width = _raw_width; S.raw_height = _raw_height; S.left_margin = _left_margin; S.top_margin = _top_margin; S.width = S.raw_width - S.left_margin - _right_margin; S.height = S.raw_height - S.top_margin - _bottom_margin; imgdata.idata.filters = 0x1010101 * bayer_pattern; imgdata.idata.colors = 4 - !((imgdata.idata.filters & imgdata.idata.filters >> 1) & 0x5555); libraw_internal_data.unpacker_data.load_flags = otherflags; switch (libraw_internal_data.unpacker_data.tiff_bps = (datalen)*8 / (S.raw_width * S.raw_height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((datalen) / S.raw_height * 3 >= S.raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (libraw_internal_data.unpacker_data.load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: libraw_internal_data.unpacker_data.load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: libraw_internal_data.unpacker_data.order = 0x4949 | 0x404 * (libraw_internal_data.unpacker_data.load_flags & 1); libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags >> 4; libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags = libraw_internal_data.unpacker_data.load_flags >> 1 & 7; load_raw = &CLASS unpacked_load_raw; } C.maximum = (1 << libraw_internal_data.unpacker_data.tiff_bps) - (1 << unused_bits); C.black = black_level; S.iwidth = S.width; S.iheight = S.height; imgdata.idata.colors = 3; imgdata.idata.filters |= ((imgdata.idata.filters >> 2 & 0x22222222) | (imgdata.idata.filters << 2 & 0x88888888)) & imgdata.idata.filters << 1; imgdata.idata.raw_count = 1; for (int i = 0; i < 4; i++) imgdata.color.pre_mul[i] = 1.0; strcpy(imgdata.idata.cdesc, "RGBG"); ID.input_internal = 1; SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); return LIBRAW_SUCCESS; } #ifdef USE_ZLIB inline unsigned int __DNG_HalfToFloat(ushort halfValue) { int sign = (halfValue >> 15) & 0x00000001; int exponent = (halfValue >> 10) & 0x0000001f; int mantissa = halfValue & 0x000003ff; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00000400)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00000400; } } else if (exponent == 31) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x1eL + 127 - 15) << 23) | (0x3ffL << 13)); } else { return 0; } } exponent += (127 - 15); mantissa <<= 13; return (unsigned int)((sign << 31) | (exponent << 23) | mantissa); } inline unsigned int __DNG_FP24ToFloat(const unsigned char *input) { int sign = (input[0] >> 7) & 0x01; int exponent = (input[0]) & 0x7F; int mantissa = (((int)input[1]) << 8) | input[2]; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00010000)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00010000; } } else if (exponent == 127) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x7eL + 128 - 64) << 23) | (0xffffL << 7)); } else { // Nan -- Just set to zero. return 0; } } exponent += (128 - 64); mantissa <<= 7; return (uint32_t)((sign << 31) | (exponent << 23) | mantissa); } inline void DecodeDeltaBytes(unsigned char *bytePtr, int cols, int channels) { if (channels == 1) { unsigned char b0 = bytePtr[0]; bytePtr += 1; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; bytePtr[0] = b0; bytePtr += 1; } } else if (channels == 3) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; bytePtr += 3; for (int col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr += 3; } } else if (channels == 4) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; unsigned char b3 = bytePtr[3]; bytePtr += 4; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; b3 += bytePtr[3]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr[3] = b3; bytePtr += 4; } } else { for (int col = 1; col < cols; ++col) { for (int chan = 0; chan < channels; ++chan) { bytePtr[chan + channels] += bytePtr[chan]; } bytePtr += channels; } } } static void DecodeFPDelta(unsigned char *input, unsigned char *output, int cols, int channels, int bytesPerSample) { DecodeDeltaBytes(input, cols * bytesPerSample, channels); int32_t rowIncrement = cols * channels; if (bytesPerSample == 2) { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; #else const unsigned char *input1 = input; const unsigned char *input0 = input + rowIncrement; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output += 2; } } else if (bytesPerSample == 3) { const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output += 3; } } else { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; const unsigned char *input3 = input + rowIncrement * 3; #else const unsigned char *input3 = input; const unsigned char *input2 = input + rowIncrement; const unsigned char *input1 = input + rowIncrement * 2; const unsigned char *input0 = input + rowIncrement * 3; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output[3] = input3[col]; output += 4; } } } static float expandFloats(unsigned char *dst, int tileWidth, int bytesps) { float max = 0.f; if (bytesps == 2) { uint16_t *dst16 = (ushort *)dst; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index) { dst32[index] = __DNG_HalfToFloat(dst16[index]); max = MAX(max, f32[index]); } } else if (bytesps == 3) { uint8_t *dst8 = ((unsigned char *)dst) + (tileWidth - 1) * 3; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index, dst8 -= 3) { dst32[index] = __DNG_FP24ToFloat(dst8); max = MAX(max, f32[index]); } } else if (bytesps == 4) { float *f32 = (float *)dst; for (int index = 0; index < tileWidth; index++) max = MAX(max, f32[index]); } return max; } void LibRaw::deflate_dng_load_raw() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) { throw LIBRAW_EXCEPTION_DECODE_RAW; } float *float_raw_image = 0; float max = 0.f; if (ifd->samples != 1 && ifd->samples != 3 && ifd->samples != 4) throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported if (libraw_internal_data.unpacker_data.tiff_samples != ifd->samples) throw LIBRAW_EXCEPTION_DECODE_RAW; // Wrong IFD size_t tilesH = (imgdata.sizes.raw_width + libraw_internal_data.unpacker_data.tile_width - 1) / libraw_internal_data.unpacker_data.tile_width; size_t tilesV = (imgdata.sizes.raw_height + libraw_internal_data.unpacker_data.tile_length - 1) / libraw_internal_data.unpacker_data.tile_length; size_t tileCnt = tilesH * tilesV; if (ifd->sample_format == 3) { // Floating point data float_raw_image = (float *)calloc(tileCnt * libraw_internal_data.unpacker_data.tile_length * libraw_internal_data.unpacker_data.tile_width * ifd->samples, sizeof(float)); // imgdata.color.maximum = 65535; // imgdata.color.black = 0; // memset(imgdata.color.cblack,0,sizeof(imgdata.color.cblack)); } else throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported int xFactor; switch (ifd->predictor) { case 3: default: xFactor = 1; break; case 34894: xFactor = 2; break; case 34895: xFactor = 4; break; } if (libraw_internal_data.unpacker_data.tile_length < INT_MAX) { if (tileCnt < 1 || tileCnt > 1000000) throw LIBRAW_EXCEPTION_DECODE_RAW; size_t *tOffsets = (size_t *)malloc(tileCnt * sizeof(size_t)); for (int t = 0; t < tileCnt; ++t) tOffsets[t] = get4(); size_t *tBytes = (size_t *)malloc(tileCnt * sizeof(size_t)); unsigned long maxBytesInTile = 0; if (tileCnt == 1) tBytes[0] = maxBytesInTile = ifd->bytes; else { libraw_internal_data.internal_data.input->seek(ifd->bytes, SEEK_SET); for (size_t t = 0; t < tileCnt; ++t) { tBytes[t] = get4(); maxBytesInTile = MAX(maxBytesInTile, tBytes[t]); } } unsigned tilePixels = libraw_internal_data.unpacker_data.tile_width * libraw_internal_data.unpacker_data.tile_length; unsigned pixelSize = sizeof(float) * ifd->samples; unsigned tileBytes = tilePixels * pixelSize; unsigned tileRowBytes = libraw_internal_data.unpacker_data.tile_width * pixelSize; unsigned char *cBuffer = (unsigned char *)malloc(maxBytesInTile); unsigned char *uBuffer = (unsigned char *)malloc(tileBytes + tileRowBytes); // extra row for decoding for (size_t y = 0, t = 0; y < imgdata.sizes.raw_height; y += libraw_internal_data.unpacker_data.tile_length) { for (size_t x = 0; x < imgdata.sizes.raw_width; x += libraw_internal_data.unpacker_data.tile_width, ++t) { libraw_internal_data.internal_data.input->seek(tOffsets[t], SEEK_SET); libraw_internal_data.internal_data.input->read(cBuffer, 1, tBytes[t]); unsigned long dstLen = tileBytes; int err = uncompress(uBuffer + tileRowBytes, &dstLen, cBuffer, tBytes[t]); if (err != Z_OK) { free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); throw LIBRAW_EXCEPTION_DECODE_RAW; return; } else { int bytesps = ifd->bps >> 3; size_t rowsInTile = y + libraw_internal_data.unpacker_data.tile_length > imgdata.sizes.raw_height ? imgdata.sizes.raw_height - y : libraw_internal_data.unpacker_data.tile_length; size_t colsInTile = x + libraw_internal_data.unpacker_data.tile_width > imgdata.sizes.raw_width ? imgdata.sizes.raw_width - x : libraw_internal_data.unpacker_data.tile_width; for (size_t row = 0; row < rowsInTile; ++row) // do not process full tile if not needed { unsigned char *dst = uBuffer + row * libraw_internal_data.unpacker_data.tile_width * bytesps * ifd->samples; unsigned char *src = dst + tileRowBytes; DecodeFPDelta(src, dst, libraw_internal_data.unpacker_data.tile_width / xFactor, ifd->samples * xFactor, bytesps); float lmax = expandFloats(dst, libraw_internal_data.unpacker_data.tile_width * ifd->samples, bytesps); max = MAX(max, lmax); unsigned char *dst2 = (unsigned char *)&float_raw_image[((y + row) * imgdata.sizes.raw_width + x) * ifd->samples]; memmove(dst2, dst, colsInTile * ifd->samples * sizeof(float)); } } } } free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); } imgdata.color.fmaximum = max; // Set fields according to data format imgdata.rawdata.raw_alloc = float_raw_image; if (ifd->samples == 1) { imgdata.rawdata.float_image = float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 4; } else if (ifd->samples == 3) { imgdata.rawdata.float3_image = (float(*)[3])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 12; } else if (ifd->samples == 4) { imgdata.rawdata.float4_image = (float(*)[4])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 16; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT) convertFloatToInt(); // with default settings } #else void LibRaw::deflate_dng_load_raw() { throw LIBRAW_EXCEPTION_DECODE_RAW; } #endif int LibRaw::is_floating_point() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) return 0; return ifd->sample_format == 3; } int LibRaw::have_fpdata() { return imgdata.rawdata.float_image || imgdata.rawdata.float3_image || imgdata.rawdata.float4_image; } void LibRaw::convertFloatToInt(float dmin /* =4096.f */, float dmax /* =32767.f */, float dtarget /*= 16383.f */) { int samples = 0; float *data = 0; if (imgdata.rawdata.float_image) { samples = 1; data = imgdata.rawdata.float_image; } else if (imgdata.rawdata.float3_image) { samples = 3; data = (float *)imgdata.rawdata.float3_image; } else if (imgdata.rawdata.float4_image) { samples = 4; data = (float *)imgdata.rawdata.float4_image; } else return; ushort *raw_alloc = (ushort *)malloc(imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples * sizeof(ushort)); float tmax = MAX(imgdata.color.maximum, 1); float datamax = imgdata.color.fmaximum; tmax = MAX(tmax, datamax); tmax = MAX(tmax, 1.f); float multip = 1.f; if (tmax < dmin || tmax > dmax) { imgdata.rawdata.color.fnorm = imgdata.color.fnorm = multip = dtarget / tmax; imgdata.rawdata.color.maximum = imgdata.color.maximum = dtarget; imgdata.rawdata.color.black = imgdata.color.black = (float)imgdata.color.black * multip; for (int i = 0; i < sizeof(imgdata.color.cblack) / sizeof(imgdata.color.cblack[0]); i++) if (i != 4 && i != 5) imgdata.rawdata.color.cblack[i] = imgdata.color.cblack[i] = (float)imgdata.color.cblack[i] * multip; } else imgdata.rawdata.color.fnorm = imgdata.color.fnorm = 0.f; for (size_t i = 0; i < imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples; ++i) { float val = MAX(data[i], 0.f); raw_alloc[i] = (ushort)(val * multip); } if (samples == 1) { imgdata.rawdata.raw_alloc = imgdata.rawdata.raw_image = raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 2; } else if (samples == 3) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color3_image = (ushort(*)[3])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; } else if (samples == 4) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = (ushort(*)[4])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; } free(data); // remove old allocation imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; imgdata.rawdata.float4_image = 0; } void LibRaw::sony_arq_load_raw() { int row, col; read_shorts(imgdata.rawdata.raw_image, imgdata.sizes.raw_width * imgdata.sizes.raw_height * 4); for (row = 0; row < imgdata.sizes.raw_height; row++) { unsigned short(*rowp)[4] = (unsigned short(*)[4]) & imgdata.rawdata.raw_image[row * imgdata.sizes.raw_width * 4]; for (col = 0; col < imgdata.sizes.raw_width; col++) { unsigned short g2 = rowp[col][2]; rowp[col][2] = rowp[col][3]; rowp[col][3] = g2; if (((unsigned)(row - imgdata.sizes.top_margin) < imgdata.sizes.height) && ((unsigned)(col - imgdata.sizes.left_margin) < imgdata.sizes.width) && (MAX(MAX(rowp[col][0], rowp[col][1]), MAX(rowp[col][2], rowp[col][3])) > imgdata.color.maximum)) derror(); } } } void LibRaw::pentax_4shot_load_raw() { ushort *plane = (ushort *)malloc(imgdata.sizes.raw_width * imgdata.sizes.raw_height * sizeof(ushort)); int alloc_sz = imgdata.sizes.raw_width * (imgdata.sizes.raw_height + 16) * 4 * sizeof(ushort); ushort(*result)[4] = (ushort(*)[4])malloc(alloc_sz); struct movement_t { int row, col; } _move[4] = { {1, 1}, {0, 1}, {0, 0}, {1, 0}, }; int tidx = 0; for (int i = 0; i < 4; i++) { int move_row, move_col; if (imgdata.params.p4shot_order[i] >= '0' && imgdata.params.p4shot_order[i] <= '3') { move_row = (imgdata.params.p4shot_order[i] - '0' & 2) ? 1 : 0; move_col = (imgdata.params.p4shot_order[i] - '0' & 1) ? 1 : 0; } else { move_row = _move[i].row; move_col = _move[i].col; } for (; tidx < 16; tidx++) if (tiff_ifd[tidx].t_width == imgdata.sizes.raw_width && tiff_ifd[tidx].t_height == imgdata.sizes.raw_height && tiff_ifd[tidx].bps > 8 && tiff_ifd[tidx].samples == 1) break; if (tidx >= 16) break; imgdata.rawdata.raw_image = plane; ID.input->seek(tiff_ifd[tidx].offset, SEEK_SET); imgdata.idata.filters = 0xb4b4b4b4; libraw_internal_data.unpacker_data.data_offset = tiff_ifd[tidx].offset; (this->*pentax_component_load_raw)(); for (int row = 0; row < imgdata.sizes.raw_height - move_row; row++) { int colors[2]; for (int c = 0; c < 2; c++) colors[c] = COLOR(row, c); ushort *srcrow = &plane[imgdata.sizes.raw_width * row]; ushort(*dstrow)[4] = &result[(imgdata.sizes.raw_width) * (row + move_row) + move_col]; for (int col = 0; col < imgdata.sizes.raw_width - move_col; col++) dstrow[col][colors[col % 2]] = srcrow[col]; } tidx++; } // assign things back: imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; imgdata.idata.filters = 0; imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = result; free(plane); imgdata.rawdata.raw_image = 0; } void LibRaw::hasselblad_full_load_raw() { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) { read_shorts(&imgdata.image[row * S.width + col][2], 1); // B read_shorts(&imgdata.image[row * S.width + col][1], 1); // G read_shorts(&imgdata.image[row * S.width + col][0], 1); // R } } static inline void unpack7bytesto4x16(unsigned char *src, unsigned short *dest) { dest[0] = (src[0] << 6) | (src[1] >> 2); dest[1] = ((src[1] & 0x3) << 12) | (src[2] << 4) | (src[3] >> 4); dest[2] = (src[3] & 0xf) << 10 | (src[4] << 2) | (src[5] >> 6); dest[3] = ((src[5] & 0x3f) << 8) | src[6]; } static inline void unpack28bytesto16x16ns(unsigned char *src, unsigned short *dest) { dest[0] = (src[3] << 6) | (src[2] >> 2); dest[1] = ((src[2] & 0x3) << 12) | (src[1] << 4) | (src[0] >> 4); dest[2] = (src[0] & 0xf) << 10 | (src[7] << 2) | (src[6] >> 6); dest[3] = ((src[6] & 0x3f) << 8) | src[5]; dest[4] = (src[4] << 6) | (src[11] >> 2); dest[5] = ((src[11] & 0x3) << 12) | (src[10] << 4) | (src[9] >> 4); dest[6] = (src[9] & 0xf) << 10 | (src[8] << 2) | (src[15] >> 6); dest[7] = ((src[15] & 0x3f) << 8) | src[14]; dest[8] = (src[13] << 6) | (src[12] >> 2); dest[9] = ((src[12] & 0x3) << 12) | (src[19] << 4) | (src[18] >> 4); dest[10] = (src[18] & 0xf) << 10 | (src[17] << 2) | (src[16] >> 6); dest[11] = ((src[16] & 0x3f) << 8) | src[23]; dest[12] = (src[22] << 6) | (src[21] >> 2); dest[13] = ((src[21] & 0x3) << 12) | (src[20] << 4) | (src[27] >> 4); dest[14] = (src[27] & 0xf) << 10 | (src[26] << 2) | (src[25] >> 6); dest[15] = ((src[25] & 0x3f) << 8) | src[24]; } #define swab32(x) \ ((unsigned int)((((unsigned int)(x) & (unsigned int)0x000000ffUL) << 24) | \ (((unsigned int)(x) & (unsigned int)0x0000ff00UL) << 8) | \ (((unsigned int)(x) & (unsigned int)0x00ff0000UL) >> 8) | \ (((unsigned int)(x) & (unsigned int)0xff000000UL) >> 24))) static inline void swab32arr(unsigned *arr, unsigned len) { for (unsigned i = 0; i < len; i++) arr[i] = swab32(arr[i]); } #undef swab32 void LibRaw::fuji_14bit_load_raw() { const unsigned linelen = S.raw_width * 7 / 4; const unsigned pitch = S.raw_pitch ? S.raw_pitch / 2 : S.raw_width; unsigned char *buf = (unsigned char *)malloc(linelen); merror(buf, "fuji_14bit_load_raw()"); for (int row = 0; row < S.raw_height; row++) { unsigned bytesread = libraw_internal_data.internal_data.input->read(buf, 1, linelen); unsigned short *dest = &imgdata.rawdata.raw_image[pitch * row]; if (bytesread % 28) { swab32arr((unsigned *)buf, bytesread / 4); for (int sp = 0, dp = 0; dp < pitch - 3 && sp < linelen - 6 && sp < bytesread - 6; sp += 7, dp += 4) unpack7bytesto4x16(buf + sp, dest + dp); } else for (int sp = 0, dp = 0; dp < pitch - 15 && sp < linelen - 27 && sp < bytesread - 27; sp += 28, dp += 16) unpack28bytesto16x16ns(buf + sp, dest + dp); } free(buf); } void LibRaw::nikon_load_striped_packed_raw() { int vbits = 0, bwide, rbits, bite, row, col, val, i; UINT64 bitbuf = 0; unsigned load_flags = 24; // libraw_internal_data.unpacker_data.load_flags; unsigned tiff_bps = libraw_internal_data.unpacker_data.tiff_bps; int tiff_compress = libraw_internal_data.unpacker_data.tiff_compress; struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) throw LIBRAW_EXCEPTION_DECODE_RAW; if (!ifd->rows_per_strip || !ifd->strip_offsets_count) return; // not unpacked int stripcnt = 0; bwide = S.raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - S.raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); for (row = 0; row < S.raw_height; row++) { checkCancel(); if (!(row % ifd->rows_per_strip)) { if (stripcnt >= ifd->strip_offsets_count) return; // run out of data libraw_internal_data.internal_data.input->seek(ifd->strip_offsets[stripcnt], SEEK_SET); stripcnt++; } for (col = 0; col < S.raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(libraw_internal_data.internal_data.input->get_char() << i); } imgdata.rawdata.raw_image[(row)*S.raw_width + (col)] = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); } vbits -= rbits; } } struct foveon_data_t { const char *make; const char *model; const int raw_width, raw_height; const int white; const int left_margin, top_margin; const int width, height; } foveon_data[] = { {"Sigma", "SD9", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD9", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD10", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD10", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD14", 2688, 1792, 14000, 18, 12, 2651, 1767}, {"Sigma", "SD14", 2688, 896, 14000, 18, 6, 2651, 883}, // 2/3 {"Sigma", "SD14", 1344, 896, 14000, 9, 6, 1326, 883}, // 1/2 {"Sigma", "SD15", 2688, 1792, 2900, 18, 12, 2651, 1767}, {"Sigma", "SD15", 2688, 896, 2900, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "SD15", 1344, 896, 2900, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1", 2688, 1792, 2100, 18, 12, 2651, 1767}, {"Sigma", "DP1", 2688, 896, 2100, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "DP1", 1344, 896, 2100, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1S", 2688, 1792, 2200, 18, 12, 2651, 1767}, {"Sigma", "DP1S", 2688, 896, 2200, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1S", 1344, 896, 2200, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP1X", 2688, 1792, 3560, 18, 12, 2651, 1767}, {"Sigma", "DP1X", 2688, 896, 3560, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1X", 1344, 896, 3560, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2", 2688, 1792, 2326, 13, 16, 2651, 1767}, {"Sigma", "DP2", 2688, 896, 2326, 13, 8, 2651, 883}, // 2/3 ?? {"Sigma", "DP2", 1344, 896, 2326, 7, 8, 1325, 883}, // 1/2 ?? {"Sigma", "DP2S", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2S", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2S", 1344, 896, 2300, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2X", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2X", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2X", 1344, 896, 2300, 9, 6, 1325, 883}, // 1/2 {"Sigma", "SD1", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "SD1 Merrill", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1 Merrill", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1 Merrill", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP1 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP2 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP2 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP2 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP3 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP3 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP3 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Polaroid", "x530", 1440, 1088, 2700, 10, 13, 1419, 1059}, // dp2 Q {"Sigma", "dp3 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp3 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp2 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp2 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp1 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp1 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp0 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp0 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size // Sigma sd Quattro {"Sigma", "sd Quattro", 5888, 3776, 16383, 204, 76, 5446, 3624}, // full size {"Sigma", "sd Quattro", 2944, 1888, 16383, 102, 38, 2723, 1812}, // half size // Sd Quattro H {"Sigma", "sd Quattro H", 6656, 4480, 16383, 224, 160, 6208, 4160}, // full size {"Sigma", "sd Quattro H", 3328, 2240, 16383, 112, 80, 3104, 2080}, // half size {"Sigma", "sd Quattro H", 5504, 3680, 16383, 0, 4, 5496, 3668}, // full size {"Sigma", "sd Quattro H", 2752, 1840, 16383, 0, 2, 2748, 1834}, // half size }; const int foveon_count = sizeof(foveon_data) / sizeof(foveon_data[0]); int LibRaw::open_datastream(LibRaw_abstract_datastream *stream) { if (!stream) return ENOENT; if (!stream->valid()) return LIBRAW_IO_ERROR; recycle(); if(callbacks.pre_identify_cb) { int r = (callbacks.pre_identify_cb)(this); if(r == 1) goto final; } try { ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); identify(); if(callbacks.post_identify_cb) (callbacks.post_identify_cb)(this); #if 0 if(!strcasecmp(imgdata.idata.make, "Sony") && imgdata.color.maximum > 0 && imgdata.color.linear_max[0] > imgdata.color.maximum*3 && imgdata.color.linear_max[0] <= imgdata.color.maximum*4) for(int c = 0; c<4; c++) imgdata.color.linear_max[c] /= 4; #endif if (!strcasecmp(imgdata.idata.make, "Canon") && (load_raw == &LibRaw::canon_sraw_load_raw) && imgdata.sizes.raw_width > 0) { float ratio = float(imgdata.sizes.raw_height) / float(imgdata.sizes.raw_width); if ((ratio < 0.57 || ratio > 0.75) && imgdata.makernotes.canon.SensorHeight > 1 && imgdata.makernotes.canon.SensorWidth > 1) { imgdata.sizes.raw_width = imgdata.makernotes.canon.SensorWidth; imgdata.sizes.left_margin = imgdata.makernotes.canon.SensorLeftBorder; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.makernotes.canon.SensorRightBorder - imgdata.makernotes.canon.SensorLeftBorder + 1; imgdata.sizes.raw_height = imgdata.makernotes.canon.SensorHeight; imgdata.sizes.top_margin = imgdata.makernotes.canon.SensorTopBorder; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.makernotes.canon.SensorBottomBorder - imgdata.makernotes.canon.SensorTopBorder + 1; libraw_internal_data.unpacker_data.load_flags |= 256; // reset width/height in canon_sraw_load_raw() imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } else if (imgdata.sizes.raw_width == 4032 && imgdata.sizes.raw_height == 3402 && !strcasecmp(imgdata.idata.model, "EOS 80D")) // 80D hardcoded { imgdata.sizes.raw_width = 4536; imgdata.sizes.left_margin = 28; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.sizes.raw_width - imgdata.sizes.left_margin; imgdata.sizes.raw_height = 3024; imgdata.sizes.top_margin = 8; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.sizes.raw_height - imgdata.sizes.top_margin; libraw_internal_data.unpacker_data.load_flags |= 256; imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } } // XTrans Compressed? if (!imgdata.idata.dng_version && !strcasecmp(imgdata.idata.make, "Fujifilm") && (load_raw == &LibRaw::unpacked_load_raw)) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 2 != libraw_internal_data.unpacker_data.data_size) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 7 / 4 == libraw_internal_data.unpacker_data.data_size) load_raw = &LibRaw::fuji_14bit_load_raw; else parse_fuji_compressed_header(); } if (imgdata.idata.filters == 9) { // Adjust top/left margins for X-Trans int newtm = imgdata.sizes.top_margin % 6 ? (imgdata.sizes.top_margin / 6 + 1) * 6 : imgdata.sizes.top_margin; int newlm = imgdata.sizes.left_margin % 6 ? (imgdata.sizes.left_margin / 6 + 1) * 6 : imgdata.sizes.left_margin; if (newtm != imgdata.sizes.top_margin || newlm != imgdata.sizes.left_margin) { imgdata.sizes.height -= (newtm - imgdata.sizes.top_margin); imgdata.sizes.top_margin = newtm; imgdata.sizes.width -= (newlm - imgdata.sizes.left_margin); imgdata.sizes.left_margin = newlm; for (int c1 = 0; c1 < 6; c1++) for (int c2 = 0; c2 < 6; c2++) imgdata.idata.xtrans[c1][c2] = imgdata.idata.xtrans_abs[c1][c2]; } } } // Fix DNG white balance if needed if (imgdata.idata.dng_version && (imgdata.idata.filters == 0) && imgdata.idata.colors > 1 && imgdata.idata.colors < 5) { float delta[4] = {0.f, 0.f, 0.f, 0.f}; int black[4]; for (int c = 0; c < 4; c++) black[c] = imgdata.color.dng_levels.dng_black + imgdata.color.dng_levels.dng_cblack[c]; for (int c = 0; c < imgdata.idata.colors; c++) delta[c] = imgdata.color.dng_levels.dng_whitelevel[c] - black[c]; float mindelta = delta[0], maxdelta = delta[0]; for (int c = 1; c < imgdata.idata.colors; c++) { if (mindelta > delta[c]) mindelta = delta[c]; if (maxdelta < delta[c]) maxdelta = delta[c]; } if (mindelta > 1 && maxdelta < (mindelta * 20)) // safety { for (int c = 0; c < imgdata.idata.colors; c++) { imgdata.color.cam_mul[c] /= (delta[c] / maxdelta); imgdata.color.pre_mul[c] /= (delta[c] / maxdelta); } imgdata.color.maximum = imgdata.color.cblack[0] + maxdelta; } } if (imgdata.idata.dng_version && ((!strcasecmp(imgdata.idata.make, "Leica") && !strcasecmp(imgdata.idata.model, "D-LUX (Typ 109)")) || (!strcasecmp(imgdata.idata.make, "Panasonic") && !strcasecmp(imgdata.idata.model, "LX100")))) imgdata.sizes.width = 4288; if (!strncasecmp(imgdata.idata.make, "Sony", 4) && imgdata.idata.dng_version && !(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)) { if (S.raw_width == 3984) S.width = 3925; else if (S.raw_width == 4288) S.width = S.raw_width - 32; else if (S.raw_width == 4928 && S.height < 3280) S.width = S.raw_width - 8; else if (S.raw_width == 5504) S.width = S.raw_width - (S.height > 3664 ? 8 : 32); } if (!strcasecmp(imgdata.idata.make, "Pentax") && /*!strcasecmp(imgdata.idata.model,"K-3 II") &&*/ imgdata.idata.raw_count == 4 && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_PENTAX_PS_ALLFRAMES)) { imgdata.idata.raw_count = 1; imgdata.idata.filters = 0; imgdata.idata.colors = 4; IO.mix_green = 1; pentax_component_load_raw = load_raw; load_raw = &LibRaw::pentax_4shot_load_raw; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Leaf") && !strcmp(imgdata.idata.model, "Credo 50")) { imgdata.color.pre_mul[0] = 1.f / 0.3984f; imgdata.color.pre_mul[2] = 1.f / 0.7666f; imgdata.color.pre_mul[1] = imgdata.color.pre_mul[3] = 1.0; } // S3Pro DNG patch if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S3Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S5Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && (!strncmp(imgdata.idata.model, "S20Pro", 6) || !strncmp(imgdata.idata.model, "F700", 4))) { imgdata.sizes.raw_width /= 2; load_raw = &LibRaw::unpacked_load_raw_fuji_f700s20; } if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Nikon") && !libraw_internal_data.unpacker_data.load_flags && (!strncasecmp(imgdata.idata.model, "D810", 4) || !strcasecmp(imgdata.idata.model, "D4S")) && libraw_internal_data.unpacker_data.data_size * 2 == imgdata.sizes.raw_height * imgdata.sizes.raw_width * 3) { libraw_internal_data.unpacker_data.load_flags = 80; } // Adjust BL for Sony A900/A850 if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Sony")) // 12 bit sony, but metadata may be for 14-bit range { if (C.maximum > 4095) C.maximum = 4095; if (C.black > 256 || C.cblack[0] > 256) { C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } } if (load_raw == &LibRaw::nikon_yuv_load_raw) // Is it Nikon sRAW? { load_raw = &LibRaw::nikon_load_sraw; C.black = 0; memset(C.cblack, 0, sizeof(C.cblack)); imgdata.idata.filters = 0; libraw_internal_data.unpacker_data.tiff_samples = 3; imgdata.idata.colors = 3; double beta_1 = -5.79342238397656E-02; double beta_2 = 3.28163551282665; double beta_3 = -8.43136004842678; double beta_4 = 1.03533181861023E+01; for (int i = 0; i <= 3072; i++) { double x = (double)i / 3072.; double y = (1. - exp(-beta_1 * x - beta_2 * x * x - beta_3 * x * x * x - beta_4 * x * x * x * x)); if (y < 0.) y = 0.; imgdata.color.curve[i] = (y * 16383.); } for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) imgdata.color.rgb_cam[i][j] = float(i == j); } // Adjust BL for Nikon 12bit if ((load_raw == &LibRaw::nikon_load_raw || load_raw == &LibRaw::packed_load_raw) && !strcasecmp(imgdata.idata.make, "Nikon") && strncmp(imgdata.idata.model, "COOLPIX", 7) // && strncmp(imgdata.idata.model,"1 ",2) && libraw_internal_data.unpacker_data.tiff_bps == 12) { C.maximum = 4095; C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } // Adjust Highlight Linearity limit if (C.linear_max[0] < 0) { if (imgdata.idata.dng_version) { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c + 6]; } else { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c]; } } if (!strcasecmp(imgdata.idata.make, "Nikon") && (!C.linear_max[0]) && (C.maximum > 1024) && (load_raw != &LibRaw::nikon_load_sraw)) { C.linear_max[0] = C.linear_max[1] = C.linear_max[2] = C.linear_max[3] = (long)((float)(C.maximum) / 1.07f); } // Correct WB for Samsung GX20 if (!strcasecmp(imgdata.idata.make, "Samsung") && !strcasecmp(imgdata.idata.model, "GX20")) { C.WB_Coeffs[LIBRAW_WBI_Daylight][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Daylight][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Shade][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Shade][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Cloudy][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Tungsten][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_D][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_D][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_N][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_N][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_W][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_W][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Flash][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Flash][2]) * 2.56f); for (int c = 0; c < 64; c++) { if (imgdata.color.WBCT_Coeffs[c][0] > 0.0f) { imgdata.color.WBCT_Coeffs[c][3] *= 2.56f; } } } // Adjust BL for Panasonic if (load_raw == &LibRaw::panasonic_load_raw && (!strcasecmp(imgdata.idata.make, "Panasonic") || !strcasecmp(imgdata.idata.make, "Leica") || !strcasecmp(imgdata.idata.make, "YUNEEC")) && ID.pana_black[0] && ID.pana_black[1] && ID.pana_black[2]) { if(libraw_internal_data.unpacker_data.pana_encoding == 5) P1.raw_count = 0; // Disable for new decoder C.black = 0; int add = libraw_internal_data.unpacker_data.pana_encoding == 4?15:0; C.cblack[0] = ID.pana_black[0]+add; C.cblack[1] = C.cblack[3] = ID.pana_black[1]+add; C.cblack[2] = ID.pana_black[2]+add; int i = C.cblack[3]; for (int c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (int c = 0; c < 4; c++) C.cblack[c] -= i; C.black = i; } // Adjust sizes for X3F processing if (load_raw == &LibRaw::x3f_load_raw) { for (int i = 0; i < foveon_count; i++) if (!strcasecmp(imgdata.idata.make, foveon_data[i].make) && !strcasecmp(imgdata.idata.model, foveon_data[i].model) && imgdata.sizes.raw_width == foveon_data[i].raw_width && imgdata.sizes.raw_height == foveon_data[i].raw_height) { imgdata.sizes.top_margin = foveon_data[i].top_margin; imgdata.sizes.left_margin = foveon_data[i].left_margin; imgdata.sizes.width = imgdata.sizes.iwidth = foveon_data[i].width; imgdata.sizes.height = imgdata.sizes.iheight = foveon_data[i].height; C.maximum = foveon_data[i].white; break; } } #if 0 size_t bytes = ID.input->size()-libraw_internal_data.unpacker_data.data_offset; float bpp = float(bytes)/float(S.raw_width)/float(S.raw_height); float bpp2 = float(bytes)/float(S.width)/float(S.height); printf("RawSize: %dx%d data offset: %d data size:%d bpp: %g bpp2: %g\n",S.raw_width,S.raw_height,libraw_internal_data.unpacker_data.data_offset,bytes,bpp,bpp2); if(!strcasecmp(imgdata.idata.make,"Hasselblad") && bpp == 6.0f) { load_raw = &LibRaw::hasselblad_full_load_raw; S.width = S.raw_width; S.height = S.raw_height; P1.filters = 0; P1.colors=3; P1.raw_count=1; C.maximum=0xffff; printf("3 channel hassy found\n"); } #endif if (C.profile_length) { if (C.profile) free(C.profile); C.profile = malloc(C.profile_length); merror(C.profile, "LibRaw::open_file()"); ID.input->seek(ID.profile_offset, SEEK_SET); ID.input->read(C.profile, C.profile_length, 1); } SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } final:; if (P1.raw_count < 1) return LIBRAW_FILE_UNSUPPORTED; write_fun = &LibRaw::write_ppm_tiff; if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); if (IO.shrink && P1.filters >= 1000) { S.width &= 65534; S.height &= 65534; } S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_SIZE_ADJUST); return LIBRAW_SUCCESS; } #ifdef USE_RAWSPEED void LibRaw::fix_after_rawspeed(int bl) { if (load_raw == &LibRaw::lossy_dng_load_raw) C.maximum = 0xffff; else if (load_raw == &LibRaw::sony_load_raw) C.maximum = 0x3ff0; } #else void LibRaw::fix_after_rawspeed(int) {} #endif void LibRaw::clearCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 0); #else __sync_fetch_and_and(&_exitflag, 0); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->resumeProcessing(); } #endif } void LibRaw::setCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 1); #else __sync_fetch_and_add(&_exitflag, 1); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->cancelProcessing(); } #endif } void LibRaw::checkCancel() { #ifdef WIN32 if (InterlockedExchange(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #else if (__sync_fetch_and_and(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } int LibRaw::try_rawspeed() { #ifdef USE_RAWSPEED int ret = LIBRAW_SUCCESS; int rawspeed_ignore_errors = 0; if (imgdata.idata.dng_version && imgdata.idata.colors == 3 && !strcasecmp(imgdata.idata.software, "Adobe Photoshop Lightroom 6.1.1 (Windows)")) rawspeed_ignore_errors = 1; // RawSpeed Supported, INT64 spos = ID.input->tell(); void *_rawspeed_buffer = 0; try { // printf("Using rawspeed\n"); ID.input->seek(0, SEEK_SET); INT64 _rawspeed_buffer_sz = ID.input->size() + 32; _rawspeed_buffer = malloc(_rawspeed_buffer_sz); if (!_rawspeed_buffer) throw LIBRAW_EXCEPTION_ALLOC; ID.input->read(_rawspeed_buffer, _rawspeed_buffer_sz, 1); FileMap map((uchar8 *)_rawspeed_buffer, _rawspeed_buffer_sz); RawParser t(&map); RawDecoder *d = 0; CameraMetaDataLR *meta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); d = t.getDecoder(); if (!d) throw "Unable to find decoder"; try { d->checkSupport(meta); } catch (const RawDecoderException &e) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_UNSUPPORTED; throw e; } d->interpolateBadPixels = FALSE; d->applyStage1DngOpcodes = FALSE; _rawspeed_decoder = static_cast<void *>(d); d->decodeRaw(); d->decodeMetaData(meta); RawImage r = d->mRaw; if (r->errors.size() > 0 && !rawspeed_ignore_errors) { delete d; _rawspeed_decoder = 0; throw 1; } if (r->isCFA) { imgdata.rawdata.raw_image = (ushort *)r->getDataUncropped(0, 0); } else if (r->getCpp() == 4) { imgdata.rawdata.color4_image = (ushort(*)[4])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else if (r->getCpp() == 3) { imgdata.rawdata.color3_image = (ushort(*)[3])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else { delete d; _rawspeed_decoder = 0; ret = LIBRAW_UNSPECIFIED_ERROR; } if (_rawspeed_decoder) { // set sizes iPoint2D rsdim = r->getUncroppedDim(); S.raw_pitch = r->pitch; S.raw_width = rsdim.x; S.raw_height = rsdim.y; // C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } free(_rawspeed_buffer); _rawspeed_buffer = 0; imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROCESSED; } catch (const RawDecoderException &RDE) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } const char *p = RDE.what(); if (!strncmp(RDE.what(), "Decoder canceled", strlen("Decoder canceled"))) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; ret = LIBRAW_UNSPECIFIED_ERROR; } catch (...) { // We may get here due to cancellation flag imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } ret = LIBRAW_UNSPECIFIED_ERROR; } ID.input->seek(spos, SEEK_SET); return ret; #else return LIBRAW_NOT_IMPLEMENTED; #endif } int LibRaw::valid_for_dngsdk() { #ifndef USE_DNGSDK return 0; #else if (!imgdata.idata.dng_version) return 0; if (!imgdata.params.use_dngsdk) return 0; if (load_raw == &LibRaw::lossy_dng_load_raw) return 0; if (is_floating_point() && (imgdata.params.use_dngsdk & LIBRAW_DNG_FLOAT)) return 1; if (!imgdata.idata.filters && (imgdata.params.use_dngsdk & LIBRAW_DNG_LINEAR)) return 1; if (libraw_internal_data.unpacker_data.tiff_bps == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_8BIT)) return 1; if (libraw_internal_data.unpacker_data.tiff_compress == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_DEFLATE)) return 1; if (libraw_internal_data.unpacker_data.tiff_samples == 2) return 0; // Always deny 2-samples (old fuji superccd) if (imgdata.idata.filters == 9 && (imgdata.params.use_dngsdk & LIBRAW_DNG_XTRANS)) return 1; if (is_fuji_rotated()) return 0; // refuse if (imgdata.params.use_dngsdk & LIBRAW_DNG_OTHER) return 1; return 0; #endif } int LibRaw::is_curve_linear() { for (int i = 0; i < 0x10000; i++) if (imgdata.color.curve[i] != i) return 0; return 1; } int LibRaw::try_dngsdk() { #ifdef USE_DNGSDK if (!dnghost) return LIBRAW_UNSPECIFIED_ERROR; dng_host *host = static_cast<dng_host *>(dnghost); try { libraw_dng_stream stream(libraw_internal_data.internal_data.input); AutoPtr<dng_negative> negative; negative.Reset(host->Make_dng_negative()); dng_info info; info.Parse(*host, stream); info.PostParse(*host); if (!info.IsValidDNG()) { return LIBRAW_DATA_ERROR; } negative->Parse(*host, stream, info); negative->PostParse(*host, stream, info); negative->ReadStage1Image(*host, stream, info); dng_simple_image *stage2 = (dng_simple_image *)negative->Stage1Image(); if (stage2->Bounds().W() != S.raw_width || stage2->Bounds().H() != S.raw_height) { return LIBRAW_DATA_ERROR; } int pplanes = stage2->Planes(); int ptype = stage2->PixelType(); dng_pixel_buffer buffer; stage2->GetPixelBuffer(buffer); int pixels = stage2->Bounds().H() * stage2->Bounds().W() * pplanes; if (ptype == ttByte) imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ttShort)); else imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ptype)); if (ptype == ttShort && !is_curve_linear()) { ushort *src = (ushort *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } else if (ptype == ttByte) { unsigned char *src = (unsigned char *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; if (is_curve_linear()) { for (int i = 0; i < pixels; i++) dst[i] = src[i]; } else { for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; } S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ttShort); } else { memmove(imgdata.rawdata.raw_alloc, buffer.fData, pixels * TagTypeSize(ptype)); S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } switch (ptype) { case ttFloat: if (pplanes == 1) imgdata.rawdata.float_image = (float *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.float3_image = (float(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.float4_image = (float(*)[4])imgdata.rawdata.raw_alloc; break; case ttByte: case ttShort: if (pplanes == 1) imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; break; default: /* do nothing */ break; } } catch (...) { return LIBRAW_UNSPECIFIED_ERROR; } return imgdata.rawdata.raw_alloc ? LIBRAW_SUCCESS : LIBRAW_UNSPECIFIED_ERROR; #else return LIBRAW_UNSPECIFIED_ERROR; #endif } void LibRaw::set_dng_host(void *p) { #ifdef USE_DNGSDK dnghost = p; #endif } int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 0, 2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if (!load_raw) return LIBRAW_UNSPECIFIED_ERROR; // already allocated ? if (imgdata.image) { free(imgdata.image); imgdata.image = 0; } if (imgdata.rawdata.raw_alloc) { free(imgdata.rawdata.raw_alloc); imgdata.rawdata.raw_alloc = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *)malloc(libraw_internal_data.unpacker_data.meta_length); merror(libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if (!IO.fuji_width) { // adjust non-Fuji allocation if (rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if (rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } if (rwidth > 65535 || rheight > 65535) // No way to make image larger than 64k pix throw LIBRAW_EXCEPTION_IO_CORRUPT; imgdata.rawdata.raw_image = 0; imgdata.rawdata.color4_image = 0; imgdata.rawdata.color3_image = 0; imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; #ifdef USE_DNGSDK if (imgdata.idata.dng_version && dnghost && imgdata.idata.raw_count == 1 && valid_for_dngsdk() && load_raw != &LibRaw::pentax_4shot_load_raw) { int rr = try_dngsdk(); } #endif #ifdef USE_RAWSPEED if (!raw_was_read()) { int rawspeed_enabled = 1; if (imgdata.idata.dng_version && libraw_internal_data.unpacker_data.tiff_samples == 2) rawspeed_enabled = 0; if (imgdata.idata.raw_count > 1) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.software, "Magic", 5)) rawspeed_enabled = 0; // Disable rawspeed for double-sized Oly files if (!strncasecmp(imgdata.idata.make, "Olympus", 7) && ((imgdata.sizes.raw_width > 6000) || !strncasecmp(imgdata.idata.model, "SH-2", 4) || !strncasecmp(imgdata.idata.model, "SH-3", 4) || !strncasecmp(imgdata.idata.model, "TG-4", 4) || !strncasecmp(imgdata.idata.model, "TG-5", 4))) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.make, "Canon", 5) && !strcasecmp(imgdata.idata.model, "EOS 6D Mark II")) rawspeed_enabled = 0; if (imgdata.idata.dng_version && imgdata.idata.filters == 0 && libraw_internal_data.unpacker_data.tiff_bps == 8) // Disable for 8 bit rawspeed_enabled = 0; if (load_raw == &LibRaw::packed_load_raw && !strncasecmp(imgdata.idata.make, "Nikon", 5) && (!strncasecmp(imgdata.idata.model, "E", 1) || !strncasecmp(imgdata.idata.model, "COOLPIX B", 9))) rawspeed_enabled = 0; // RawSpeed Supported, if (O.use_rawspeed && rawspeed_enabled && !(is_sraw() && (O.raw_processing_options & (LIBRAW_PROCESSING_SRAW_NO_RGB | LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE))) && (decoder_info.decoder_flags & LIBRAW_DECODER_TRYRAWSPEED) && _rawspeed_camerameta) { int rr = try_rawspeed(); } } #endif if (!raw_was_read()) // RawSpeed failed or not run { // Not allocated on RawSpeed call, try call LibRaow int zero_rawimage = 0; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder and DNG float // Do nothing! Decoder will allocate data internally } if (decoder_info.decoder_flags & LIBRAW_DECODER_3CHANNEL) { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3 > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3); imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 6; } else if (imgdata.idata.filters || P1.colors == 1) // Bayer image or single color -> decode to raw_image { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 2; // Bayer case, not set before } else // NO LEGACY FLAG if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) { S.raw_pitch = S.raw_width * 8; } else { S.iwidth = S.width; S.iheight = S.height; IO.shrink = 0; if (!S.raw_pitch) S.raw_pitch = (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS) ? S.raw_width * 8 : S.width * 8; } // sRAW and old Foveon decoders only, so extra buffer size is just 1/4 // allocate image as temporary buffer, size if (INT64(MAX(S.width, S.raw_width)) * INT64(MAX(S.height, S.raw_height)) * sizeof(*imgdata.image) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = 0; imgdata.image = (ushort(*)[4])calloc( unsigned(MAX(S.width, S.raw_width)) * unsigned(MAX(S.height, S.raw_height)), sizeof(*imgdata.image)); if (!(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL)) { imgdata.rawdata.raw_image = (ushort *)imgdata.image; zero_rawimage = 1; } } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); unsigned m_save = C.maximum; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = 65535; (this->*load_raw)(); if (zero_rawimage) imgdata.rawdata.raw_image = 0; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = m_save; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder only: do nothing } else if (!(imgdata.idata.filters || P1.colors == 1)) // legacy decoder, ownalloc handled above { // successfully decoded legacy image, attach image to raw_alloc imgdata.rawdata.raw_alloc = imgdata.image; imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; imgdata.image = 0; // Restore saved values. Note: Foveon have masked frame // Other 4-color legacy data: no borders if (!(libraw_internal_data.unpacker_data.load_flags & 256) && !(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) && !(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS)) { S.raw_width = S.width; S.left_margin = 0; S.raw_height = S.height; S.top_margin = 0; } } } if (imgdata.rawdata.raw_image) crop_masked_pixels(); // calculate black levels // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 1, 2); return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } void LibRaw::unpacked_load_raw_fuji_f700s20() { int base_offset = 0; int row_size = imgdata.sizes.raw_width * 2; // in bytes if (imgdata.idata.raw_count == 2 && imgdata.params.shot_select) { libraw_internal_data.internal_data.input->seek(-row_size, SEEK_CUR); base_offset = row_size; // in bytes } unsigned char *buffer = (unsigned char *)malloc(row_size * 2); for (int row = 0; row < imgdata.sizes.raw_height; row++) { read_shorts((ushort *)buffer, imgdata.sizes.raw_width * 2); memmove(&imgdata.rawdata.raw_image[row * imgdata.sizes.raw_pitch / 2], buffer + base_offset, row_size); } free(buffer); } void LibRaw::nikon_load_sraw() { // We're already seeked to data! unsigned char *rd = (unsigned char *)malloc(3 * (imgdata.sizes.raw_width + 2)); if (!rd) throw LIBRAW_EXCEPTION_ALLOC; try { int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); libraw_internal_data.internal_data.input->read(rd, 3, imgdata.sizes.raw_width); for (col = 0; col < imgdata.sizes.raw_width - 1; col += 2) { int bi = col * 3; ushort bits1 = (rd[bi + 1] & 0xf) << 8 | rd[bi]; // 3,0,1 ushort bits2 = rd[bi + 2] << 4 | ((rd[bi + 1] >> 4) & 0xf); // 452 ushort bits3 = ((rd[bi + 4] & 0xf) << 8) | rd[bi + 3]; // 967 ushort bits4 = rd[bi + 5] << 4 | ((rd[bi + 4] >> 4) & 0xf); // ab8 imgdata.image[row * imgdata.sizes.raw_width + col][0] = bits1; imgdata.image[row * imgdata.sizes.raw_width + col][1] = bits3; imgdata.image[row * imgdata.sizes.raw_width + col][2] = bits4; imgdata.image[row * imgdata.sizes.raw_width + col + 1][0] = bits2; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = 2048; imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = 2048; } } } catch (...) { free(rd); throw; } free(rd); C.maximum = 0xfff; // 12 bit? if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { return; // no CbCr interpolation } // Interpolate CC channels int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col += 2) { int col2 = col < imgdata.sizes.raw_width - 2 ? col + 2 : col; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][1] + imgdata.image[row * imgdata.sizes.raw_width + col2][1]) / 2); imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][2] + imgdata.image[row * imgdata.sizes.raw_width + col2][2]) / 2); } } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) return; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col++) { float Y = float(imgdata.image[row * imgdata.sizes.raw_width + col][0]) / 2549.f; float Ch2 = float(imgdata.image[row * imgdata.sizes.raw_width + col][1] - 1280) / 1536.f; float Ch3 = float(imgdata.image[row * imgdata.sizes.raw_width + col][2] - 1280) / 1536.f; if (Y > 1.f) Y = 1.f; if (Y > 0.803f) Ch2 = Ch3 = 0.5f; float r = Y + 1.40200f * (Ch3 - 0.5f); if (r < 0.f) r = 0.f; if (r > 1.f) r = 1.f; float g = Y - 0.34414f * (Ch2 - 0.5f) - 0.71414 * (Ch3 - 0.5f); if (g > 1.f) g = 1.f; if (g < 0.f) g = 0.f; float b = Y + 1.77200 * (Ch2 - 0.5f); if (b > 1.f) b = 1.f; if (b < 0.f) b = 0.f; imgdata.image[row * imgdata.sizes.raw_width + col][0] = imgdata.color.curve[int(r * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][1] = imgdata.color.curve[int(g * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][2] = imgdata.color.curve[int(b * 3072.f)]; } } C.maximum = 16383; } void LibRaw::free_image(void) { if (imgdata.image) { free(imgdata.image); imgdata.image = 0; imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; } } void LibRaw::raw2image_start() { // restore color,sizes and internal data into raw_image fields memmove(&imgdata.color, &imgdata.rawdata.color, sizeof(imgdata.color)); memmove(&imgdata.sizes, &imgdata.rawdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.idata, &imgdata.rawdata.iparams, sizeof(imgdata.idata)); memmove(&libraw_internal_data.internal_output_params, &imgdata.rawdata.ioparams, sizeof(libraw_internal_data.internal_output_params)); if (O.user_flip >= 0) S.flip = O.user_flip; switch ((S.flip + 3600) % 360) { case 270: S.flip = 5; break; case 180: S.flip = 3; break; case 90: S.flip = 6; break; } // adjust for half mode! IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; } int LibRaw::is_phaseone_compressed() { return (load_raw == &LibRaw::phase_one_load_raw_c || load_raw == &LibRaw::phase_one_load_raw); } int LibRaw::is_canon_600() { return load_raw == &LibRaw::canon_600_load_raw; } int LibRaw::raw2image(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // free and re-allocate image bitmap if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, S.iheight * S.iwidth * sizeof(*imgdata.image)); memset(imgdata.image, 0, S.iheight * S.iwidth * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { unsigned r, c; int row, col; for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][FC(r, c)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } } else { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][fcol(row, col)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.width * 8 == S.raw_pitch) memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); else { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } // hack - clear later flags! if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } void LibRaw::phase_one_allocate_tempbuffer() { // Allocate temp raw_image buffer imgdata.rawdata.raw_image = (ushort *)malloc(S.raw_pitch * S.raw_height); merror(imgdata.rawdata.raw_image, "phase_one_prepare_to_correct()"); } void LibRaw::phase_one_free_tempbuffer() { free(imgdata.rawdata.raw_image); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; } int LibRaw::phase_one_subtract_black(ushort *src, ushort *dest) { try { if (O.user_black < 0 && O.user_cblack[0] <= -1000000 && O.user_cblack[1] <= -1000000 && O.user_cblack[2] <= -1000000 && O.user_cblack[3] <= -1000000) { if (!imgdata.rawdata.ph1_cblack || !imgdata.rawdata.ph1_rblack) { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl; dest[idx] = val > 0 ? val : 0; } } } else { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl + imgdata.rawdata.ph1_cblack[row][col >= imgdata.rawdata.color.phase_one_data.split_col] + imgdata.rawdata.ph1_rblack[col][row >= imgdata.rawdata.color.phase_one_data.split_row]; dest[idx] = val > 0 ? val : 0; } } } } else // black set by user interaction { // Black level in cblack! for (int row = 0; row < S.raw_height; row++) { checkCancel(); unsigned short cblk[16]; for (int cc = 0; cc < 16; cc++) cblk[cc] = C.cblack[fcol(row, cc)]; for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; ushort val = src[idx]; ushort bl = cblk[col & 0xf]; dest[idx] = val > bl ? val - bl : 0; } } } return 0; } catch (LibRaw_exceptions err) { return LIBRAW_CANCELLED_BY_CALLBACK; } } void LibRaw::copy_fuji_uncropped(unsigned short cblack[4], unsigned short *dmaxp) { int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { unsigned r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FC(r, c); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][cc] = val; } } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } void LibRaw::copy_bayer(unsigned short cblack[4], unsigned short *dmaxp) { // Both cropped and uncropped int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.height; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < S.width; col++) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = fcol(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][cc] = val; } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } int LibRaw::raw2image_ex(int do_subtract_black) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); // Compressed P1 files with bl data! if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // process cropping int do_crop = 0; unsigned save_width = S.width; if (~O.cropbox[2] && ~O.cropbox[3]) { int crop[4], c, filt; for (int c = 0; c < 4; c++) { crop[c] = O.cropbox[c]; if (crop[c] < 0) crop[c] = 0; } if (IO.fuji_width && imgdata.idata.filters >= 1000) { crop[0] = (crop[0] / 4) * 4; crop[1] = (crop[1] / 4) * 4; if (!libraw_internal_data.unpacker_data.fuji_layout) { crop[2] *= sqrt(2.0); crop[3] /= sqrt(2.0); } crop[2] = (crop[2] / 4 + 1) * 4; crop[3] = (crop[3] / 4 + 1) * 4; } else if (imgdata.idata.filters == 1) { crop[0] = (crop[0] / 16) * 16; crop[1] = (crop[1] / 16) * 16; } else if (imgdata.idata.filters == LIBRAW_XTRANS) { crop[0] = (crop[0] / 6) * 6; crop[1] = (crop[1] / 6) * 6; } do_crop = 1; crop[2] = MIN(crop[2], (signed)S.width - crop[0]); crop[3] = MIN(crop[3], (signed)S.height - crop[1]); if (crop[2] <= 0 || crop[3] <= 0) throw LIBRAW_EXCEPTION_BAD_CROP; // adjust sizes! S.left_margin += crop[0]; S.top_margin += crop[1]; S.width = crop[2]; S.height = crop[3]; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if (!IO.fuji_width && imgdata.idata.filters && imgdata.idata.filters >= 1000) { for (filt = c = 0; c < 16; c++) filt |= FC((c >> 1) + (crop[1]), (c & 1) + (crop[0])) << c * 2; imgdata.idata.filters = filt; } } int alloc_width = S.iwidth; int alloc_height = S.iheight; if (IO.fuji_width && do_crop) { int IO_fw = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int t_alloc_width = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO_fw; int t_alloc_height = t_alloc_width - 1; alloc_height = (t_alloc_height + IO.shrink) >> IO.shrink; alloc_width = (t_alloc_width + IO.shrink) >> IO.shrink; } int alloc_sz = alloc_width * alloc_height; if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, alloc_sz * sizeof(*imgdata.image)); memset(imgdata.image, 0, alloc_sz * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(alloc_sz, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image_ex()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Adjust black levels unsigned short cblack[4] = {0, 0, 0, 0}; unsigned short dmax = 0; if (do_subtract_black) { adjust_bl(); for (int i = 0; i < 4; i++) cblack[i] = (unsigned short)C.cblack[i]; } // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { if (do_crop) { IO.fuji_width = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int IO_fwidth = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO.fuji_width; int IO_fheight = IO_fwidth - 1; int row, col; for (row = 0; row < S.height; row++) { for (col = 0; col < S.width; col++) { int r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FCF(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (dmax < val) dmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * alloc_width + ((c) >> IO.shrink)][cc] = val; } } S.height = IO_fheight; S.width = IO_fwidth; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; S.raw_height -= 2 * S.top_margin; } else { copy_fuji_uncropped(cblack, &dmax); } } // end Fuji else { copy_bayer(cblack, &dmax); } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.raw_pitch != S.width * 8) { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } else { // legacy is always 4channel and not shrinked! memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } if (do_subtract_black) { C.data_maximum = (int)dmax; C.maximum -= C.black; // ZERO(C.cblack); C.cblack[0] = C.cblack[1] = C.cblack[2] = C.cblack[3] = 0; C.black = 0; } // hack - clear later flags! imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #if 1 libraw_processed_image_t *LibRaw::dcraw_make_mem_thumb(int *errcode) { if (!T.thumb) { if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { if (errcode) *errcode = LIBRAW_NO_THUMBNAIL; } else { if (errcode) *errcode = LIBRAW_OUT_OF_ORDER_CALL; } return NULL; } if (T.tformat == LIBRAW_THUMBNAIL_BITMAP) { libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + T.tlength); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_BITMAP; ret->height = T.theight; ret->width = T.twidth; ret->colors = 3; ret->bits = 8; ret->data_size = T.tlength; memmove(ret->data, T.thumb, T.tlength); if (errcode) *errcode = 0; return ret; } else if (T.tformat == LIBRAW_THUMBNAIL_JPEG) { ushort exif[5]; int mk_exif = 0; if (strcmp(T.thumb + 6, "Exif")) mk_exif = 1; int dsize = T.tlength + mk_exif * (sizeof(exif) + sizeof(tiff_hdr)); libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + dsize); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_JPEG; ret->data_size = dsize; ret->data[0] = 0xff; ret->data[1] = 0xd8; if (mk_exif) { struct tiff_hdr th; memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); memmove(ret->data + 2, exif, sizeof(exif)); tiff_head(&th, 0); memmove(ret->data + (2 + sizeof(exif)), &th, sizeof(th)); memmove(ret->data + (2 + sizeof(exif) + sizeof(th)), T.thumb + 2, T.tlength - 2); } else { memmove(ret->data + 2, T.thumb + 2, T.tlength - 2); } if (errcode) *errcode = 0; return ret; } else { if (errcode) *errcode = LIBRAW_UNSUPPORTED_THUMBNAIL; return NULL; } } // jlb // macros for copying pixels to either BGR or RGB formats #define FORBGR for (c = P1.colors - 1; c >= 0; c--) #define FORRGB for (c = 0; c < P1.colors; c++) void LibRaw::get_mem_image_format(int *width, int *height, int *colors, int *bps) const { if (S.flip & 4) { *width = S.height; *height = S.width; } else { *width = S.width; *height = S.height; } *colors = P1.colors; *bps = O.output_bps; } int LibRaw::copy_mem_image(void *scan0, int stride, int bgr) { // the image memory pointed to by scan0 is assumed to be in the format returned by get_mem_image_format if ((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) < LIBRAW_PROGRESS_PRE_INTERPOLATE) return LIBRAW_OUT_OF_ORDER_CALL; if (libraw_internal_data.output_data.histogram) { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * O.auto_bright_thr; if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } int s_iheight = S.iheight; int s_iwidth = S.iwidth; int s_width = S.width; int s_hwight = S.height; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, S.width); for (row = 0; row < S.height; row++, soff += rstep) { uchar *bufp = ((uchar *)scan0) + row * stride; ppm2 = (ushort *)(ppm = bufp); // keep trivial decisions in the outer loop for speed if (bgr) { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } else { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } // bufp += stride; // go to the next line } S.iheight = s_iheight; S.iwidth = s_iwidth; S.width = s_width; S.height = s_hwight; return 0; } #undef FORBGR #undef FORRGB libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode) { int width, height, colors, bps; get_mem_image_format(&width, &height, &colors, &bps); int stride = width * (bps / 8) * colors; unsigned ds = height * stride; libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + ds); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); // metadata init ret->type = LIBRAW_IMAGE_BITMAP; ret->height = height; ret->width = width; ret->colors = colors; ret->bits = bps; ret->data_size = ds; copy_mem_image(ret->data, stride, 0); return ret; } #undef FORC #undef FORCC #undef SWAP #endif int LibRaw::dcraw_ppm_tiff_writer(const char *filename) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); if (!imgdata.image) return LIBRAW_OUT_OF_ORDER_CALL; if (!filename) return ENOENT; FILE *f = fopen(filename, "wb"); if (!f) return errno; try { if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_ppm_tiff_writer()"); } libraw_internal_data.internal_data.output = f; write_ppm_tiff(); SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); libraw_internal_data.internal_data.output = NULL; fclose(f); return 0; } catch (LibRaw_exceptions err) { fclose(f); EXCEPTION_HANDLER(err); } } #define THUMB_READ_BEYOND 16384 void LibRaw::kodak_thumb_loader() { INT64 est_datasize = T.theight * T.twidth / 3; // is 0.3 bytes per pixel good estimate? if (ID.toffset < 0) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (ID.toffset + est_datasize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; // some kodak cameras ushort s_height = S.height, s_width = S.width, s_iwidth = S.iwidth, s_iheight = S.iheight; ushort s_flags = libraw_internal_data.unpacker_data.load_flags; libraw_internal_data.unpacker_data.load_flags = 12; int s_colors = P1.colors; unsigned s_filters = P1.filters; ushort(*s_image)[4] = imgdata.image; S.height = T.theight; S.width = T.twidth; P1.filters = 0; if (thumb_load_raw == &CLASS kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "LibRaw::kodak_thumb_loader()"); ID.input->seek(ID.toffset, SEEK_SET); // read kodak thumbnail into T.image[] try { (this->*thumb_load_raw)(); } catch (...) { free(imgdata.image); imgdata.image = s_image; T.twidth = 0; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = 0; S.height = s_height; T.tcolors = 0; P1.colors = s_colors; P1.filters = s_filters; T.tlength = 0; libraw_internal_data.unpacker_data.load_flags = s_flags; return; } // copy-n-paste from image pipe #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #ifndef CLIP #define CLIP(x) LIM(x, 0, 65535) #endif #define SWAP(a, b) \ { \ a ^= b; \ a ^= (b ^= a); \ } // from scale_colors { double dmax; float scale_mul[4]; int c, val; for (dmax = DBL_MAX, c = 0; c < 3; c++) if (dmax > C.pre_mul[c]) dmax = C.pre_mul[c]; for (c = 0; c < 3; c++) scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum; scale_mul[3] = scale_mul[1]; size_t size = S.height * S.width; for (unsigned i = 0; i < size * 4; i++) { val = imgdata.image[0][i]; if (!val) continue; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } // from convert_to_rgb ushort *img; int row, col; int(*t_hist)[LIBRAW_HISTOGRAM_SIZE] = (int(*)[LIBRAW_HISTOGRAM_SIZE])calloc(sizeof(*t_hist), 4); merror(t_hist, "LibRaw::kodak_thumb_loader()"); float out[3], out_cam[3][4] = {{2.81761312, -1.98369181, 0.166078627, 0}, {-0.111855984, 1.73688626, -0.625030339, 0}, {-0.0379119813, -0.891268849, 1.92918086, 0}}; for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { out[0] = out[1] = out[2] = 0; int c; for (c = 0; c < 3; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); for (c = 0; c < P1.colors; c++) t_hist[c][img[c] >> 3]++; } // from gamma_lut int(*save_hist)[LIBRAW_HISTOGRAM_SIZE] = libraw_internal_data.output_data.histogram; libraw_internal_data.output_data.histogram = t_hist; // make curve output curve! ushort(*t_curve) = (ushort *)calloc(sizeof(C.curve), 1); merror(t_curve, "LibRaw::kodak_thumb_loader()"); memmove(t_curve, C.curve, sizeof(C.curve)); memset(C.curve, 0, sizeof(C.curve)); { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } libraw_internal_data.output_data.histogram = save_hist; free(t_hist); // from write_ppm_tiff - copy pixels into bitmap int s_flip = imgdata.sizes.flip; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = 0; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); if (T.thumb) free(T.thumb); T.thumb = (char *)calloc(S.width * S.height, P1.colors); merror(T.thumb, "LibRaw::kodak_thumb_loader()"); T.tlength = S.width * S.height * P1.colors; // from write_tiff_ppm { int soff = flip_index(0, 0); int cstep = flip_index(0, 1) - soff; int rstep = flip_index(1, 0) - flip_index(0, S.width); for (int row = 0; row < S.height; row++, soff += rstep) { char *ppm = T.thumb + row * S.width * P1.colors; for (int col = 0; col < S.width; col++, soff += cstep) for (int c = 0; c < P1.colors; c++) ppm[col * P1.colors + c] = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } } memmove(C.curve, t_curve, sizeof(C.curve)); free(t_curve); // restore variables free(imgdata.image); imgdata.image = s_image; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = s_flip; T.twidth = S.width; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = S.height; S.height = s_height; T.tcolors = P1.colors; P1.colors = s_colors; P1.filters = s_filters; libraw_internal_data.unpacker_data.load_flags = s_flags; } #undef MIN #undef MAX #undef LIM #undef CLIP #undef SWAP // ������� thumbnail �� �����, ������ thumb_format � ������������ � �������� int LibRaw::thumbOK(INT64 maxsz) { if (!ID.input) return 0; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) return 0; INT64 fsize = ID.input->size(); if (fsize > 0x7fffffffU) return 0; // No thumb for raw > 2Gb int tsize = 0; int tcol = (T.tcolors > 0 && T.tcolors < 4) ? T.tcolors : 3; if (write_thumb == &LibRaw::jpeg_thumb) tsize = T.tlength; else if (write_thumb == &LibRaw::ppm_thumb) tsize = tcol * T.twidth * T.theight; else if (write_thumb == &LibRaw::ppm16_thumb) tsize = tcol * T.twidth * T.theight * ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1); else if (write_thumb == &LibRaw::x3f_thumb_loader) { tsize = x3f_thumb_size(); } else // Kodak => no check tsize = 1; if (tsize < 0) return 0; if (maxsz > 0 && tsize > maxsz) return 0; return (tsize + ID.toffset <= fsize) ? 1 : 0; } #ifndef NO_JPEG struct jpegErrorManager { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; longjmp(myerr->setjmp_buffer, 1); } #endif int LibRaw::unpack_thumb(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7; int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { return LIBRAW_NO_THUMBNAIL; } else if (thumb_load_raw) { kodak_thumb_loader(); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { if (write_thumb == &LibRaw::x3f_thumb_loader) { INT64 tsize = x3f_thumb_size(); if (tsize < 2048 || INT64(ID.toffset) + tsize < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } else { if (INT64(ID.toffset) + INT64(T.tlength) < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + INT64(T.tlength) > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } ID.input->seek(ID.toffset, SEEK_SET); if (write_thumb == &LibRaw::jpeg_thumb) { if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "jpeg_thumb()"); ID.input->read(T.thumb, 1, T.tlength); unsigned char *tthumb = (unsigned char *)T.thumb; tthumb[0] = 0xff; tthumb[1] = 0xd8; #ifdef NO_JPEG T.tcolors = 3; #else { jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; if (setjmp(jerr.setjmp_buffer)) { err2: jpeg_destroy_decompress(&cinfo); T.tcolors = 3; } jpeg_create_decompress(&cinfo); jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) goto err2; T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3) ? cinfo.num_components : 3; jpeg_destroy_decompress(&cinfo); } #endif T.tformat = LIBRAW_THUMBNAIL_JPEG; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm_thumb) { if (t_bytesps > 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more bits int t_length = T.twidth * T.theight * t_colors; if (T.tlength && T.tlength < t_length) // try to find tiff ifd with needed offset { int pifd = -1; for (int ii = 0; ii < libraw_internal_data.identify_data.tiff_nifds && ii < LIBRAW_IFD_MAXCOUNT; ii++) if (tiff_ifd[ii].offset == libraw_internal_data.internal_data.toffset) // found { pifd = ii; break; } if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count && tiff_ifd[pifd].strip_byte_counts_count) { // We found it, calculate final size unsigned total_size = 0; for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++) total_size += tiff_ifd[pifd].strip_byte_counts[i]; if (total_size != t_length) // recalculate colors { if (total_size == T.twidth * T.tlength * 3) T.tcolors = 3; else if (total_size == T.twidth * T.tlength) T.tcolors = 1; } T.tlength = total_size; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "ppm_thumb()"); char *dest = T.thumb; INT64 pos = ID.input->tell(); for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count && i < tiff_ifd[pifd].strip_offsets_count; i++) { int remain = T.tlength; int sz = tiff_ifd[pifd].strip_byte_counts[i]; int off = tiff_ifd[pifd].strip_offsets[i]; if (off >= 0 && off + sz <= ID.input->size() && sz <= remain) { ID.input->seek(off, SEEK_SET); ID.input->read(dest, sz, 1); remain -= sz; dest += sz; } } ID.input->seek(pos, SEEK_SET); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } } if (!T.tlength) T.tlength = t_length; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); if (!T.tcolors) T.tcolors = t_colors; merror(T.thumb, "ppm_thumb()"); ID.input->read(T.thumb, 1, T.tlength); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm16_thumb) { if (t_bytesps > 2) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for more bits int o_bps = (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1; int o_length = T.twidth * T.theight * t_colors * o_bps; int i_length = T.twidth * T.theight * t_colors * 2; if (!T.tlength) T.tlength = o_length; ushort *t_thumb = (ushort *)calloc(i_length, 1); ID.input->read(t_thumb, 1, i_length); if ((libraw_internal_data.unpacker_data.order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)t_thumb, (char *)t_thumb, i_length); if (T.thumb) free(T.thumb); if ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS)) { T.thumb = (char *)t_thumb; T.tformat = LIBRAW_THUMBNAIL_BITMAP16; } else { T.thumb = (char *)malloc(o_length); merror(T.thumb, "ppm_thumb()"); for (int i = 0; i < o_length; i++) T.thumb[i] = t_thumb[i] >> 8; free(t_thumb); T.tformat = LIBRAW_THUMBNAIL_BITMAP; } SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::x3f_thumb_loader) { x3f_thumb_loader(); SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { return LIBRAW_UNSUPPORTED_THUMBNAIL; } } // last resort return LIBRAW_UNSUPPORTED_THUMBNAIL; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } int LibRaw::dcraw_thumb_writer(const char *fname) { // CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD); if (!fname) return ENOENT; FILE *tfp = fopen(fname, "wb"); if (!tfp) return errno; if (!T.thumb) { fclose(tfp); return LIBRAW_OUT_OF_ORDER_CALL; } try { switch (T.tformat) { case LIBRAW_THUMBNAIL_JPEG: jpeg_thumb_writer(tfp, T.thumb, T.tlength); break; case LIBRAW_THUMBNAIL_BITMAP: fprintf(tfp, "P6\n%d %d\n255\n", T.twidth, T.theight); fwrite(T.thumb, 1, T.tlength, tfp); break; default: fclose(tfp); return LIBRAW_UNSUPPORTED_THUMBNAIL; } fclose(tfp); return 0; } catch (LibRaw_exceptions err) { fclose(tfp); EXCEPTION_HANDLER(err); } } int LibRaw::adjust_sizes_info_only(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); raw2image_start(); if (O.use_fuji_rotate) { if (IO.fuji_width) { IO.fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink; S.iwidth = (ushort)(IO.fuji_width / sqrt(0.5)); S.iheight = (ushort)((S.iheight - IO.fuji_width) / sqrt(0.5)); } else { if (S.pixel_aspect < 0.995) S.iheight = (ushort)(S.iheight / S.pixel_aspect + 0.5); if (S.pixel_aspect > 1.005) S.iwidth = (ushort)(S.iwidth * S.pixel_aspect + 0.5); } } SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); if (S.flip & 4) { unsigned short t = S.iheight; S.iheight = S.iwidth; S.iwidth = t; SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); } return 0; } int LibRaw::subtract_black() { adjust_bl(); return subtract_black_internal(); } int LibRaw::subtract_black_internal() { CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE); try { if (!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3] || (C.cblack[4] && C.cblack[5]))) { #define BAYERC(row, col, c) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][c] int cblk[4], i; for (i = 0; i < 4; i++) cblk[i] = C.cblack[i]; int size = S.iheight * S.iwidth; #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define CLIP(x) LIM(x, 0, 65535) int dmax = 0; if (C.cblack[4] && C.cblack[5]) { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } else { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } C.data_maximum = dmax & 0xffff; #undef MIN #undef MAX #undef LIM #undef CLIP C.maximum -= C.black; ZERO(C.cblack); // Yeah, we used cblack[6+] values too! C.black = 0; #undef BAYERC } else { // Nothing to Do, maximum is already calculated, black level is 0, so no change // only calculate channel maximum; int idx; ushort *p = (ushort *)imgdata.image; int dmax = 0; for (idx = 0; idx < S.iheight * S.iwidth * 4; idx++) if (dmax < p[idx]) dmax = p[idx]; C.data_maximum = dmax; } return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #define TBLN 65535 void LibRaw::exp_bef(float shift, float smooth) { // params limits if (shift > 8) shift = 8; if (shift < 0.25) shift = 0.25; if (smooth < 0.0) smooth = 0.0; if (smooth > 1.0) smooth = 1.0; unsigned short *lut = (ushort *)malloc((TBLN + 1) * sizeof(unsigned short)); if (shift <= 1.0) { for (int i = 0; i <= TBLN; i++) lut[i] = (unsigned short)((float)i * shift); } else { float x1, x2, y1, y2; float cstops = log(shift) / log(2.0f); float room = cstops * 2; float roomlin = powf(2.0f, room); x2 = (float)TBLN; x1 = (x2 + 1) / roomlin - 1; y1 = x1 * shift; y2 = x2 * (1 + (1 - smooth) * (shift - 1)); float sq3x = powf(x1 * x1 * x2, 1.0f / 3.0f); float B = (y2 - y1 + shift * (3 * x1 - 3.0f * sq3x)) / (x2 + 2.0f * x1 - 3.0f * sq3x); float A = (shift - B) * 3.0f * powf(x1 * x1, 1.0f / 3.0f); float CC = y2 - A * powf(x2, 1.0f / 3.0f) - B * x2; for (int i = 0; i <= TBLN; i++) { float X = (float)i; float Y = A * powf(X, 1.0f / 3.0f) + B * X + CC; if (i < x1) lut[i] = (unsigned short)((float)i * shift); else lut[i] = Y < 0 ? 0 : (Y > TBLN ? TBLN : (unsigned short)(Y)); } } for (int i = 0; i < S.height * S.width; i++) { imgdata.image[i][0] = lut[imgdata.image[i][0]]; imgdata.image[i][1] = lut[imgdata.image[i][1]]; imgdata.image[i][2] = lut[imgdata.image[i][2]]; imgdata.image[i][3] = lut[imgdata.image[i][3]]; } if (C.data_maximum <= TBLN) C.data_maximum = lut[C.data_maximum]; if (C.maximum <= TBLN) C.maximum = lut[C.maximum]; free(lut); } #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y)) #define CLIP(x) LIM(x, 0, 65535) void LibRaw::convert_to_rgb_loop(float out_cam[3][4]) { int row, col, c; float out[3]; ushort *img; memset(libraw_internal_data.output_data.histogram, 0, sizeof(int) * LIBRAW_HISTOGRAM_SIZE * 4); for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { if (!libraw_internal_data.internal_output_params.raw_color) { out[0] = out[1] = out[2] = 0; for (c = 0; c < imgdata.idata.colors; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); } for (c = 0; c < imgdata.idata.colors; c++) libraw_internal_data.output_data.histogram[c][img[c] >> 3]++; } } void LibRaw::scale_colors_loop(float scale_mul[4]) { unsigned size = S.iheight * S.iwidth; if (C.cblack[4] && C.cblack[5]) { int val; for (unsigned i = 0; i < size * 4; i++) { if (!(val = imgdata.image[0][i])) continue; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else if (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3]) { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; if (!val) continue; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else // BL is zero { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } } void LibRaw::adjust_bl() { int clear_repeat = 0; if (O.user_black >= 0) { C.black = O.user_black; clear_repeat = 1; } for (int i = 0; i < 4; i++) if (O.user_cblack[i] > -1000000) { C.cblack[i] = O.user_cblack[i]; clear_repeat = 1; } if (clear_repeat) C.cblack[4] = C.cblack[5] = 0; // Add common part to cblack[] early if (imgdata.idata.filters > 1000 && (C.cblack[4] + 1) / 2 == 1 && (C.cblack[5] + 1) / 2 == 1) { int clrs[4]; int lastg = -1, gcnt = 0; for (int c = 0; c < 4; c++) { clrs[c] = FC(c / 2, c % 2); if (clrs[c] == 1) { gcnt++; lastg = c; } } if (gcnt > 1 && lastg >= 0) clrs[lastg] = 3; for (int c = 0; c < 4; c++) C.cblack[clrs[c]] += C.cblack[6 + c / 2 % C.cblack[4] * C.cblack[5] + c % 2 % C.cblack[5]]; C.cblack[4] = C.cblack[5] = 0; // imgdata.idata.filters = sfilters; } else if (imgdata.idata.filters <= 1000 && C.cblack[4] == 1 && C.cblack[5] == 1) // Fuji RAF dng { for (int c = 0; c < 4; c++) C.cblack[c] += C.cblack[6]; C.cblack[4] = C.cblack[5] = 0; } // remove common part from C.cblack[] int i = C.cblack[3]; int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; // remove common part C.black += i; // Now calculate common part for cblack[6+] part and move it to C.black if (C.cblack[4] && C.cblack[5]) { i = C.cblack[6]; for (c = 1; c < C.cblack[4] * C.cblack[5]; c++) if (i > C.cblack[6 + c]) i = C.cblack[6 + c]; // Remove i from cblack[6+] int nonz = 0; for (c = 0; c < C.cblack[4] * C.cblack[5]; c++) { C.cblack[6 + c] -= i; if (C.cblack[6 + c]) nonz++; } C.black += i; if (!nonz) C.cblack[4] = C.cblack[5] = 0; } for (c = 0; c < 4; c++) C.cblack[c] += C.black; } int LibRaw::dcraw_process(void) { int quality, i; int iterations = -1, dcb_enhance = 1, noiserd = 0; int eeci_refine_fl = 0, es_med_passes_fl = 0; float cared = 0, cablue = 0; float linenoise = 0; float lclean = 0, cclean = 0; float thresh = 0; float preser = 0; float expos = 1.0; CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); // CHECK_ORDER_HIGH(LIBRAW_PROGRESS_PRE_INTERPOLATE); try { int no_crop = 1; if (~O.cropbox[2] && ~O.cropbox[3]) no_crop = 0; libraw_decoder_info_t di; get_decoder_info(&di); bool is_bayer = (imgdata.idata.filters || P1.colors == 1); int subtract_inline = !O.bad_pixels && !O.dark_frame && is_bayer && !IO.zero_is_bad; raw2image_ex(subtract_inline); // allocate imgdata.image and copy data! // Adjust sizes int save_4color = O.four_color_rgb; if (IO.zero_is_bad) { remove_zeroes(); SET_PROC_FLAG(LIBRAW_PROGRESS_REMOVE_ZEROES); } if (O.bad_pixels && no_crop) { bad_pixels(O.bad_pixels); SET_PROC_FLAG(LIBRAW_PROGRESS_BAD_PIXELS); } if (O.dark_frame && no_crop) { subtract(O.dark_frame); SET_PROC_FLAG(LIBRAW_PROGRESS_DARK_FRAME); } /* pre subtract black callback: check for it above to disable subtract inline */ if(callbacks.pre_subtractblack_cb) (callbacks.pre_subtractblack_cb)(this); quality = 2 + !IO.fuji_width; if (O.user_qual >= 0) quality = O.user_qual; if (!subtract_inline || !C.data_maximum) { adjust_bl(); subtract_black_internal(); } if (!(di.decoder_flags & LIBRAW_DECODER_FIXEDMAXC)) adjust_maximum(); if (O.user_sat > 0) C.maximum = O.user_sat; if (P1.is_foveon) { if (load_raw == &LibRaw::x3f_load_raw) { // Filter out zeroes for (int i = 0; i < S.height * S.width * 4; i++) if ((short)imgdata.image[0][i] < 0) imgdata.image[0][i] = 0; } SET_PROC_FLAG(LIBRAW_PROGRESS_FOVEON_INTERPOLATE); } if (O.green_matching && !O.half_size) { green_matching(); } if(callbacks.pre_scalecolors_cb) (callbacks.pre_scalecolors_cb)(this); if (!O.no_auto_scale) { scale_colors(); SET_PROC_FLAG(LIBRAW_PROGRESS_SCALE_COLORS); } if(callbacks.pre_preinterpolate_cb) (callbacks.pre_preinterpolate_cb)(this); pre_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_PRE_INTERPOLATE); if (O.dcb_iterations >= 0) iterations = O.dcb_iterations; if (O.dcb_enhance_fl >= 0) dcb_enhance = O.dcb_enhance_fl; if (O.fbdd_noiserd >= 0) noiserd = O.fbdd_noiserd; /* pre-exposure correction callback */ if (O.exp_correc > 0) { expos = O.exp_shift; preser = O.exp_preser; exp_bef(expos, preser); } if(callbacks.pre_interpolate_cb) (callbacks.pre_interpolate_cb)(this); /* post-exposure correction fallback */ if (P1.filters && !O.no_interpolation) { if (noiserd > 0 && P1.colors == 3 && P1.filters) fbdd(noiserd); if (P1.filters > 1000 && callbacks.interpolate_bayer_cb) (callbacks.interpolate_bayer_cb)(this); else if (P1.filters == 9 && callbacks.interpolate_xtrans_cb) (callbacks.interpolate_xtrans_cb)(this); else if (quality == 0) lin_interpolate(); else if (quality == 1 || P1.colors > 3) vng_interpolate(); else if (quality == 2 && P1.filters > 1000) ppg_interpolate(); else if (P1.filters == LIBRAW_XTRANS) { // Fuji X-Trans xtrans_interpolate(quality > 2 ? 3 : 1); } else if (quality == 3) ahd_interpolate(); // really don't need it here due to fallback op else if (quality == 4) dcb(iterations, dcb_enhance); else if (quality == 11) dht_interpolate(); else if (quality == 12) aahd_interpolate(); // fallback to AHD else { ahd_interpolate(); imgdata.process_warnings |= LIBRAW_WARN_FALLBACK_TO_AHD; } SET_PROC_FLAG(LIBRAW_PROGRESS_INTERPOLATE); } if (IO.mix_green) { for (P1.colors = 3, i = 0; i < S.height * S.width; i++) imgdata.image[i][1] = (imgdata.image[i][1] + imgdata.image[i][3]) >> 1; SET_PROC_FLAG(LIBRAW_PROGRESS_MIX_GREEN); } if(callbacks.post_interpolate_cb) (callbacks.post_interpolate_cb)(this); if (!P1.is_foveon) { if (P1.colors == 3) { /* median filter callback, if not set use own */ median_filter(); SET_PROC_FLAG(LIBRAW_PROGRESS_MEDIAN_FILTER); } } if (O.highlight == 2) { blend_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.highlight > 2) { recover_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.use_fuji_rotate) { fuji_rotate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); } if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_process()"); } #ifndef NO_LCMS if (O.camera_profile) { apply_profile(O.camera_profile, O.output_profile); SET_PROC_FLAG(LIBRAW_PROGRESS_APPLY_PROFILE); } #endif if(callbacks.pre_converttorgb_cb) (callbacks.pre_converttorgb_cb)(this); convert_to_rgb(); SET_PROC_FLAG(LIBRAW_PROGRESS_CONVERT_RGB); if(callbacks.post_converttorgb_cb) (callbacks.post_converttorgb_cb)(this); if (O.use_fuji_rotate) { stretch(); SET_PROC_FLAG(LIBRAW_PROGRESS_STRETCH); } O.four_color_rgb = save_4color; // also, restore return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } // clang-format off // Supported cameras: static const char *static_camera_list[] = { "Adobe Digital Negative (DNG)", "AgfaPhoto DC-833m", "Alcatel 5035D", "Apple iPad Pro", "Apple iPhone SE", "Apple iPhone 6s", "Apple iPhone 6 plus", "Apple iPhone 7", "Apple iPhone 7 plus", "Apple iPhone 8", "Apple iPhone 8 plus", "Apple iPhone X", "Apple QuickTake 100", "Apple QuickTake 150", "Apple QuickTake 200", "ARRIRAW format", "AVT F-080C", "AVT F-145C", "AVT F-201C", "AVT F-510C", "AVT F-810C", "Baumer TXG14", "BlackMagic Cinema Camera", "BlackMagic Micro Cinema Camera", "BlackMagic Pocket Cinema Camera", "BlackMagic Production Camera 4k", "BlackMagic URSA", "BlackMagic URSA Mini 4k", "BlackMagic URSA Mini 4.6k", "BlackMagic URSA Mini Pro 4.6k", "Canon PowerShot 600", "Canon PowerShot A5", "Canon PowerShot A5 Zoom", "Canon PowerShot A50", "Canon PowerShot A410 (CHDK hack)", "Canon PowerShot A460 (CHDK hack)", "Canon PowerShot A470 (CHDK hack)", "Canon PowerShot A530 (CHDK hack)", "Canon PowerShot A540 (CHDK hack)", "Canon PowerShot A550 (CHDK hack)", "Canon PowerShot A570 (CHDK hack)", "Canon PowerShot A590 (CHDK hack)", "Canon PowerShot A610 (CHDK hack)", "Canon PowerShot A620 (CHDK hack)", "Canon PowerShot A630 (CHDK hack)", "Canon PowerShot A640 (CHDK hack)", "Canon PowerShot A650 (CHDK hack)", "Canon PowerShot A710 IS (CHDK hack)", "Canon PowerShot A720 IS (CHDK hack)", "Canon PowerShot A3300 IS (CHDK hack)", "Canon PowerShot D10 (CHDK hack)", "Canon PowerShot ELPH 130 IS (CHDK hack)", "Canon PowerShot ELPH 160 IS (CHDK hack)", "Canon PowerShot Pro70", "Canon PowerShot Pro90 IS", "Canon PowerShot Pro1", "Canon PowerShot G1", "Canon PowerShot G1 X", "Canon PowerShot G1 X Mark II", "Canon PowerShot G1 X Mark III", "Canon PowerShot G2", "Canon PowerShot G3", "Canon PowerShot G3 X", "Canon PowerShot G5", "Canon PowerShot G5 X", "Canon PowerShot G6", "Canon PowerShot G7 (CHDK hack)", "Canon PowerShot G7 X", "Canon PowerShot G7 X Mark II", "Canon PowerShot G9", "Canon PowerShot G9 X", "Canon PowerShot G9 X Mark II", "Canon PowerShot G10", "Canon PowerShot G11", "Canon PowerShot G12", "Canon PowerShot G15", "Canon PowerShot G16", "Canon PowerShot S2 IS (CHDK hack)", "Canon PowerShot S3 IS (CHDK hack)", "Canon PowerShot S5 IS (CHDK hack)", "Canon PowerShot SD300 (CHDK hack)", "Canon PowerShot SD750 (CHDK hack)", "Canon PowerShot SD950 (CHDK hack)", "Canon PowerShot S30", "Canon PowerShot S40", "Canon PowerShot S45", "Canon PowerShot S50", "Canon PowerShot S60", "Canon PowerShot S70", "Canon PowerShot S90", "Canon PowerShot S95", "Canon PowerShot S100", "Canon PowerShot S110", "Canon PowerShot S120", "Canon PowerShot SX1 IS", "Canon PowerShot SX50 HS", "Canon PowerShot SX60 HS", "Canon PowerShot SX100 IS (CHDK hack)", "Canon PowerShot SX110 IS (CHDK hack)", "Canon PowerShot SX120 IS (CHDK hack)", "Canon PowerShot SX130 IS (CHDK hack)", "Canon PowerShot SX160 IS (CHDK hack)", "Canon PowerShot SX220 HS (CHDK hack)", "Canon PowerShot SX510 HS (CHDK hack)", "Canon PowerShot SX10 IS (CHDK hack)", "Canon PowerShot SX20 IS (CHDK hack)", "Canon PowerShot SX30 IS (CHDK hack)", "Canon PowerShot IXUS 160 (CHDK hack)", "Canon PowerShot IXUS 900Ti (CHDK hack)", "Canon EOS D30", "Canon EOS D60", "Canon EOS 5D", "Canon EOS 5DS", "Canon EOS 5DS R", "Canon EOS 5D Mark II", "Canon EOS 5D Mark III", "Canon EOS 5D Mark IV", "Canon EOS 6D", "Canon EOS 6D Mark II", "Canon EOS 7D", "Canon EOS 7D Mark II", "Canon EOS 10D", "Canon EOS 20D", "Canon EOS 20Da", "Canon EOS 30D", "Canon EOS 40D", "Canon EOS 50D", "Canon EOS 60D", "Canon EOS 60Da", "Canon EOS 70D", "Canon EOS 77D", "Canon EOS 80D", "Canon EOS 200D", "Canon EOS 300D / Digital Rebel / Kiss Digital", "Canon EOS 350D / Digital Rebel XT / Kiss Digital N", "Canon EOS 400D / Digital Rebel XTi / Kiss Digital X", "Canon EOS 450D / Digital Rebel XSi / Kiss Digital X2", "Canon EOS 500D / Digital Rebel T1i / Kiss Digital X3", "Canon EOS 550D / Digital Rebel T2i / Kiss Digital X4", "Canon EOS 600D / Digital Rebel T3i / Kiss Digital X5", "Canon EOS 650D / Digital Rebel T4i / Kiss Digital X6i", "Canon EOS 700D / Digital Rebel T5i", "Canon EOS 750D / Digital Rebel T6i", "Canon EOS 760D / Digital Rebel T6S", "Canon EOS 800D", "Canon EOS 100D / Digital Rebel SL1", "Canon EOS 1000D / Digital Rebel XS / Kiss Digital F", "Canon EOS 1100D / Digital Rebel T3 / Kiss Digital X50", "Canon EOS 1200D", "Canon EOS 1300D", "Canon EOS C500", "Canon EOS D2000C", "Canon EOS M", "Canon EOS M2", "Canon EOS M3", "Canon EOS M5", "Canon EOS M6", "Canon EOS M10", "Canon EOS M100", "Canon EOS-1D", "Canon EOS-1DS", "Canon EOS-1D C", "Canon EOS-1D X", "Canon EOS-1D Mark II", "Canon EOS-1D Mark II N", "Canon EOS-1D Mark III", "Canon EOS-1D Mark IV", "Canon EOS-1Ds Mark II", "Canon EOS-1Ds Mark III", "Canon EOS-1D X Mark II", "Casio QV-2000UX", "Casio QV-3000EX", "Casio QV-3500EX", "Casio QV-4000", "Casio QV-5700", "Casio QV-R41", "Casio QV-R51", "Casio QV-R61", "Casio EX-F1", "Casio EX-FC300S", "Casio EX-FC400S", "Casio EX-FH20", "Casio EX-FH25", "Casio EX-FH100", "Casio EX-P600", "Casio EX-S20", "Casio EX-S100", "Casio EX-Z4", "Casio EX-Z50", "Casio EX-Z500", "Casio EX-Z55", "Casio EX-Z60", "Casio EX-Z75", "Casio EX-Z750", "Casio EX-Z8", "Casio EX-Z850", "Casio EX-Z1050", "Casio EX-ZR100", "Casio EX-Z1080", "Casio EX-ZR700", "Casio EX-ZR710", "Casio EX-ZR750", "Casio EX-ZR800", "Casio EX-ZR850", "Casio EX-ZR1000", "Casio EX-ZR1100", "Casio EX-ZR1200", "Casio EX-ZR1300", "Casio EX-ZR1500", "Casio EX-ZR3000", "Casio EX-ZR4000/5000", "Casio EX-ZR4100/5100", "Casio EX-100", "Casio EX-100F", "Casio EX-10", "Casio Exlim Pro 505", "Casio Exlim Pro 600", "Casio Exlim Pro 700", "Contax N Digital", "Creative PC-CAM 600", "Digital Bolex D16", "Digital Bolex D16M", "DJI 4384x3288", "DJI Phantom4 Pro/Pro+", "DJI Zenmuse X5", "DJI Zenmuse X5R", "DXO One", "Epson R-D1", "Epson R-D1s", "Epson R-D1x", "Foculus 531C", "FujiFilm E505", "FujiFilm E550", "FujiFilm E900", "FujiFilm F700", "FujiFilm F710", "FujiFilm F800", "FujiFilm F810", "FujiFilm S2Pro", "FujiFilm S3Pro", "FujiFilm S5Pro", "FujiFilm S20Pro", "FujiFilm S1", "FujiFilm S100FS", "FujiFilm S5000", "FujiFilm S5100/S5500", "FujiFilm S5200/S5600", "FujiFilm S6000fd", "FujiFilm S6500fd", "FujiFilm S7000", "FujiFilm S9000/S9500", "FujiFilm S9100/S9600", "FujiFilm S200EXR", "FujiFilm S205EXR", "FujiFilm SL1000", "FujiFilm HS10/HS11", "FujiFilm HS20EXR", "FujiFilm HS22EXR", "FujiFilm HS30EXR", "FujiFilm HS33EXR", "FujiFilm HS35EXR", "FujiFilm HS50EXR", "FujiFilm F505EXR", "FujiFilm F550EXR", "FujiFilm F600EXR", "FujiFilm F605EXR", "FujiFilm F770EXR", "FujiFilm F775EXR", "FujiFilm F800EXR", "FujiFilm F900EXR", "FujiFilm GFX 50S", "FujiFilm X-Pro1", "FujiFilm X-Pro2", "FujiFilm X-S1", "FujiFilm XQ1", "FujiFilm XQ2", "FujiFilm X100", "FujiFilm X100f", "FujiFilm X100S", "FujiFilm X100T", "FujiFilm X10", "FujiFilm X20", "FujiFilm X30", "FujiFilm X70", "FujiFilm X-A1", "FujiFilm X-A2", "FujiFilm X-A3", "FujiFilm X-A5", "FujiFilm X-A10", "FujiFilm X-A20", "FujiFilm X-E1", "FujiFilm X-E2", "FujiFilm X-E2S", "FujiFilm X-E3", "FujiFilm X-M1", "FujiFilm XF1", "FujiFilm X-H1", "FujiFilm X-T1", "FujiFilm X-T1 Graphite Silver", "FujiFilm X-T2", "FujiFilm X-T10", "FujiFilm X-T20", "FujiFilm IS-1", "Gione E7", "GITUP GIT2", "GITUP GIT2P", "Google Pixel", "Google Pixel XL", "Hasselblad H2D-22", "Hasselblad H2D-39", "Hasselblad H3DII-22", "Hasselblad H3DII-31", "Hasselblad H3DII-39", "Hasselblad H3DII-50", "Hasselblad H3D-22", "Hasselblad H3D-31", "Hasselblad H3D-39", "Hasselblad H4D-60", "Hasselblad H4D-50", "Hasselblad H4D-40", "Hasselblad H4D-31", "Hasselblad H5D-60", "Hasselblad H5D-50", "Hasselblad H5D-50c", "Hasselblad H5D-40", "Hasselblad H6D-100c", "Hasselblad A6D-100c", // Aerial camera "Hasselblad CFV", "Hasselblad CFV-50", "Hasselblad CFH", "Hasselblad CF-22", "Hasselblad CF-31", "Hasselblad CF-39", "Hasselblad V96C", "Hasselblad Lusso", "Hasselblad Lunar", "Hasselblad True Zoom", "Hasselblad Stellar", "Hasselblad Stellar II", "Hasselblad HV", "Hasselblad X1D", "HTC UltraPixel", "HTC MyTouch 4G", "HTC One (A9)", "HTC One (M9)", "HTC 10", "Huawei P9 (EVA-L09/AL00)", "Huawei Honor6a", "Huawei Honor9", "Huawei Mate10 (BLA-L29)", "Imacon Ixpress 96, 96C", "Imacon Ixpress 384, 384C (single shot only)", "Imacon Ixpress 132C", "Imacon Ixpress 528C (single shot only)", "ISG 2020x1520", "Ikonoskop A-Cam dII Panchromatic", "Ikonoskop A-Cam dII", "Kinefinity KineMINI", "Kinefinity KineRAW Mini", "Kinefinity KineRAW S35", "Kodak DC20", "Kodak DC25", "Kodak DC40", "Kodak DC50", "Kodak DC120", "Kodak DCS200", "Kodak DCS315C", "Kodak DCS330C", "Kodak DCS420", "Kodak DCS460", "Kodak DCS460A", "Kodak DCS460D", "Kodak DCS520C", "Kodak DCS560C", "Kodak DCS620C", "Kodak DCS620X", "Kodak DCS660C", "Kodak DCS660M", "Kodak DCS720X", "Kodak DCS760C", "Kodak DCS760M", "Kodak EOSDCS1", "Kodak EOSDCS3B", "Kodak NC2000F", "Kodak ProBack", "Kodak PB645C", "Kodak PB645H", "Kodak PB645M", "Kodak DCS Pro 14n", "Kodak DCS Pro 14nx", "Kodak DCS Pro SLR/c", "Kodak DCS Pro SLR/n", "Kodak C330", "Kodak C603", "Kodak P850", "Kodak P880", "Kodak S-1", "Kodak Z980", "Kodak Z981", "Kodak Z990", "Kodak Z1015", "Kodak KAI-0340", "Konica KD-400Z", "Konica KD-510Z", "Leaf AFi 5", "Leaf AFi 6", "Leaf AFi 7", "Leaf AFi-II 6", "Leaf AFi-II 7", "Leaf AFi-II 10", "Leaf AFi-II 10R", "Leaf Aptus-II 5", "Leaf Aptus-II 6", "Leaf Aptus-II 7", "Leaf Aptus-II 8", "Leaf Aptus-II 10", "Leaf Aptus-II 12", "Leaf Aptus-II 12R", "Leaf Aptus 17", "Leaf Aptus 22", "Leaf Aptus 54S", "Leaf Aptus 65", "Leaf Aptus 65S", "Leaf Aptus 75", "Leaf Aptus 75S", "Leaf Cantare", "Leaf Cantare XY", "Leaf CatchLight", "Leaf CMost", "Leaf Credo 40", "Leaf Credo 50", "Leaf Credo 60", "Leaf Credo 80 (low compression mode only)", "Leaf DCB-II", "Leaf Valeo 6", "Leaf Valeo 11", "Leaf Valeo 17", "Leaf Valeo 17wi", "Leaf Valeo 22", "Leaf Valeo 22wi", "Leaf Volare", "Lenovo a820", "Leica C (Typ 112)", "Leica CL", "Leica Digilux 2", "Leica Digilux 3", "Leica Digital-Modul-R", "Leica D-LUX2", "Leica D-LUX3", "Leica D-LUX4", "Leica D-LUX5", "Leica D-LUX6", "Leica D-Lux (Typ 109)", "Leica M8", "Leica M8.2", "Leica M9", "Leica M10", "Leica M (Typ 240)", "Leica M (Typ 262)", "Leica Monochrom (Typ 240)", "Leica Monochrom (Typ 246)", "Leica M-D (Typ 262)", "Leica M-E", "Leica M-P", "Leica R8", "Leica Q (Typ 116)", "Leica S", "Leica S2", "Leica S (Typ 007)", "Leica SL (Typ 601)", "Leica T (Typ 701)", "Leica TL", "Leica TL2", "Leica X1", "Leica X (Typ 113)", "Leica X2", "Leica X-E (Typ 102)", "Leica X-U (Typ 113)", "Leica V-LUX1", "Leica V-LUX2", "Leica V-LUX3", "Leica V-LUX4", "Leica V-Lux (Typ 114)", "Leica X VARIO (Typ 107)", "LG G3", "LG G4", "LG V20 (F800K)", "LG VS995", "Logitech Fotoman Pixtura", "Mamiya ZD", "Matrix 4608x3288", "Meizy MX4", "Micron 2010", "Minolta RD175", "Minolta DiMAGE 5", "Minolta DiMAGE 7", "Minolta DiMAGE 7i", "Minolta DiMAGE 7Hi", "Minolta DiMAGE A1", "Minolta DiMAGE A2", "Minolta DiMAGE A200", "Minolta DiMAGE G400", "Minolta DiMAGE G500", "Minolta DiMAGE G530", "Minolta DiMAGE G600", "Minolta DiMAGE Z2", "Minolta Alpha/Dynax/Maxxum 5D", "Minolta Alpha/Dynax/Maxxum 7D", "Motorola PIXL", "Nikon D1", "Nikon D1H", "Nikon D1X", "Nikon D2H", "Nikon D2Hs", "Nikon D2X", "Nikon D2Xs", "Nikon D3", "Nikon D3s", "Nikon D3X", "Nikon D4", "Nikon D4s", "Nikon D40", "Nikon D40X", "Nikon D5", "Nikon D50", "Nikon D60", "Nikon D70", "Nikon D70s", "Nikon D80", "Nikon D90", "Nikon D100", "Nikon D200", "Nikon D300", "Nikon D300s", "Nikon D500", "Nikon D600", "Nikon D610", "Nikon D700", "Nikon D750", "Nikon D800", "Nikon D800E", "Nikon D810", "Nikon D810A", "Nikon D850", "Nikon D3000", "Nikon D3100", "Nikon D3200", "Nikon D3300", "Nikon D3400", "Nikon D5000", "Nikon D5100", "Nikon D5200", "Nikon D5300", "Nikon D5500", "Nikon D5600", "Nikon D7000", "Nikon D7100", "Nikon D7200", "Nikon D7500", "Nikon Df", "Nikon 1 AW1", "Nikon 1 J1", "Nikon 1 J2", "Nikon 1 J3", "Nikon 1 J4", "Nikon 1 J5", "Nikon 1 S1", "Nikon 1 S2", "Nikon 1 V1", "Nikon 1 V2", "Nikon 1 V3", "Nikon E700 (\"DIAG RAW\" hack)", "Nikon E800 (\"DIAG RAW\" hack)", "Nikon E880 (\"DIAG RAW\" hack)", "Nikon E900 (\"DIAG RAW\" hack)", "Nikon E950 (\"DIAG RAW\" hack)", "Nikon E990 (\"DIAG RAW\" hack)", "Nikon E995 (\"DIAG RAW\" hack)", "Nikon E2100 (\"DIAG RAW\" hack)", "Nikon E2500 (\"DIAG RAW\" hack)", "Nikon E3200 (\"DIAG RAW\" hack)", "Nikon E3700 (\"DIAG RAW\" hack)", "Nikon E4300 (\"DIAG RAW\" hack)", "Nikon E4500 (\"DIAG RAW\" hack)", "Nikon E5000", "Nikon E5400", "Nikon E5700", "Nikon E8400", "Nikon E8700", "Nikon E8800", "Nikon Coolpix A", "Nikon Coolpix B700", "Nikon Coolpix P330", "Nikon Coolpix P340", "Nikon Coolpix P6000", "Nikon Coolpix P7000", "Nikon Coolpix P7100", "Nikon Coolpix P7700", "Nikon Coolpix P7800", "Nikon Coolpix S6 (\"DIAG RAW\" hack)", "Nikon Coolscan NEF", "Nokia N95", "Nokia X2", "Nokia 1200x1600", "Nokia Lumia 950 XL", "Nokia Lumia 1020", "Nokia Lumia 1520", "Olympus AIR A01", "Olympus C3030Z", "Olympus C5050Z", "Olympus C5060Z", "Olympus C7070WZ", "Olympus C70Z,C7000Z", "Olympus C740UZ", "Olympus C770UZ", "Olympus C8080WZ", "Olympus X200,D560Z,C350Z", "Olympus E-1", "Olympus E-3", "Olympus E-5", "Olympus E-10", "Olympus E-20", "Olympus E-30", "Olympus E-300", "Olympus E-330", "Olympus E-400", "Olympus E-410", "Olympus E-420", "Olympus E-450", "Olympus E-500", "Olympus E-510", "Olympus E-520", "Olympus E-600", "Olympus E-620", "Olympus E-P1", "Olympus E-P2", "Olympus E-P3", "Olympus E-P5", "Olympus E-PL1", "Olympus E-PL1s", "Olympus E-PL2", "Olympus E-PL3", "Olympus E-PL5", "Olympus E-PL6", "Olympus E-PL7", "Olympus E-PL8", "Olympus E-PL9", "Olympus E-PM1", "Olympus E-PM2", "Olympus E-M1", "Olympus E-M1 Mark II", "Olympus E-M10", "Olympus E-M10 Mark II", "Olympus E-M10 Mark III", "Olympus E-M5", "Olympus E-M5 Mark II", "Olympus Pen F", "Olympus SP310", "Olympus SP320", "Olympus SP350", "Olympus SP500UZ", "Olympus SP510UZ", "Olympus SP550UZ", "Olympus SP560UZ", "Olympus SP565UZ", "Olympus SP570UZ", "Olympus STYLUS1", "Olympus STYLUS1s", "Olympus SH-2", "Olympus SH-3", "Olympus TG-4", "Olympus TG-5", "Olympus XZ-1", "Olympus XZ-2", "Olympus XZ-10", "OmniVision 4688", "OmniVision OV5647", "OmniVision OV5648", "OmniVision OV8850", "OmniVision 13860", "OnePlus One", "OnePlus A3303", "OnePlus A5000", "Panasonic DMC-CM1", "Panasonic DMC-FZ8", "Panasonic DMC-FZ18", "Panasonic DMC-FZ28", "Panasonic DMC-FZ30", "Panasonic DMC-FZ35/FZ38", "Panasonic DMC-FZ40", "Panasonic DMC-FZ45", "Panasonic DMC-FZ50", "Panasonic DMC-FZ7", "Panasonic DMC-FZ70", "Panasonic DMC-FZ72", "Panasonic DC-FZ80/82", "Panasonic DMC-FZ100", "Panasonic DMC-FZ150", "Panasonic DMC-FZ200", "Panasonic DMC-FZ300/330", "Panasonic DMC-FZ1000", "Panasonic DMC-FZ2000/2500/FZH1", "Panasonic DMC-FX150", "Panasonic DMC-G1", "Panasonic DMC-G10", "Panasonic DMC-G2", "Panasonic DMC-G3", "Panasonic DMC-G5", "Panasonic DMC-G6", "Panasonic DMC-G7/G70", "Panasonic DMC-G8/80/81/85", "Panasonic DC-G9", "Panasonic DMC-GF1", "Panasonic DMC-GF2", "Panasonic DMC-GF3", "Panasonic DMC-GF5", "Panasonic DMC-GF6", "Panasonic DMC-GF7", "Panasonic DC-GF10/GF90", "Panasonic DMC-GH1", "Panasonic DMC-GH2", "Panasonic DMC-GH3", "Panasonic DMC-GH4", "Panasonic AG-GH4", "Panasonic DC-GH5", "Panasonic DMC-GM1", "Panasonic DMC-GM1s", "Panasonic DMC-GM5", "Panasonic DMC-GX1", "Panasonic DMC-GX7", "Panasonic DMC-GX8", "Panasonic DC-GX9", "Panasonic DMC-GX80/85", "Panasonic DC-GX800/850/GF9", "Panasonic DMC-L1", "Panasonic DMC-L10", "Panasonic DMC-LC1", "Panasonic DMC-LF1", "Panasonic DMC-LX1", "Panasonic DMC-LX2", "Panasonic DMC-LX3", "Panasonic DMC-LX5", "Panasonic DMC-LX7", "Panasonic DMC-LX9/10/15", "Panasonic DMC-LX100", "Panasonic DMC-TZ60/61/SZ40", "Panasonic DMC-TZ70/71/ZS50", "Panasonic DMC-TZ80/81/85/ZS60", "Panasonic DC-ZS70 (DC-TZ90/91/92, DC-T93)", "Panasonic DC-TZ100/101/ZS100", "Panasonic DC-TZ200/ZS200", "PARROT Bebop 2", "PARROT Bebop Drone", "Pentax *ist D", "Pentax *ist DL", "Pentax *ist DL2", "Pentax *ist DS", "Pentax *ist DS2", "Pentax GR", "Pentax K10D", "Pentax K20D", "Pentax K100D", "Pentax K100D Super", "Pentax K110D", "Pentax K200D", "Pentax K2000/K-m", "Pentax KP", "Pentax K-x", "Pentax K-r", "Pentax K-01", "Pentax K-1", "Pentax K-3", "Pentax K-3 II", "Pentax K-30", "Pentax K-5", "Pentax K-5 II", "Pentax K-5 IIs", "Pentax K-50", "Pentax K-500", "Pentax K-7", "Pentax K-70", "Pentax K-S1", "Pentax K-S2", "Pentax MX-1", "Pentax Q", "Pentax Q7", "Pentax Q10", "Pentax QS-1", "Pentax Optio S", "Pentax Optio S4", "Pentax Optio 33WR", "Pentax Optio 750Z", "Pentax 645D", "Pentax 645Z", "PhaseOne IQ140", "PhaseOne IQ150", "PhaseOne IQ160", "PhaseOne IQ180", "PhaseOne IQ180 IR", "PhaseOne IQ250", "PhaseOne IQ260", "PhaseOne IQ260 Achromatic", "PhaseOne IQ280", "PhaseOne IQ3 50MP", "PhaseOne IQ3 60MP", "PhaseOne IQ3 80MP", "PhaseOne IQ3 100MP", "PhaseOne IQ3 100MP Trichromatic", "PhaseOne LightPhase", "PhaseOne Achromatic+", "PhaseOne H 10", "PhaseOne H 20", "PhaseOne H 25", "PhaseOne P 20", "PhaseOne P 20+", "PhaseOne P 21", "PhaseOne P 25", "PhaseOne P 25+", "PhaseOne P 30", "PhaseOne P 30+", "PhaseOne P 40+", "PhaseOne P 45", "PhaseOne P 45+", "PhaseOne P 65", "PhaseOne P 65+", "Photron BC2-HD", "Pixelink A782", "Polaroid x530", "RaspberryPi Camera", "RaspberryPi Camera V2", "Ricoh GR", "Ricoh GR Digital", "Ricoh GR Digital II", "Ricoh GR Digital III", "Ricoh GR Digital IV", "Ricoh GR II", "Ricoh GX100", "Ricoh GX200", "Ricoh GXR MOUNT A12", "Ricoh GXR MOUNT A16 24-85mm F3.5-5.5", "Ricoh GXR, S10 24-72mm F2.5-4.4 VC", "Ricoh GXR, GR A12 50mm F2.5 MACRO", "Ricoh GXR, GR LENS A12 28mm F2.5", "Ricoh GXR, GXR P10", #ifndef NO_JASPER "Redcode R3D format", #endif "Rollei d530flex", "RoverShot 3320af", "Samsung EX1", "Samsung EX2F", "Samsung GX-1L", "Samsung GX-1S", "Samsung GX10", "Samsung GX20", "Samsung Galaxy Nexus", "Samsung Galaxy NX (EK-GN120)", "Samsung Galaxy S3", "Samsung Galaxy S6 (SM-G920F)", "Samsung Galaxy S7", "Samsung Galaxy S7 Edge", "Samsung Galaxy S8 (SM-G950U)", "Samsung NX1", "Samsung NX5", "Samsung NX10", "Samsung NX11", "Samsung NX100", "Samsung NX1000", "Samsung NX1100", "Samsung NX20", "Samsung NX200", "Samsung NX210", "Samsung NX2000", "Samsung NX30", "Samsung NX300", "Samsung NX300M", "Samsung NX3000", "Samsung NX500", "Samsung NX mini", "Samsung Pro815", "Samsung WB550", "Samsung WB2000", "Samsung S85 (hacked)", "Samsung S850 (hacked)", "Sarnoff 4096x5440", "Seitz 6x17", "Seitz Roundshot D3", "Seitz Roundshot D2X", "Seitz Roundshot D2Xs", "Sigma SD9 (raw decode only)", "Sigma SD10 (raw decode only)", "Sigma SD14 (raw decode only)", "Sigma SD15 (raw decode only)", "Sigma SD1", "Sigma SD1 Merill", "Sigma DP1", "Sigma DP1 Merill", "Sigma DP1S", "Sigma DP1X", "Sigma DP2", "Sigma DP2 Merill", "Sigma DP2S", "Sigma DP2X", "Sigma DP3 Merill", "Sigma dp0 Quattro", "Sigma dp1 Quattro", "Sigma dp2 Quattro", "Sigma dp3 Quattro", "Sigma sd Quattro", "Sigma sd Quattro H", "Sinar eMotion 22", "Sinar eMotion 54", "Sinar eSpirit 65", "Sinar eMotion 75", "Sinar eVolution 75", "Sinar 3072x2048", "Sinar 4080x4080", "Sinar 4080x5440", "Sinar STI format", "Sinar Sinarback 54", "SMaL Ultra-Pocket 3", "SMaL Ultra-Pocket 4", "SMaL Ultra-Pocket 5", "Sony A7", "Sony A7 II", "Sony A7R", "Sony A7R II", "Sony A7R III", "Sony A7S", "Sony A7S II", "Sony A9", "Sony ILCA-68 (A68)", "Sony ILCA-77M2 (A77-II)", "Sony ILCA-99M2 (A99-II)", "Sony ILCE-3000", "Sony ILCE-5000", "Sony ILCE-5100", "Sony ILCE-6000", "Sony ILCE-6300", "Sony ILCE-6500", "Sony ILCE-QX1", "Sony DSC-F828", "Sony DSC-R1", "Sony DSC-RX0", "Sony DSC-RX1", "Sony DSC-RX1R", "Sony DSC-RX1R II", "Sony DSC-RX10", "Sony DSC-RX10II", "Sony DSC-RX10III", "Sony DSC-RX10IV", "Sony DSC-RX100", "Sony DSC-RX100II", "Sony DSC-RX100III", "Sony DSC-RX100IV", "Sony DSC-RX100V", "Sony DSC-V3", "Sony DSLR-A100", "Sony DSLR-A200", "Sony DSLR-A230", "Sony DSLR-A290", "Sony DSLR-A300", "Sony DSLR-A330", "Sony DSLR-A350", "Sony DSLR-A380", "Sony DSLR-A390", "Sony DSLR-A450", "Sony DSLR-A500", "Sony DSLR-A550", "Sony DSLR-A560", "Sony DSLR-A580", "Sony DSLR-A700", "Sony DSLR-A850", "Sony DSLR-A900", "Sony NEX-3", "Sony NEX-3N", "Sony NEX-5", "Sony NEX-5N", "Sony NEX-5R", "Sony NEX-5T", "Sony NEX-6", "Sony NEX-7", "Sony NEX-C3", "Sony NEX-F3", "Sony NEX-VG20", "Sony NEX-VG30", "Sony NEX-VG900", "Sony SLT-A33", "Sony SLT-A35", "Sony SLT-A37", "Sony SLT-A55V", "Sony SLT-A57", "Sony SLT-A58", "Sony SLT-A65V", "Sony SLT-A77V", "Sony SLT-A99V", "Sony XCD-SX910CR", "Sony IMX135-mipi 13mp", "Sony IMX135-QCOM", "Sony IMX072-mipi", "Sony IMX214", "Sony IMX219", "Sony IMX230", "Sony IMX298-mipi 16mp", "Sony IMX219-mipi 8mp", "Sony Xperia L", "STV680 VGA", "PtGrey GRAS-50S5C", "JaiPulnix BB-500CL", "JaiPulnix BB-500GE", "SVS SVS625CL", "Yi M1", "YUNEEC CGO3", "YUNEEC CGO3P", "YUNEEC CGO4", "Xiaomi MI3", "Xiaomi RedMi Note3 Pro", "Xiaoyi YIAC3 (YI 4k)", NULL }; // clang-format on const char **LibRaw::cameraList() { return static_camera_list; } int LibRaw::cameraCount() { return (sizeof(static_camera_list) / sizeof(static_camera_list[0])) - 1; } const char *LibRaw::strprogress(enum LibRaw_progress p) { switch (p) { case LIBRAW_PROGRESS_START: return "Starting"; case LIBRAW_PROGRESS_OPEN: return "Opening file"; case LIBRAW_PROGRESS_IDENTIFY: return "Reading metadata"; case LIBRAW_PROGRESS_SIZE_ADJUST: return "Adjusting size"; case LIBRAW_PROGRESS_LOAD_RAW: return "Reading RAW data"; case LIBRAW_PROGRESS_REMOVE_ZEROES: return "Clearing zero values"; case LIBRAW_PROGRESS_BAD_PIXELS: return "Removing dead pixels"; case LIBRAW_PROGRESS_DARK_FRAME: return "Subtracting dark frame data"; case LIBRAW_PROGRESS_FOVEON_INTERPOLATE: return "Interpolating Foveon sensor data"; case LIBRAW_PROGRESS_SCALE_COLORS: return "Scaling colors"; case LIBRAW_PROGRESS_PRE_INTERPOLATE: return "Pre-interpolating"; case LIBRAW_PROGRESS_INTERPOLATE: return "Interpolating"; case LIBRAW_PROGRESS_MIX_GREEN: return "Mixing green channels"; case LIBRAW_PROGRESS_MEDIAN_FILTER: return "Median filter"; case LIBRAW_PROGRESS_HIGHLIGHTS: return "Highlight recovery"; case LIBRAW_PROGRESS_FUJI_ROTATE: return "Rotating Fuji diagonal data"; case LIBRAW_PROGRESS_FLIP: return "Flipping image"; case LIBRAW_PROGRESS_APPLY_PROFILE: return "ICC conversion"; case LIBRAW_PROGRESS_CONVERT_RGB: return "Converting to RGB"; case LIBRAW_PROGRESS_STRETCH: return "Stretching image"; case LIBRAW_PROGRESS_THUMB_LOAD: return "Loading thumbnail"; default: return "Some strange things"; } } #undef ID #include "../internal/libraw_x3f.cpp" void x3f_clear(void *p) { x3f_delete((x3f_t *)p); } void utf2char(utf16_t *str, char *buffer, unsigned bufsz) { if(bufsz<1) return; buffer[bufsz-1] = 0; char *b = buffer; while (*str != 0x00 && --bufsz>0) { char *chr = (char *)str; *b++ = *chr; str++; } *b = 0; } static void *lr_memmem(const void *l, size_t l_len, const void *s, size_t s_len) { register char *cur, *last; const char *cl = (const char *)l; const char *cs = (const char *)s; /* we need something to compare */ if (l_len == 0 || s_len == 0) return NULL; /* "s" must be smaller or equal to "l" */ if (l_len < s_len) return NULL; /* special case where s_len == 1 */ if (s_len == 1) return (void *)memchr(l, (int)*cs, l_len); /* the last position where its possible to find "s" in "l" */ last = (char *)cl + l_len - s_len; for (cur = (char *)cl; cur <= last; cur++) if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) return cur; return NULL; } void LibRaw::parse_x3f() { x3f_t *x3f = x3f_new_from_file(libraw_internal_data.internal_data.input); if (!x3f) return; _x3f_data = x3f; x3f_header_t *H = NULL; x3f_directory_section_t *DS = NULL; H = &x3f->header; // Parse RAW size from RAW section x3f_directory_entry_t *DE = x3f_get_raw(x3f); if (!DE) return; imgdata.sizes.flip = H->rotation; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.sizes.raw_width = ID->columns; imgdata.sizes.raw_height = ID->rows; // Parse other params from property section DE = x3f_get_prop(x3f); if ((x3f_load_data(x3f, DE) == X3F_OK)) { // Parse property list DEH = &DE->header; x3f_property_list_t *PL = &DEH->data_subsection.property_list; if (PL->property_table.size != 0) { int i; x3f_property_t *P = PL->property_table.element; for (i = 0; i < PL->num_properties; i++) { char name[100], value[100]; utf2char(P[i].name, name,sizeof(name)); utf2char(P[i].value, value,sizeof(value)); if (!strcmp(name, "ISO")) imgdata.other.iso_speed = atoi(value); if (!strcmp(name, "CAMMANUF")) strcpy(imgdata.idata.make, value); if (!strcmp(name, "CAMMODEL")) strcpy(imgdata.idata.model, value); if (!strcmp(name, "CAMSERIAL")) strcpy(imgdata.shootinginfo.BodySerial, value); if (!strcmp(name, "WB_DESC")) strcpy(imgdata.color.model2, value); if (!strcmp(name, "TIME")) imgdata.other.timestamp = atoi(value); if (!strcmp(name, "SHUTTER")) imgdata.other.shutter = atof(value); if (!strcmp(name, "APERTURE")) imgdata.other.aperture = atof(value); if (!strcmp(name, "FLENGTH")) imgdata.other.focal_len = atof(value); if (!strcmp(name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp(name, "IMAGERTEMP")) imgdata.other.SensorTemperature = atof(value); if (!strcmp(name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp(name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp(name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff imgdata.color.maximum = 0x3fff; // To be reset by color table libraw_internal_data.unpacker_data.order = 0x4949; } } else { // No property list if (imgdata.sizes.raw_width == 5888 || imgdata.sizes.raw_width == 2944 || imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328 || imgdata.sizes.raw_width == 5504 || imgdata.sizes.raw_width == 2752) // Quattro { imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff libraw_internal_data.unpacker_data.order = 0x4949; strcpy(imgdata.idata.make, "SIGMA"); #if 1 // Try to find model number in first 2048 bytes; int pos = libraw_internal_data.internal_data.input->tell(); libraw_internal_data.internal_data.input->seek(0, SEEK_SET); unsigned char buf[2048]; libraw_internal_data.internal_data.input->read(buf, 2048, 1); libraw_internal_data.internal_data.input->seek(pos, SEEK_SET); unsigned char *fnd = (unsigned char *)lr_memmem(buf, 2048, "SIGMA dp", 8); unsigned char *fndsd = (unsigned char *)lr_memmem(buf, 2048, "sd Quatt", 8); if (fnd) { unsigned char *nm = fnd + 8; snprintf(imgdata.idata.model, 64, "dp%c Quattro", *nm <= '9' && *nm >= '0' ? *nm : '2'); } else if (fndsd) { snprintf(imgdata.idata.model, 64, "%s", fndsd); } else #endif if (imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328) strcpy(imgdata.idata.model, "sd Quattro H"); else strcpy(imgdata.idata.model, "dp2 Quattro"); } // else } // Try to get thumbnail data LibRaw_thumbnail_formats format = LIBRAW_THUMBNAIL_UNKNOWN; if ((DE = x3f_get_thumb_jpeg(x3f))) { format = LIBRAW_THUMBNAIL_JPEG; } else if ((DE = x3f_get_thumb_plain(x3f))) { format = LIBRAW_THUMBNAIL_BITMAP; } if (DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; imgdata.thumbnail.tformat = format; libraw_internal_data.internal_data.toffset = DE->input.offset; write_thumb = &LibRaw::x3f_thumb_loader; } } INT64 LibRaw::x3f_thumb_size() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return -1; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return -1; int64_t p = x3f_load_data_size(x3f, DE); if (p < 0 || p > 0xffffffff) return -1; return p; } catch (...) { return -1; } } void LibRaw::x3f_thumb_loader() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return; if (X3F_OK != x3f_load_data(x3f, DE)) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_JPEG) { imgdata.thumbnail.thumb = (char *)malloc(ID->data_size); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); memmove(imgdata.thumbnail.thumb, ID->data, ID->data_size); imgdata.thumbnail.tlength = ID->data_size; } else if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_BITMAP) { imgdata.thumbnail.tlength = ID->columns * ID->rows * 3; imgdata.thumbnail.thumb = (char *)malloc(ID->columns * ID->rows * 3); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); char *src0 = (char *)ID->data; for (int row = 0; row < ID->rows; row++) { int offset = row * ID->row_stride; if (offset + ID->columns * 3 > ID->data_size) break; char *dest = &imgdata.thumbnail.thumb[row * ID->columns * 3]; char *src = &src0[offset]; memmove(dest, src, ID->columns * 3); } } } catch (...) { // do nothing } } static inline uint32_t _clampbits(int x, uint32_t n) { uint32_t _y_temp; if ((_y_temp = x >> n)) x = ~_y_temp >> (32 - n); return x; } void LibRaw::x3f_dpq_interpolate_rg() { int w = imgdata.sizes.raw_width / 2; int h = imgdata.sizes.raw_height / 2; unsigned short *image = (ushort *)imgdata.rawdata.color3_image; for (int color = 0; color < 2; color++) { for (int y = 2; y < (h - 2); y++) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * (y * 2) + color]; // dst[1] uint16_t row0_3 = row0[3]; uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y * 2 + 1) + color]; // dst1[1] uint16_t row1_3 = row1[3]; for (int x = 2; x < (w - 2); x++) { row1[0] = row1[3] = row0[3] = row0[0]; row0 += 6; row1 += 6; } } } } #define _ABS(a) ((a) < 0 ? -(a) : (a)) #undef CLIP #define CLIP(value, high) ((value) > (high) ? (high) : (value)) void LibRaw::x3f_dpq_interpolate_af(int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = 0; y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { if (y < imgdata.rawdata.sizes.top_margin) continue; if (y < scale) continue; if (y > imgdata.rawdata.sizes.raw_height - scale) break; uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже for (int x = 0; x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { if (x < imgdata.rawdata.sizes.left_margin) continue; if (x < scale) continue; if (x > imgdata.rawdata.sizes.raw_width - scale) break; uint16_t *pixel0 = &row0[x * 3]; uint16_t *pixel_top = &row_minus[x * 3]; uint16_t *pixel_bottom = &row_plus[x * 3]; uint16_t *pixel_left = &row0[(x - scale) * 3]; uint16_t *pixel_right = &row0[(x + scale) * 3]; uint16_t *pixf = pixel_top; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_bottom[2] - pixel0[2])) pixf = pixel_bottom; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_left[2] - pixel0[2])) pixf = pixel_left; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_right[2] - pixel0[2])) pixf = pixel_right; int blocal = pixel0[2], bnear = pixf[2]; if (blocal < imgdata.color.black + 16 || bnear < imgdata.color.black + 16) { if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; pixel0[0] = CLIP((pixel0[0] - imgdata.color.black) * 4 + imgdata.color.black, 16383); pixel0[1] = CLIP((pixel0[1] - imgdata.color.black) * 4 + imgdata.color.black, 16383); } else { float multip = float(bnear - imgdata.color.black) / float(blocal - imgdata.color.black); if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; float pixf0 = pixf[0]; if (pixf0 < imgdata.color.black) pixf0 = imgdata.color.black; float pixf1 = pixf[1]; if (pixf1 < imgdata.color.black) pixf1 = imgdata.color.black; pixel0[0] = CLIP(((float(pixf0 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[0] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); pixel0[1] = CLIP(((float(pixf1 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[1] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); // pixel0[1] = float(pixf[1]-imgdata.color.black)*multip + imgdata.color.black; } } } } void LibRaw::x3f_dpq_interpolate_af_sd(int xstart, int ystart, int xend, int yend, int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = ystart; y < yend && y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y + 1)]; // Следующая строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже AF-point (scale=2 -> ниже row1 uint16_t *row_minus1 = &image[imgdata.sizes.raw_width * 3 * (y - 1)]; for (int x = xstart; x < xend && x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { uint16_t *pixel00 = &row0[x * 3]; // Current pixel float sumR = 0.f, sumG = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumR += row_minus[(x + xx) * 3]; sumR += row_plus[(x + xx) * 3]; sumG += row_minus[(x + xx) * 3 + 1]; sumG += row_plus[(x + xx) * 3 + 1]; cnt += 1.f; if (xx) { cnt += 1.f; sumR += row0[(x + xx) * 3]; sumG += row0[(x + xx) * 3 + 1]; } } pixel00[0] = sumR / 8.f; pixel00[1] = sumG / 8.f; if (scale == 2) { uint16_t *pixel0B = &row0[x * 3 + 3]; // right pixel uint16_t *pixel1B = &row1[x * 3 + 3]; // right pixel float sumG0 = 0, sumG1 = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumG0 += row_minus1[(x + xx) * 3 + 2]; sumG1 += row_plus[(x + xx) * 3 + 2]; cnt += 1.f; if (xx) { sumG0 += row0[(x + xx) * 3 + 2]; sumG1 += row1[(x + xx) * 3 + 2]; cnt += 1.f; } } pixel0B[2] = sumG0 / cnt; pixel1B[2] = sumG1 / cnt; } // uint16_t* pixel10 = &row1[x*3]; // Pixel below current // uint16_t* pixel_bottom = &row_plus[x*3]; } } } void LibRaw::x3f_load_raw() { // already in try/catch int raise_error = 0; x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set if (X3F_OK == x3f_load_data(x3f, x3f_get_raw(x3f))) { x3f_directory_entry_t *DE = x3f_get_raw(x3f); x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_quattro_t *Q = ID->quattro; x3f_huffman_t *HUF = ID->huffman; x3f_true_t *TRU = ID->tru; uint16_t *data = NULL; if (ID->rows != S.raw_height || ID->columns != S.raw_width) { raise_error = 1; goto end; } if (HUF != NULL) data = HUF->x3rgb16.data; if (TRU != NULL) data = TRU->x3rgb16.data; if (data == NULL) { raise_error = 1; goto end; } size_t datasize = S.raw_height * S.raw_width * 3 * sizeof(unsigned short); S.raw_pitch = S.raw_width * 3 * sizeof(unsigned short); if (!(imgdata.rawdata.raw_alloc = malloc(datasize))) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (HUF) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && (!Q || !Q->quattro_layout)) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && Q) { // Move quattro data in place // R/B plane for (int prow = 0; prow < TRU->x3rgb16.rows && prow < S.raw_height / 2; prow++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[prow * 2 * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow)[3] = (unsigned short(*)[3]) & data[prow * TRU->x3rgb16.row_stride]; for (int pcol = 0; pcol < TRU->x3rgb16.columns && pcol < S.raw_width / 2; pcol++) { destrow[pcol * 2][0] = srcrow[pcol][0]; destrow[pcol * 2][1] = srcrow[pcol][1]; } } for (int row = 0; row < Q->top16.rows && row < S.raw_height; row++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[row * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow) = (unsigned short *)&Q->top16.data[row * Q->top16.columns]; for (int col = 0; col < Q->top16.columns && col < S.raw_width; col++) destrow[col][2] = srcrow[col]; } } #if 1 if (TRU && Q && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF)) { if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3672) // dpN Quattro normal { x3f_dpq_interpolate_af(32, 8, 2); } else if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3776) // sd Quattro normal raw { x3f_dpq_interpolate_af_sd(216, 464, imgdata.sizes.raw_width - 1, 3312, 16, 32, 2); } else if (imgdata.sizes.raw_width == 6656 && imgdata.sizes.raw_height == 4480) // sd Quattro H normal raw { x3f_dpq_interpolate_af_sd(232, 592, imgdata.sizes.raw_width - 1, 3920, 16, 32, 2); } else if (imgdata.sizes.raw_width == 3328 && imgdata.sizes.raw_height == 2240) // sd Quattro H half size { x3f_dpq_interpolate_af_sd(116, 296, imgdata.sizes.raw_width - 1, 2200, 8, 16, 1); } else if (imgdata.sizes.raw_width == 5504 && imgdata.sizes.raw_height == 3680) // sd Quattro H APS-C raw { x3f_dpq_interpolate_af_sd(8, 192, imgdata.sizes.raw_width - 1, 3185, 16, 32, 2); } else if (imgdata.sizes.raw_width == 2752 && imgdata.sizes.raw_height == 1840) // sd Quattro H APS-C half size { x3f_dpq_interpolate_af_sd(4, 96, imgdata.sizes.raw_width - 1, 1800, 8, 16, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1836) // dpN Quattro small raw { x3f_dpq_interpolate_af(16, 4, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1888) // sd Quattro small { x3f_dpq_interpolate_af_sd(108, 232, imgdata.sizes.raw_width - 1, 1656, 8, 16, 1); } } #endif if (TRU && Q && Q->quattro_layout && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATERG)) x3f_dpq_interpolate_rg(); } else raise_error = 1; end: if (raise_error) throw LIBRAW_EXCEPTION_IO_CORRUPT; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_93_0
crossvul-cpp_data_good_4256_4
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ESTreeIRGen.h" #include "llvh/ADT/StringSet.h" #include "llvh/Support/Debug.h" #include "llvh/Support/SaveAndRestore.h" namespace hermes { namespace irgen { //===----------------------------------------------------------------------===// // Free standing helpers. Instruction *emitLoad(IRBuilder &builder, Value *from, bool inhibitThrow) { if (auto *var = llvh::dyn_cast<Variable>(from)) { if (Variable::declKindNeedsTDZ(var->getDeclKind()) && var->getRelatedVariable()) { builder.createThrowIfUndefinedInst( builder.createLoadFrameInst(var->getRelatedVariable())); } return builder.createLoadFrameInst(var); } else if (auto *globalProp = llvh::dyn_cast<GlobalObjectProperty>(from)) { if (globalProp->isDeclared() || inhibitThrow) return builder.createLoadPropertyInst( builder.getGlobalObject(), globalProp->getName()); else return builder.createTryLoadGlobalPropertyInst(globalProp); } else { llvm_unreachable("unvalid value to load from"); } } Instruction * emitStore(IRBuilder &builder, Value *storedValue, Value *ptr, bool declInit) { if (auto *var = llvh::dyn_cast<Variable>(ptr)) { if (!declInit && Variable::declKindNeedsTDZ(var->getDeclKind()) && var->getRelatedVariable()) { // Must verify whether the variable is initialized. builder.createThrowIfUndefinedInst( builder.createLoadFrameInst(var->getRelatedVariable())); } auto *store = builder.createStoreFrameInst(storedValue, var); if (declInit && Variable::declKindNeedsTDZ(var->getDeclKind()) && var->getRelatedVariable()) { builder.createStoreFrameInst( builder.getLiteralBool(true), var->getRelatedVariable()); } return store; } else if (auto *globalProp = llvh::dyn_cast<GlobalObjectProperty>(ptr)) { if (globalProp->isDeclared() || !builder.getFunction()->isStrictMode()) return builder.createStorePropertyInst( storedValue, builder.getGlobalObject(), globalProp->getName()); else return builder.createTryStoreGlobalPropertyInst(storedValue, globalProp); } else { llvm_unreachable("unvalid value to load from"); } } /// \returns true if \p node is a constant expression. bool isConstantExpr(ESTree::Node *node) { // TODO: a little more agressive constant folding. switch (node->getKind()) { case ESTree::NodeKind::StringLiteral: case ESTree::NodeKind::NumericLiteral: case ESTree::NodeKind::NullLiteral: case ESTree::NodeKind::BooleanLiteral: return true; default: return false; } } //===----------------------------------------------------------------------===// // LReference IRBuilder &LReference::getBuilder() { return irgen_->Builder; } Value *LReference::emitLoad() { auto &builder = getBuilder(); IRBuilder::ScopedLocationChange slc(builder, loadLoc_); switch (kind_) { case Kind::Empty: assert(false && "empty cannot be loaded"); return builder.getLiteralUndefined(); case Kind::Member: return builder.createLoadPropertyInst(base_, property_); case Kind::VarOrGlobal: return irgen::emitLoad(builder, base_); case Kind::Destructuring: assert(false && "destructuring cannot be loaded"); return builder.getLiteralUndefined(); case Kind::Error: return builder.getLiteralUndefined(); } llvm_unreachable("invalid LReference kind"); } void LReference::emitStore(Value *value) { auto &builder = getBuilder(); switch (kind_) { case Kind::Empty: return; case Kind::Member: builder.createStorePropertyInst(value, base_, property_); return; case Kind::VarOrGlobal: irgen::emitStore(builder, value, base_, declInit_); return; case Kind::Error: return; case Kind::Destructuring: return irgen_->emitDestructuringAssignment( declInit_, destructuringTarget_, value); } llvm_unreachable("invalid LReference kind"); } bool LReference::canStoreWithoutSideEffects() const { return kind_ == Kind::VarOrGlobal && llvh::isa<Variable>(base_); } Variable *LReference::castAsVariable() const { return kind_ == Kind::VarOrGlobal ? dyn_cast_or_null<Variable>(base_) : nullptr; } GlobalObjectProperty *LReference::castAsGlobalObjectProperty() const { return kind_ == Kind::VarOrGlobal ? dyn_cast_or_null<GlobalObjectProperty>(base_) : nullptr; } //===----------------------------------------------------------------------===// // ESTreeIRGen ESTreeIRGen::ESTreeIRGen( ESTree::Node *root, const DeclarationFileListTy &declFileList, Module *M, const ScopeChain &scopeChain) : Mod(M), Builder(Mod), instrumentIR_(M, Builder), Root(root), DeclarationFileList(declFileList), lexicalScopeChain(resolveScopeIdentifiers(scopeChain)), identEval_(Builder.createIdentifier("eval")), identLet_(Builder.createIdentifier("let")), identDefaultExport_(Builder.createIdentifier("?default")) {} void ESTreeIRGen::doIt() { LLVM_DEBUG(dbgs() << "Processing top level program.\n"); ESTree::ProgramNode *Program; Program = llvh::dyn_cast<ESTree::ProgramNode>(Root); if (!Program) { Builder.getModule()->getContext().getSourceErrorManager().error( SMLoc{}, "missing 'Program' AST node"); return; } LLVM_DEBUG(dbgs() << "Found Program decl.\n"); // The function which will "execute" the module. Function *topLevelFunction; // Function context used only when compiling in an existing lexical scope // chain. It is only initialized if we have a lexical scope chain. llvh::Optional<FunctionContext> wrapperFunctionContext{}; if (!lexicalScopeChain) { topLevelFunction = Builder.createTopLevelFunction( ESTree::isStrict(Program->strictness), Program->getSourceRange()); } else { // If compiling in an existing lexical context, we need to install the // scopes in a wrapper function, which represents the "global" code. Function *wrapperFunction = Builder.createFunction( "", Function::DefinitionKind::ES5Function, ESTree::isStrict(Program->strictness), Program->getSourceRange(), true); // Initialize the wrapper context. wrapperFunctionContext.emplace(this, wrapperFunction, nullptr); // Populate it with dummy code so it doesn't crash the back-end. genDummyFunction(wrapperFunction); // Restore the previously saved parent scopes. materializeScopesInChain(wrapperFunction, lexicalScopeChain, -1); // Finally create the function which will actually be executed. topLevelFunction = Builder.createFunction( "eval", Function::DefinitionKind::ES5Function, ESTree::isStrict(Program->strictness), Program->getSourceRange(), false); } Mod->setTopLevelFunction(topLevelFunction); // Function context for topLevelFunction. FunctionContext topLevelFunctionContext{ this, topLevelFunction, Program->getSemInfo()}; // IRGen needs a pointer to the outer-most context, which is either // topLevelContext or wrapperFunctionContext, depending on whether the latter // was created. // We want to set the pointer to that outer-most context, but ensure that it // doesn't outlive the context it is pointing to. llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext( topLevelContext, !wrapperFunctionContext.hasValue() ? &topLevelFunctionContext : &wrapperFunctionContext.getValue()); // Now declare all externally supplied global properties, but only if we don't // have a lexical scope chain. if (!lexicalScopeChain) { for (auto declFile : DeclarationFileList) { processDeclarationFile(declFile); } } emitFunctionPrologue( Program, Builder.createBasicBlock(topLevelFunction), InitES5CaptureState::Yes, DoEmitParameters::Yes); Value *retVal; { // Allocate the return register, initialize it to undefined. curFunction()->globalReturnRegister = Builder.createAllocStackInst(genAnonymousLabelName("ret")); Builder.createStoreStackInst( Builder.getLiteralUndefined(), curFunction()->globalReturnRegister); genBody(Program->_body); // Terminate the top-level scope with a return statement. retVal = Builder.createLoadStackInst(curFunction()->globalReturnRegister); } emitFunctionEpilogue(retVal); } void ESTreeIRGen::doCJSModule( Function *topLevelFunction, sem::FunctionInfo *semInfo, uint32_t id, llvh::StringRef filename) { assert(Root && "no root in ESTreeIRGen"); auto *func = cast<ESTree::FunctionExpressionNode>(Root); assert(func && "doCJSModule without a module"); FunctionContext topLevelFunctionContext{this, topLevelFunction, semInfo}; llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext( topLevelContext, &topLevelFunctionContext); // Now declare all externally supplied global properties, but only if we don't // have a lexical scope chain. assert( !lexicalScopeChain && "Lexical scope chain not supported for CJS modules"); for (auto declFile : DeclarationFileList) { processDeclarationFile(declFile); } Identifier functionName = Builder.createIdentifier("cjs_module"); Function *newFunc = genES5Function(functionName, nullptr, func); Builder.getModule()->addCJSModule( id, Builder.createIdentifier(filename), newFunc); } static int getDepth(const std::shared_ptr<SerializedScope> chain) { int depth = 0; const SerializedScope *current = chain.get(); while (current) { depth += 1; current = current->parentScope.get(); } return depth; } std::pair<Function *, Function *> ESTreeIRGen::doLazyFunction( hbc::LazyCompilationData *lazyData) { // Create a top level function that will never be executed, because: // 1. IRGen assumes the first function always has global scope // 2. It serves as the root for dummy functions for lexical data Function *topLevel = Builder.createTopLevelFunction(lazyData->strictMode, {}); FunctionContext topLevelFunctionContext{this, topLevel, nullptr}; // Save the top-level context, but ensure it doesn't outlive what it is // pointing to. llvh::SaveAndRestore<FunctionContext *> saveTopLevelContext( topLevelContext, &topLevelFunctionContext); auto *node = cast<ESTree::FunctionLikeNode>(Root); // We restore scoping information in two separate ways: // 1. By adding them to ExternalScopes for resolution here // 2. By adding dummy functions for lexical scoping debug info later // // Instruction selection determines the delta between the ExternalScope // and the dummy function chain, so we add the ExternalScopes with // positive depth. lexicalScopeChain = lazyData->parentScope; materializeScopesInChain( topLevel, lexicalScopeChain, getDepth(lexicalScopeChain) - 1); // If lazyData->closureAlias is specified, we must create an alias binding // between originalName (which must be valid) and the variable identified by // closureAlias. Variable *parentVar = nullptr; if (lazyData->closureAlias.isValid()) { assert(lazyData->originalName.isValid() && "Original name invalid"); assert( lazyData->originalName != lazyData->closureAlias && "Original name must be different from the alias"); // NOTE: the closureAlias target must exist and must be a Variable. parentVar = cast<Variable>(nameTable_.lookup(lazyData->closureAlias)); // Re-create the alias. nameTable_.insert(lazyData->originalName, parentVar); } assert( !llvh::isa<ESTree::ArrowFunctionExpressionNode>(node) && "lazy compilation not supported for arrow functions"); auto *func = genES5Function( lazyData->originalName, parentVar, node, lazyData->isGeneratorInnerFunction); addLexicalDebugInfo(func, topLevel, lexicalScopeChain); return {func, topLevel}; } std::pair<Value *, bool> ESTreeIRGen::declareVariableOrGlobalProperty( Function *inFunc, VarDecl::Kind declKind, Identifier name) { Value *found = nameTable_.lookup(name); // If the variable is already declared in this scope, do not create a // second instance. if (found) { if (auto *var = llvh::dyn_cast<Variable>(found)) { if (var->getParent()->getFunction() == inFunc) return {found, false}; } else { assert( llvh::isa<GlobalObjectProperty>(found) && "Invalid value found in name table"); if (inFunc->isGlobalScope()) return {found, false}; } } // Create a property if global scope, variable otherwise. Value *res; if (inFunc->isGlobalScope() && declKind == VarDecl::Kind::Var) { res = Builder.createGlobalObjectProperty(name, true); } else { Variable::DeclKind vdc; if (declKind == VarDecl::Kind::Let) vdc = Variable::DeclKind::Let; else if (declKind == VarDecl::Kind::Const) vdc = Variable::DeclKind::Const; else { assert(declKind == VarDecl::Kind::Var); vdc = Variable::DeclKind::Var; } auto *var = Builder.createVariable(inFunc->getFunctionScope(), vdc, name); // For "let" and "const" create the related TDZ flag. if (Variable::declKindNeedsTDZ(vdc) && Mod->getContext().getCodeGenerationSettings().enableTDZ) { llvh::SmallString<32> strBuf{"tdz$"}; strBuf.append(name.str()); auto *related = Builder.createVariable( var->getParent(), Variable::DeclKind::Var, genAnonymousLabelName(strBuf)); var->setRelatedVariable(related); related->setRelatedVariable(var); } res = var; } // Register the variable in the scoped hash table. nameTable_.insert(name, res); return {res, true}; } GlobalObjectProperty *ESTreeIRGen::declareAmbientGlobalProperty( Identifier name) { // Avoid redefining global properties. auto *prop = dyn_cast_or_null<GlobalObjectProperty>(nameTable_.lookup(name)); if (prop) return prop; LLVM_DEBUG( llvh::dbgs() << "declaring ambient global property " << name << " " << name.getUnderlyingPointer() << "\n"); prop = Builder.createGlobalObjectProperty(name, false); nameTable_.insertIntoScope(&topLevelContext->scope, name, prop); return prop; } namespace { /// This visitor structs collects declarations within a single closure without /// descending into child closures. struct DeclHoisting { /// The list of collected identifiers (variables and functions). llvh::SmallVector<ESTree::VariableDeclaratorNode *, 8> decls{}; /// A list of functions that need to be hoisted and materialized before we /// can generate the rest of the function. llvh::SmallVector<ESTree::FunctionDeclarationNode *, 8> closures; explicit DeclHoisting() = default; ~DeclHoisting() = default; /// Extract the variable name from the nodes that can define new variables. /// The nodes that can define a new variable in the scope are: /// VariableDeclarator and FunctionDeclaration> void collectDecls(ESTree::Node *V) { if (auto VD = llvh::dyn_cast<ESTree::VariableDeclaratorNode>(V)) { return decls.push_back(VD); } if (auto FD = llvh::dyn_cast<ESTree::FunctionDeclarationNode>(V)) { return closures.push_back(FD); } } bool shouldVisit(ESTree::Node *V) { // Collect declared names, even if we don't descend into children nodes. collectDecls(V); // Do not descend to child closures because the variables they define are // not exposed to the outside function. if (llvh::isa<ESTree::FunctionDeclarationNode>(V) || llvh::isa<ESTree::FunctionExpressionNode>(V) || llvh::isa<ESTree::ArrowFunctionExpressionNode>(V)) return false; return true; } void enter(ESTree::Node *V) {} void leave(ESTree::Node *V) {} }; } // anonymous namespace. void ESTreeIRGen::processDeclarationFile(ESTree::ProgramNode *programNode) { auto Program = dyn_cast_or_null<ESTree::ProgramNode>(programNode); if (!Program) return; DeclHoisting DH; Program->visit(DH); // Create variable declarations for each of the hoisted variables. for (auto vd : DH.decls) declareAmbientGlobalProperty(getNameFieldFromID(vd->_id)); for (auto fd : DH.closures) declareAmbientGlobalProperty(getNameFieldFromID(fd->_id)); } Value *ESTreeIRGen::ensureVariableExists(ESTree::IdentifierNode *id) { assert(id && "id must be a valid Identifier node"); Identifier name = getNameFieldFromID(id); // Check if this is a known variable. if (auto *var = nameTable_.lookup(name)) return var; if (curFunction()->function->isStrictMode()) { // Report a warning in strict mode. auto currentFunc = Builder.getInsertionBlock()->getParent(); Builder.getModule()->getContext().getSourceErrorManager().warning( Warning::UndefinedVariable, id->getSourceRange(), Twine("the variable \"") + name.str() + "\" was not declared in " + currentFunc->getDescriptiveDefinitionKindStr() + " \"" + currentFunc->getInternalNameStr() + "\""); } // Undeclared variable is an ambient global property. return declareAmbientGlobalProperty(name); } Value *ESTreeIRGen::genMemberExpressionProperty( ESTree::MemberExpressionLikeNode *Mem) { // If computed is true, the node corresponds to a computed (a[b]) member // lookup and '_property' is an Expression. Otherwise, the node // corresponds to a static (a.b) member lookup and '_property' is an // Identifier. // Details of the computed field are available here: // https://github.com/estree/estree/blob/master/spec.md#memberexpression if (getComputed(Mem)) { return genExpression(getProperty(Mem)); } // Arrays and objects may be accessed with integer indices. if (auto N = llvh::dyn_cast<ESTree::NumericLiteralNode>(getProperty(Mem))) { return Builder.getLiteralNumber(N->_value); } // ESTree encodes property access as MemberExpression -> Identifier. auto Id = cast<ESTree::IdentifierNode>(getProperty(Mem)); Identifier fieldName = getNameFieldFromID(Id); LLVM_DEBUG( dbgs() << "Emitting direct label access to field '" << fieldName << "'\n"); return Builder.getLiteralString(fieldName); } bool ESTreeIRGen::canCreateLRefWithoutSideEffects( hermes::ESTree::Node *target) { // Check for an identifier bound to an existing local variable. if (auto *iden = llvh::dyn_cast<ESTree::IdentifierNode>(target)) { return dyn_cast_or_null<Variable>( nameTable_.lookup(getNameFieldFromID(iden))); } return false; } LReference ESTreeIRGen::createLRef(ESTree::Node *node, bool declInit) { SMLoc sourceLoc = node->getDebugLoc(); IRBuilder::ScopedLocationChange slc(Builder, sourceLoc); if (llvh::isa<ESTree::EmptyNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for EmptyNode.\n"); return LReference( LReference::Kind::Empty, this, false, nullptr, nullptr, sourceLoc); } /// Create lref for member expression (ex: o.f). if (auto *ME = llvh::dyn_cast<ESTree::MemberExpressionNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for member expression.\n"); Value *obj = genExpression(ME->_object); Value *prop = genMemberExpressionProperty(ME); return LReference( LReference::Kind::Member, this, false, obj, prop, sourceLoc); } /// Create lref for identifiers (ex: a). if (auto *iden = llvh::dyn_cast<ESTree::IdentifierNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for identifier.\n"); LLVM_DEBUG( dbgs() << "Looking for identifier \"" << getNameFieldFromID(iden) << "\"\n"); auto *var = ensureVariableExists(iden); return LReference( LReference::Kind::VarOrGlobal, this, declInit, var, nullptr, sourceLoc); } /// Create lref for variable decls (ex: var a). if (auto *V = llvh::dyn_cast<ESTree::VariableDeclarationNode>(node)) { LLVM_DEBUG(dbgs() << "Creating an LRef for variable declaration.\n"); assert(V->_declarations.size() == 1 && "Malformed variable declaration"); auto *decl = cast<ESTree::VariableDeclaratorNode>(&V->_declarations.front()); return createLRef(decl->_id, true); } // Destructuring assignment. if (auto *pat = llvh::dyn_cast<ESTree::PatternNode>(node)) { return LReference(this, declInit, pat); } Builder.getModule()->getContext().getSourceErrorManager().error( node->getSourceRange(), "unsupported assignment target"); return LReference( LReference::Kind::Error, this, false, nullptr, nullptr, sourceLoc); } Value *ESTreeIRGen::genHermesInternalCall( StringRef name, Value *thisValue, ArrayRef<Value *> args) { return Builder.createCallInst( Builder.createLoadPropertyInst( Builder.createTryLoadGlobalPropertyInst("HermesInternal"), name), thisValue, args); } Value *ESTreeIRGen::genBuiltinCall( hermes::BuiltinMethod::Enum builtinIndex, ArrayRef<Value *> args) { return Builder.createCallBuiltinInst(builtinIndex, args); } void ESTreeIRGen::emitEnsureObject(Value *value, StringRef message) { // TODO: use "thisArg" when builtins get fixed to support it. genBuiltinCall( BuiltinMethod::HermesBuiltin_ensureObject, {value, Builder.getLiteralString(message)}); } Value *ESTreeIRGen::emitIteratorSymbol() { // FIXME: use the builtin value of @@iterator. Symbol could have been // overridden. return Builder.createLoadPropertyInst( Builder.createTryLoadGlobalPropertyInst("Symbol"), "iterator"); } ESTreeIRGen::IteratorRecordSlow ESTreeIRGen::emitGetIteratorSlow(Value *obj) { auto *method = Builder.createLoadPropertyInst(obj, emitIteratorSymbol()); auto *iterator = Builder.createCallInst(method, obj, {}); emitEnsureObject(iterator, "iterator is not an object"); auto *nextMethod = Builder.createLoadPropertyInst(iterator, "next"); return {iterator, nextMethod}; } Value *ESTreeIRGen::emitIteratorNextSlow(IteratorRecordSlow iteratorRecord) { auto *nextResult = Builder.createCallInst( iteratorRecord.nextMethod, iteratorRecord.iterator, {}); emitEnsureObject(nextResult, "iterator.next() did not return an object"); return nextResult; } Value *ESTreeIRGen::emitIteratorCompleteSlow(Value *iterResult) { return Builder.createLoadPropertyInst(iterResult, "done"); } Value *ESTreeIRGen::emitIteratorValueSlow(Value *iterResult) { return Builder.createLoadPropertyInst(iterResult, "value"); } void ESTreeIRGen::emitIteratorCloseSlow( hermes::irgen::ESTreeIRGen::IteratorRecordSlow iteratorRecord, bool ignoreInnerException) { auto *haveReturn = Builder.createBasicBlock(Builder.getFunction()); auto *noReturn = Builder.createBasicBlock(Builder.getFunction()); auto *returnMethod = genBuiltinCall( BuiltinMethod::HermesBuiltin_getMethod, {iteratorRecord.iterator, Builder.getLiteralString("return")}); Builder.createCompareBranchInst( returnMethod, Builder.getLiteralUndefined(), BinaryOperatorInst::OpKind::StrictlyEqualKind, noReturn, haveReturn); Builder.setInsertionBlock(haveReturn); if (ignoreInnerException) { emitTryCatchScaffolding( noReturn, // emitBody. [this, returnMethod, &iteratorRecord]() { Builder.createCallInst(returnMethod, iteratorRecord.iterator, {}); }, // emitNormalCleanup. []() {}, // emitHandler. [this](BasicBlock *nextBlock) { // We need to catch the exception, even if we don't used it. Builder.createCatchInst(); Builder.createBranchInst(nextBlock); }); } else { auto *innerResult = Builder.createCallInst(returnMethod, iteratorRecord.iterator, {}); emitEnsureObject(innerResult, "iterator.return() did not return an object"); Builder.createBranchInst(noReturn); } Builder.setInsertionBlock(noReturn); } ESTreeIRGen::IteratorRecord ESTreeIRGen::emitGetIterator(Value *obj) { // Each of these will be modified by "next", so we use a stack storage. auto *iterStorage = Builder.createAllocStackInst(genAnonymousLabelName("iter")); auto *sourceOrNext = Builder.createAllocStackInst(genAnonymousLabelName("sourceOrNext")); Builder.createStoreStackInst(obj, sourceOrNext); auto *iter = Builder.createIteratorBeginInst(sourceOrNext); Builder.createStoreStackInst(iter, iterStorage); return IteratorRecord{iterStorage, sourceOrNext}; } void ESTreeIRGen::emitDestructuringAssignment( bool declInit, ESTree::PatternNode *target, Value *source) { if (auto *APN = llvh::dyn_cast<ESTree::ArrayPatternNode>(target)) return emitDestructuringArray(declInit, APN, source); else if (auto *OPN = llvh::dyn_cast<ESTree::ObjectPatternNode>(target)) return emitDestructuringObject(declInit, OPN, source); else { Mod->getContext().getSourceErrorManager().error( target->getSourceRange(), "unsupported destructuring target"); } } void ESTreeIRGen::emitDestructuringArray( bool declInit, ESTree::ArrayPatternNode *targetPat, Value *source) { const IteratorRecord iteratorRecord = emitGetIterator(source); /// iteratorDone = undefined. auto *iteratorDone = Builder.createAllocStackInst(genAnonymousLabelName("iterDone")); Builder.createStoreStackInst(Builder.getLiteralUndefined(), iteratorDone); auto *value = Builder.createAllocStackInst(genAnonymousLabelName("iterValue")); SharedExceptionHandler handler{}; handler.exc = Builder.createAllocStackInst(genAnonymousLabelName("exc")); // All exception handlers branch to this block. handler.exceptionBlock = Builder.createBasicBlock(Builder.getFunction()); bool first = true; bool emittedRest = false; // The LReference created in the previous iteration of the destructuring // loop. We need it because we want to put the previous store and the creation // of the next LReference under one try block. llvh::Optional<LReference> lref; /// If the previous LReference is valid and non-empty, store "value" into /// it and reset the LReference. auto storePreviousValue = [&lref, &handler, this, value]() { if (lref && !lref->isEmpty()) { if (lref->canStoreWithoutSideEffects()) { lref->emitStore(Builder.createLoadStackInst(value)); } else { // If we can't store without side effects, wrap the store in try/catch. emitTryWithSharedHandler(&handler, [this, &lref, value]() { lref->emitStore(Builder.createLoadStackInst(value)); }); } lref.reset(); } }; for (auto &elem : targetPat->_elements) { ESTree::Node *target = &elem; ESTree::Node *init = nullptr; if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(target)) { storePreviousValue(); emitRestElement(declInit, rest, iteratorRecord, iteratorDone, &handler); emittedRest = true; break; } // If we have an initializer, unwrap it. if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(target)) { target = assign->_left; init = assign->_right; } // Can we create the new LReference without side effects and avoid a // try/catch. The complexity comes from having to check whether the last // LReference also can avoid a try/catch or not. if (canCreateLRefWithoutSideEffects(target)) { // We don't need a try/catch, but last lref might. Just let the routine // do the right thing. storePreviousValue(); lref = createLRef(target, declInit); } else { // We need a try/catch, but last lref might not. If it doesn't, emit it // directly and clear it, so we won't do anything inside our try/catch. if (lref && lref->canStoreWithoutSideEffects()) { lref->emitStore(Builder.createLoadStackInst(value)); lref.reset(); } emitTryWithSharedHandler( &handler, [this, &lref, value, target, declInit]() { // Store the previous value, if we have one. if (lref && !lref->isEmpty()) lref->emitStore(Builder.createLoadStackInst(value)); lref = createLRef(target, declInit); }); } // Pseudocode of the algorithm for a step: // // value = undefined; // if (iteratorDone) goto nextBlock // notDoneBlock: // stepResult = IteratorNext(iteratorRecord) // stepDone = IteratorComplete(stepResult) // iteratorDone = stepDone // if (stepDone) goto nextBlock // newValueBlock: // value = IteratorValue(stepResult) // nextBlock: // if (value !== undefined) goto storeBlock [if initializer present] // value = initializer [if initializer present] // storeBlock: // lref.emitStore(value) auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *newValueBlock = Builder.createBasicBlock(Builder.getFunction()); auto *nextBlock = Builder.createBasicBlock(Builder.getFunction()); auto *getDefaultBlock = init ? Builder.createBasicBlock(Builder.getFunction()) : nullptr; auto *storeBlock = init ? Builder.createBasicBlock(Builder.getFunction()) : nullptr; Builder.createStoreStackInst(Builder.getLiteralUndefined(), value); // In the first iteration we know that "done" is false. if (first) { first = false; Builder.createBranchInst(notDoneBlock); } else { Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), nextBlock, notDoneBlock); } // notDoneBlock: Builder.setInsertionBlock(notDoneBlock); auto *stepValue = emitIteratorNext(iteratorRecord); auto *stepDone = emitIteratorComplete(iteratorRecord); Builder.createStoreStackInst(stepDone, iteratorDone); Builder.createCondBranchInst( stepDone, init ? getDefaultBlock : nextBlock, newValueBlock); // newValueBlock: Builder.setInsertionBlock(newValueBlock); Builder.createStoreStackInst(stepValue, value); Builder.createBranchInst(nextBlock); // nextBlock: Builder.setInsertionBlock(nextBlock); // NOTE: we can't use emitOptionalInitializationHere() because we want to // be able to jump directly to getDefaultBlock. if (init) { // if (value !== undefined) goto storeBlock [if initializer present] // value = initializer [if initializer present] // storeBlock: Builder.createCondBranchInst( Builder.createBinaryOperatorInst( Builder.createLoadStackInst(value), Builder.getLiteralUndefined(), BinaryOperatorInst::OpKind::StrictlyNotEqualKind), storeBlock, getDefaultBlock); Identifier nameHint = llvh::isa<ESTree::IdentifierNode>(target) ? getNameFieldFromID(target) : Identifier{}; // getDefaultBlock: Builder.setInsertionBlock(getDefaultBlock); Builder.createStoreStackInst(genExpression(init, nameHint), value); Builder.createBranchInst(storeBlock); // storeBlock: Builder.setInsertionBlock(storeBlock); } } storePreviousValue(); // If in the end the iterator is not done, close it. We only need to do // that if we didn't end with a rest element because it would have exhausted // the iterator. if (!emittedRest) { auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *doneBlock = Builder.createBasicBlock(Builder.getFunction()); Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock); Builder.setInsertionBlock(notDoneBlock); emitIteratorClose(iteratorRecord, false); Builder.createBranchInst(doneBlock); Builder.setInsertionBlock(doneBlock); } // If we emitted at least one try block, generate the exception handler. if (handler.emittedTry) { IRBuilder::SaveRestore saveRestore{Builder}; Builder.setInsertionBlock(handler.exceptionBlock); auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *doneBlock = Builder.createBasicBlock(Builder.getFunction()); Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock); Builder.setInsertionBlock(notDoneBlock); emitIteratorClose(iteratorRecord, true); Builder.createBranchInst(doneBlock); Builder.setInsertionBlock(doneBlock); Builder.createThrowInst(Builder.createLoadStackInst(handler.exc)); } else { // If we didn't use the exception block, we need to delete it, otherwise // it fails IR validation even though it will be never executed. handler.exceptionBlock->eraseFromParent(); // Delete the not needed exception stack allocation. It would be optimized // out later, but it is nice to produce cleaner non-optimized IR, if it is // easy to do so. assert( !handler.exc->hasUsers() && "should not have any users if no try/catch was emitted"); handler.exc->eraseFromParent(); } } void ESTreeIRGen::emitRestElement( bool declInit, ESTree::RestElementNode *rest, hermes::irgen::ESTreeIRGen::IteratorRecord iteratorRecord, hermes::AllocStackInst *iteratorDone, SharedExceptionHandler *handler) { // 13.3.3.8 BindingRestElement:...BindingIdentifier auto *notDoneBlock = Builder.createBasicBlock(Builder.getFunction()); auto *newValueBlock = Builder.createBasicBlock(Builder.getFunction()); auto *doneBlock = Builder.createBasicBlock(Builder.getFunction()); llvh::Optional<LReference> lref; if (canCreateLRefWithoutSideEffects(rest->_argument)) { lref = createLRef(rest->_argument, declInit); } else { emitTryWithSharedHandler(handler, [this, &lref, rest, declInit]() { lref = createLRef(rest->_argument, declInit); }); } auto *A = Builder.createAllocArrayInst({}, 0); auto *n = Builder.createAllocStackInst(genAnonymousLabelName("n")); // n = 0. Builder.createStoreStackInst(Builder.getLiteralPositiveZero(), n); Builder.createCondBranchInst( Builder.createLoadStackInst(iteratorDone), doneBlock, notDoneBlock); // notDoneBlock: Builder.setInsertionBlock(notDoneBlock); auto *stepValue = emitIteratorNext(iteratorRecord); auto *stepDone = emitIteratorComplete(iteratorRecord); Builder.createStoreStackInst(stepDone, iteratorDone); Builder.createCondBranchInst(stepDone, doneBlock, newValueBlock); // newValueBlock: Builder.setInsertionBlock(newValueBlock); auto *nVal = Builder.createLoadStackInst(n); nVal->setType(Type::createNumber()); // A[n] = stepValue; // Unfortunately this can throw because our arrays can have limited range. // The spec doesn't specify what to do in this case, but the reasonable thing // to do is to what we would if this was a for-of loop doing the same thing. // See section BindingRestElement:...BindingIdentifier, step f and g: // https://www.ecma-international.org/ecma-262/9.0/index.html#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization emitTryWithSharedHandler(handler, [this, stepValue, A, nVal]() { Builder.createStorePropertyInst(stepValue, A, nVal); }); // ++n; auto add = Builder.createBinaryOperatorInst( nVal, Builder.getLiteralNumber(1), BinaryOperatorInst::OpKind::AddKind); add->setType(Type::createNumber()); Builder.createStoreStackInst(add, n); Builder.createBranchInst(notDoneBlock); // doneBlock: Builder.setInsertionBlock(doneBlock); if (lref->canStoreWithoutSideEffects()) { lref->emitStore(A); } else { emitTryWithSharedHandler(handler, [&lref, A]() { lref->emitStore(A); }); } } void ESTreeIRGen::emitDestructuringObject( bool declInit, ESTree::ObjectPatternNode *target, Value *source) { // Keep track of which keys have been destructured. llvh::SmallVector<Value *, 4> excludedItems{}; if (target->_properties.empty() || llvh::isa<ESTree::RestElementNode>(target->_properties.front())) { // ES10.0 13.3.3.5 // 1. Perform ? RequireObjectCoercible(value). // The extremely unlikely case that the user is attempting to destructure // into {} or {...rest}. Any other object destructuring will fail upon // attempting to retrieve a real property from `source`. // We must check that the source can be destructured, // and the only time this will throw is if source is undefined or null. auto *throwBB = Builder.createBasicBlock(Builder.getFunction()); auto *doneBB = Builder.createBasicBlock(Builder.getFunction()); // Use == instead of === to account for both undefined and null. Builder.createCondBranchInst( Builder.createBinaryOperatorInst( source, Builder.getLiteralNull(), BinaryOperatorInst::OpKind::EqualKind), throwBB, doneBB); Builder.setInsertionBlock(throwBB); genBuiltinCall( BuiltinMethod::HermesBuiltin_throwTypeError, {source, Builder.getLiteralString( "Cannot destructure 'undefined' or 'null'.")}); // throwTypeError will always throw. // This return is here to ensure well-formed IR, and will not run. Builder.createReturnInst(Builder.getLiteralUndefined()); Builder.setInsertionBlock(doneBB); } for (auto &elem : target->_properties) { if (auto *rest = llvh::dyn_cast<ESTree::RestElementNode>(&elem)) { emitRestProperty(declInit, rest, excludedItems, source); break; } auto *propNode = cast<ESTree::PropertyNode>(&elem); ESTree::Node *valueNode = propNode->_value; ESTree::Node *init = nullptr; // If we have an initializer, unwrap it. if (auto *assign = llvh::dyn_cast<ESTree::AssignmentPatternNode>(valueNode)) { valueNode = assign->_left; init = assign->_right; } Identifier nameHint = llvh::isa<ESTree::IdentifierNode>(valueNode) ? getNameFieldFromID(valueNode) : Identifier{}; if (llvh::isa<ESTree::IdentifierNode>(propNode->_key) && !propNode->_computed) { Identifier key = getNameFieldFromID(propNode->_key); excludedItems.push_back(Builder.getLiteralString(key)); auto *loadedValue = Builder.createLoadPropertyInst(source, key); createLRef(valueNode, declInit) .emitStore(emitOptionalInitialization(loadedValue, init, nameHint)); } else { Value *key = genExpression(propNode->_key); excludedItems.push_back(key); auto *loadedValue = Builder.createLoadPropertyInst(source, key); createLRef(valueNode, declInit) .emitStore(emitOptionalInitialization(loadedValue, init, nameHint)); } } } void ESTreeIRGen::emitRestProperty( bool declInit, ESTree::RestElementNode *rest, const llvh::SmallVectorImpl<Value *> &excludedItems, hermes::Value *source) { auto lref = createLRef(rest->_argument, declInit); // Construct the excluded items. HBCAllocObjectFromBufferInst::ObjectPropertyMap exMap{}; llvh::SmallVector<Value *, 4> computedExcludedItems{}; // Keys need de-duping so we don't create a dummy exclusion object with // duplicate keys. llvh::DenseSet<Literal *> keyDeDupeSet; auto *zeroValue = Builder.getLiteralPositiveZero(); for (Value *key : excludedItems) { if (auto *lit = llvh::dyn_cast<Literal>(key)) { // If the key is a literal, we can place it in the // HBCAllocObjectFromBufferInst buffer. if (keyDeDupeSet.insert(lit).second) { exMap.emplace_back(std::make_pair(lit, zeroValue)); } } else { // If the key is not a literal, then we have to dynamically populate the // excluded object with it after creation from the buffer. computedExcludedItems.push_back(key); } } Value *excludedObj; if (excludedItems.empty()) { excludedObj = Builder.getLiteralUndefined(); } else { // This size is only a hint as the true size may change if there are // duplicates when computedExcludedItems is processed at run-time. auto excludedSizeHint = exMap.size() + computedExcludedItems.size(); if (exMap.empty()) { excludedObj = Builder.createAllocObjectInst(excludedSizeHint); } else { excludedObj = Builder.createHBCAllocObjectFromBufferInst(exMap, excludedSizeHint); } for (Value *key : computedExcludedItems) { Builder.createStorePropertyInst(zeroValue, excludedObj, key); } } auto *restValue = genBuiltinCall( BuiltinMethod::HermesBuiltin_copyDataProperties, {Builder.createAllocObjectInst(0), source, excludedObj}); lref.emitStore(restValue); } Value *ESTreeIRGen::emitOptionalInitialization( Value *value, ESTree::Node *init, Identifier nameHint) { if (!init) return value; auto *currentBlock = Builder.getInsertionBlock(); auto *getDefaultBlock = Builder.createBasicBlock(Builder.getFunction()); auto *storeBlock = Builder.createBasicBlock(Builder.getFunction()); // if (value !== undefined) goto storeBlock [if initializer present] // value = initializer [if initializer present] // storeBlock: Builder.createCondBranchInst( Builder.createBinaryOperatorInst( value, Builder.getLiteralUndefined(), BinaryOperatorInst::OpKind::StrictlyNotEqualKind), storeBlock, getDefaultBlock); // getDefaultBlock: Builder.setInsertionBlock(getDefaultBlock); auto *defaultValue = genExpression(init, nameHint); auto *defaultResultBlock = Builder.getInsertionBlock(); Builder.createBranchInst(storeBlock); // storeBlock: Builder.setInsertionBlock(storeBlock); return Builder.createPhiInst( {value, defaultValue}, {currentBlock, defaultResultBlock}); } std::shared_ptr<SerializedScope> ESTreeIRGen::resolveScopeIdentifiers( const ScopeChain &chain) { std::shared_ptr<SerializedScope> current{}; for (auto it = chain.functions.rbegin(), end = chain.functions.rend(); it < end; it++) { auto next = std::make_shared<SerializedScope>(); next->variables.reserve(it->variables.size()); for (auto var : it->variables) { next->variables.push_back(std::move(Builder.createIdentifier(var))); } next->parentScope = current; current = next; } return current; } void ESTreeIRGen::materializeScopesInChain( Function *wrapperFunction, const std::shared_ptr<const SerializedScope> &scope, int depth) { if (!scope) return; assert(depth < 1000 && "Excessive scope depth"); // First materialize parent scopes. materializeScopesInChain(wrapperFunction, scope->parentScope, depth - 1); // If scope->closureAlias is specified, we must create an alias binding // between originalName (which must be valid) and the variable identified by // closureAlias. // // We do this *before* inserting the other variables below to reflect that // the closure alias is conceptually in an outside scope and also avoid the // closure name incorrectly shadowing the same name inside the closure. if (scope->closureAlias.isValid()) { assert(scope->originalName.isValid() && "Original name invalid"); assert( scope->originalName != scope->closureAlias && "Original name must be different from the alias"); // NOTE: the closureAlias target must exist and must be a Variable. auto *closureVar = cast<Variable>(nameTable_.lookup(scope->closureAlias)); // Re-create the alias. nameTable_.insert(scope->originalName, closureVar); } // Create an external scope. ExternalScope *ES = Builder.createExternalScope(wrapperFunction, depth); for (auto variableId : scope->variables) { auto *variable = Builder.createVariable(ES, Variable::DeclKind::Var, variableId); nameTable_.insert(variableId, variable); } } namespace { void buildDummyLexicalParent( IRBuilder &builder, Function *parent, Function *child) { // FunctionScopeAnalysis works through CreateFunctionInsts, so we have to add // that even though these functions are never invoked. auto *block = builder.createBasicBlock(parent); builder.setInsertionBlock(block); builder.createUnreachableInst(); auto *inst = builder.createCreateFunctionInst(child); builder.createReturnInst(inst); } } // namespace /// Add dummy functions for lexical scope debug info. // They are never executed and serve no purpose other than filling in debug // info. This is currently necessary because we can't rely on parent bytecode // modules for lexical scoping data. void ESTreeIRGen::addLexicalDebugInfo( Function *child, Function *global, const std::shared_ptr<const SerializedScope> &scope) { if (!scope || !scope->parentScope) { buildDummyLexicalParent(Builder, global, child); return; } auto *current = Builder.createFunction( scope->originalName, Function::DefinitionKind::ES5Function, false, {}, false); for (auto &var : scope->variables) { Builder.createVariable( current->getFunctionScope(), Variable::DeclKind::Var, var); } buildDummyLexicalParent(Builder, current, child); addLexicalDebugInfo(current, global, scope->parentScope); } std::shared_ptr<SerializedScope> ESTreeIRGen::serializeScope( FunctionContext *ctx, bool includeGlobal) { // Serialize the global scope if and only if it's the only scope. // We serialize the global scope to avoid re-declaring variables, // and only do it once to avoid creating spurious scopes. if (!ctx || (ctx->function->isGlobalScope() && !includeGlobal)) return lexicalScopeChain; auto scope = std::make_shared<SerializedScope>(); auto *func = ctx->function; assert(func && "Missing function when saving scope"); scope->originalName = func->getOriginalOrInferredName(); if (auto *closure = func->getLazyClosureAlias()) { scope->closureAlias = closure->getName(); } for (auto *var : func->getFunctionScope()->getVariables()) { scope->variables.push_back(var->getName()); } scope->parentScope = serializeScope(ctx->getPreviousContext(), false); return scope; } } // namespace irgen } // namespace hermes
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_4256_4
crossvul-cpp_data_good_1309_0
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "precomp.hpp" #include "opencv2/core/hal/intrin.hpp" #include "opencl_kernels_video.hpp" using namespace std; #define EPS 0.001F #define INF 1E+10F namespace cv { class DISOpticalFlowImpl CV_FINAL : public DISOpticalFlow { public: DISOpticalFlowImpl(); void calc(InputArray I0, InputArray I1, InputOutputArray flow) CV_OVERRIDE; void collectGarbage() CV_OVERRIDE; protected: //!< algorithm parameters int finest_scale, coarsest_scale; int patch_size; int patch_stride; int grad_descent_iter; int variational_refinement_iter; float variational_refinement_alpha; float variational_refinement_gamma; float variational_refinement_delta; bool use_mean_normalization; bool use_spatial_propagation; protected: //!< some auxiliary variables int border_size; int w, h; //!< flow buffer width and height on the current scale int ws, hs; //!< sparse flow buffer width and height on the current scale public: int getFinestScale() const CV_OVERRIDE { return finest_scale; } void setFinestScale(int val) CV_OVERRIDE { finest_scale = val; } int getPatchSize() const CV_OVERRIDE { return patch_size; } void setPatchSize(int val) CV_OVERRIDE { patch_size = val; } int getPatchStride() const CV_OVERRIDE { return patch_stride; } void setPatchStride(int val) CV_OVERRIDE { patch_stride = val; } int getGradientDescentIterations() const CV_OVERRIDE { return grad_descent_iter; } void setGradientDescentIterations(int val) CV_OVERRIDE { grad_descent_iter = val; } int getVariationalRefinementIterations() const CV_OVERRIDE { return variational_refinement_iter; } void setVariationalRefinementIterations(int val) CV_OVERRIDE { variational_refinement_iter = val; } float getVariationalRefinementAlpha() const CV_OVERRIDE { return variational_refinement_alpha; } void setVariationalRefinementAlpha(float val) CV_OVERRIDE { variational_refinement_alpha = val; } float getVariationalRefinementDelta() const CV_OVERRIDE { return variational_refinement_delta; } void setVariationalRefinementDelta(float val) CV_OVERRIDE { variational_refinement_delta = val; } float getVariationalRefinementGamma() const CV_OVERRIDE { return variational_refinement_gamma; } void setVariationalRefinementGamma(float val) CV_OVERRIDE { variational_refinement_gamma = val; } bool getUseMeanNormalization() const CV_OVERRIDE { return use_mean_normalization; } void setUseMeanNormalization(bool val) CV_OVERRIDE { use_mean_normalization = val; } bool getUseSpatialPropagation() const CV_OVERRIDE { return use_spatial_propagation; } void setUseSpatialPropagation(bool val) CV_OVERRIDE { use_spatial_propagation = val; } protected: //!< internal buffers vector<Mat_<uchar> > I0s; //!< Gaussian pyramid for the current frame vector<Mat_<uchar> > I1s; //!< Gaussian pyramid for the next frame vector<Mat_<uchar> > I1s_ext; //!< I1s with borders vector<Mat_<short> > I0xs; //!< Gaussian pyramid for the x gradient of the current frame vector<Mat_<short> > I0ys; //!< Gaussian pyramid for the y gradient of the current frame vector<Mat_<float> > Ux; //!< x component of the flow vectors vector<Mat_<float> > Uy; //!< y component of the flow vectors vector<Mat_<float> > initial_Ux; //!< x component of the initial flow field, if one was passed as an input vector<Mat_<float> > initial_Uy; //!< y component of the initial flow field, if one was passed as an input Mat_<Vec2f> U; //!< a buffer for the merged flow Mat_<float> Sx; //!< intermediate sparse flow representation (x component) Mat_<float> Sy; //!< intermediate sparse flow representation (y component) /* Structure tensor components: */ Mat_<float> I0xx_buf; //!< sum of squares of x gradient values Mat_<float> I0yy_buf; //!< sum of squares of y gradient values Mat_<float> I0xy_buf; //!< sum of x and y gradient products /* Extra buffers that are useful if patch mean-normalization is used: */ Mat_<float> I0x_buf; //!< sum of x gradient values Mat_<float> I0y_buf; //!< sum of y gradient values /* Auxiliary buffers used in structure tensor computation: */ Mat_<float> I0xx_buf_aux; Mat_<float> I0yy_buf_aux; Mat_<float> I0xy_buf_aux; Mat_<float> I0x_buf_aux; Mat_<float> I0y_buf_aux; vector<Ptr<VariationalRefinement> > variational_refinement_processors; private: //!< private methods and parallel sections void prepareBuffers(Mat &I0, Mat &I1, Mat &flow, bool use_flow); void precomputeStructureTensor(Mat &dst_I0xx, Mat &dst_I0yy, Mat &dst_I0xy, Mat &dst_I0x, Mat &dst_I0y, Mat &I0x, Mat &I0y); int autoSelectCoarsestScale(int img_width); void autoSelectPatchSizeAndScales(int img_width); struct PatchInverseSearch_ParBody : public ParallelLoopBody { DISOpticalFlowImpl *dis; int nstripes, stripe_sz; int hs; Mat *Sx, *Sy, *Ux, *Uy, *I0, *I1, *I0x, *I0y; int num_iter, pyr_level; PatchInverseSearch_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _hs, Mat &dst_Sx, Mat &dst_Sy, Mat &src_Ux, Mat &src_Uy, Mat &_I0, Mat &_I1, Mat &_I0x, Mat &_I0y, int _num_iter, int _pyr_level); void operator()(const Range &range) const CV_OVERRIDE; }; struct Densification_ParBody : public ParallelLoopBody { DISOpticalFlowImpl *dis; int nstripes, stripe_sz; int h; Mat *Ux, *Uy, *Sx, *Sy, *I0, *I1; Densification_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _h, Mat &dst_Ux, Mat &dst_Uy, Mat &src_Sx, Mat &src_Sy, Mat &_I0, Mat &_I1); void operator()(const Range &range) const CV_OVERRIDE; }; #ifdef HAVE_OPENCL vector<UMat> u_I0s; //!< Gaussian pyramid for the current frame vector<UMat> u_I1s; //!< Gaussian pyramid for the next frame vector<UMat> u_I1s_ext; //!< I1s with borders vector<UMat> u_I0xs; //!< Gaussian pyramid for the x gradient of the current frame vector<UMat> u_I0ys; //!< Gaussian pyramid for the y gradient of the current frame vector<UMat> u_Ux; //!< x component of the flow vectors vector<UMat> u_Uy; //!< y component of the flow vectors vector<UMat> u_initial_Ux; //!< x component of the initial flow field, if one was passed as an input vector<UMat> u_initial_Uy; //!< y component of the initial flow field, if one was passed as an input UMat u_U; //!< a buffer for the merged flow UMat u_Sx; //!< intermediate sparse flow representation (x component) UMat u_Sy; //!< intermediate sparse flow representation (y component) /* Structure tensor components: */ UMat u_I0xx_buf; //!< sum of squares of x gradient values UMat u_I0yy_buf; //!< sum of squares of y gradient values UMat u_I0xy_buf; //!< sum of x and y gradient products /* Extra buffers that are useful if patch mean-normalization is used: */ UMat u_I0x_buf; //!< sum of x gradient values UMat u_I0y_buf; //!< sum of y gradient values /* Auxiliary buffers used in structure tensor computation: */ UMat u_I0xx_buf_aux; UMat u_I0yy_buf_aux; UMat u_I0xy_buf_aux; UMat u_I0x_buf_aux; UMat u_I0y_buf_aux; bool ocl_precomputeStructureTensor(UMat &dst_I0xx, UMat &dst_I0yy, UMat &dst_I0xy, UMat &dst_I0x, UMat &dst_I0y, UMat &I0x, UMat &I0y); void ocl_prepareBuffers(UMat &I0, UMat &I1, UMat &flow, bool use_flow); bool ocl_calc(InputArray I0, InputArray I1, InputOutputArray flow); bool ocl_Densification(UMat &dst_Ux, UMat &dst_Uy, UMat &src_Sx, UMat &src_Sy, UMat &_I0, UMat &_I1); bool ocl_PatchInverseSearch(UMat &src_Ux, UMat &src_Uy, UMat &I0, UMat &I1, UMat &I0x, UMat &I0y, int num_iter, int pyr_level); #endif }; DISOpticalFlowImpl::DISOpticalFlowImpl() { finest_scale = 2; patch_size = 8; patch_stride = 4; grad_descent_iter = 16; variational_refinement_iter = 5; variational_refinement_alpha = 20.f; variational_refinement_gamma = 10.f; variational_refinement_delta = 5.f; border_size = 16; use_mean_normalization = true; use_spatial_propagation = true; coarsest_scale = 10; /* Use separate variational refinement instances for different scales to avoid repeated memory allocation: */ int max_possible_scales = 10; ws = hs = w = h = 0; for (int i = 0; i < max_possible_scales; i++) variational_refinement_processors.push_back(VariationalRefinement::create()); } void DISOpticalFlowImpl::prepareBuffers(Mat &I0, Mat &I1, Mat &flow, bool use_flow) { I0s.resize(coarsest_scale + 1); I1s.resize(coarsest_scale + 1); I1s_ext.resize(coarsest_scale + 1); I0xs.resize(coarsest_scale + 1); I0ys.resize(coarsest_scale + 1); Ux.resize(coarsest_scale + 1); Uy.resize(coarsest_scale + 1); Mat flow_uv[2]; if (use_flow) { split(flow, flow_uv); initial_Ux.resize(coarsest_scale + 1); initial_Uy.resize(coarsest_scale + 1); } int fraction = 1; int cur_rows = 0, cur_cols = 0; for (int i = 0; i <= coarsest_scale; i++) { /* Avoid initializing the pyramid levels above the finest scale, as they won't be used anyway */ if (i == finest_scale) { cur_rows = I0.rows / fraction; cur_cols = I0.cols / fraction; I0s[i].create(cur_rows, cur_cols); resize(I0, I0s[i], I0s[i].size(), 0.0, 0.0, INTER_AREA); I1s[i].create(cur_rows, cur_cols); resize(I1, I1s[i], I1s[i].size(), 0.0, 0.0, INTER_AREA); /* These buffers are reused in each scale so we initialize them once on the finest scale: */ Sx.create(cur_rows / patch_stride, cur_cols / patch_stride); Sy.create(cur_rows / patch_stride, cur_cols / patch_stride); I0xx_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0yy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0xy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0x_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0y_buf.create(cur_rows / patch_stride, cur_cols / patch_stride); I0xx_buf_aux.create(cur_rows, cur_cols / patch_stride); I0yy_buf_aux.create(cur_rows, cur_cols / patch_stride); I0xy_buf_aux.create(cur_rows, cur_cols / patch_stride); I0x_buf_aux.create(cur_rows, cur_cols / patch_stride); I0y_buf_aux.create(cur_rows, cur_cols / patch_stride); U.create(cur_rows, cur_cols); } else if (i > finest_scale) { cur_rows = I0s[i - 1].rows / 2; cur_cols = I0s[i - 1].cols / 2; I0s[i].create(cur_rows, cur_cols); resize(I0s[i - 1], I0s[i], I0s[i].size(), 0.0, 0.0, INTER_AREA); I1s[i].create(cur_rows, cur_cols); resize(I1s[i - 1], I1s[i], I1s[i].size(), 0.0, 0.0, INTER_AREA); } if (i >= finest_scale) { I1s_ext[i].create(cur_rows + 2 * border_size, cur_cols + 2 * border_size); copyMakeBorder(I1s[i], I1s_ext[i], border_size, border_size, border_size, border_size, BORDER_REPLICATE); I0xs[i].create(cur_rows, cur_cols); I0ys[i].create(cur_rows, cur_cols); spatialGradient(I0s[i], I0xs[i], I0ys[i]); Ux[i].create(cur_rows, cur_cols); Uy[i].create(cur_rows, cur_cols); variational_refinement_processors[i]->setAlpha(variational_refinement_alpha); variational_refinement_processors[i]->setDelta(variational_refinement_delta); variational_refinement_processors[i]->setGamma(variational_refinement_gamma); variational_refinement_processors[i]->setSorIterations(5); variational_refinement_processors[i]->setFixedPointIterations(variational_refinement_iter); if (use_flow) { resize(flow_uv[0], initial_Ux[i], Size(cur_cols, cur_rows)); initial_Ux[i] /= fraction; resize(flow_uv[1], initial_Uy[i], Size(cur_cols, cur_rows)); initial_Uy[i] /= fraction; } } fraction *= 2; } } /* This function computes the structure tensor elements (local sums of I0x^2, I0x*I0y and I0y^2). * A simple box filter is not used instead because we need to compute these sums on a sparse grid * and store them densely in the output buffers. */ void DISOpticalFlowImpl::precomputeStructureTensor(Mat &dst_I0xx, Mat &dst_I0yy, Mat &dst_I0xy, Mat &dst_I0x, Mat &dst_I0y, Mat &I0x, Mat &I0y) { float *I0xx_ptr = dst_I0xx.ptr<float>(); float *I0yy_ptr = dst_I0yy.ptr<float>(); float *I0xy_ptr = dst_I0xy.ptr<float>(); float *I0x_ptr = dst_I0x.ptr<float>(); float *I0y_ptr = dst_I0y.ptr<float>(); float *I0xx_aux_ptr = I0xx_buf_aux.ptr<float>(); float *I0yy_aux_ptr = I0yy_buf_aux.ptr<float>(); float *I0xy_aux_ptr = I0xy_buf_aux.ptr<float>(); float *I0x_aux_ptr = I0x_buf_aux.ptr<float>(); float *I0y_aux_ptr = I0y_buf_aux.ptr<float>(); /* Separable box filter: horizontal pass */ for (int i = 0; i < h; i++) { float sum_xx = 0.0f, sum_yy = 0.0f, sum_xy = 0.0f, sum_x = 0.0f, sum_y = 0.0f; short *x_row = I0x.ptr<short>(i); short *y_row = I0y.ptr<short>(i); for (int j = 0; j < patch_size; j++) { sum_xx += x_row[j] * x_row[j]; sum_yy += y_row[j] * y_row[j]; sum_xy += x_row[j] * y_row[j]; sum_x += x_row[j]; sum_y += y_row[j]; } I0xx_aux_ptr[i * ws] = sum_xx; I0yy_aux_ptr[i * ws] = sum_yy; I0xy_aux_ptr[i * ws] = sum_xy; I0x_aux_ptr[i * ws] = sum_x; I0y_aux_ptr[i * ws] = sum_y; int js = 1; for (int j = patch_size; j < w; j++) { sum_xx += (x_row[j] * x_row[j] - x_row[j - patch_size] * x_row[j - patch_size]); sum_yy += (y_row[j] * y_row[j] - y_row[j - patch_size] * y_row[j - patch_size]); sum_xy += (x_row[j] * y_row[j] - x_row[j - patch_size] * y_row[j - patch_size]); sum_x += (x_row[j] - x_row[j - patch_size]); sum_y += (y_row[j] - y_row[j - patch_size]); if ((j - patch_size + 1) % patch_stride == 0) { I0xx_aux_ptr[i * ws + js] = sum_xx; I0yy_aux_ptr[i * ws + js] = sum_yy; I0xy_aux_ptr[i * ws + js] = sum_xy; I0x_aux_ptr[i * ws + js] = sum_x; I0y_aux_ptr[i * ws + js] = sum_y; js++; } } } AutoBuffer<float> sum_xx(ws), sum_yy(ws), sum_xy(ws), sum_x(ws), sum_y(ws); for (int j = 0; j < ws; j++) { sum_xx[j] = 0.0f; sum_yy[j] = 0.0f; sum_xy[j] = 0.0f; sum_x[j] = 0.0f; sum_y[j] = 0.0f; } /* Separable box filter: vertical pass */ for (int i = 0; i < patch_size; i++) for (int j = 0; j < ws; j++) { sum_xx[j] += I0xx_aux_ptr[i * ws + j]; sum_yy[j] += I0yy_aux_ptr[i * ws + j]; sum_xy[j] += I0xy_aux_ptr[i * ws + j]; sum_x[j] += I0x_aux_ptr[i * ws + j]; sum_y[j] += I0y_aux_ptr[i * ws + j]; } for (int j = 0; j < ws; j++) { I0xx_ptr[j] = sum_xx[j]; I0yy_ptr[j] = sum_yy[j]; I0xy_ptr[j] = sum_xy[j]; I0x_ptr[j] = sum_x[j]; I0y_ptr[j] = sum_y[j]; } int is = 1; for (int i = patch_size; i < h; i++) { for (int j = 0; j < ws; j++) { sum_xx[j] += (I0xx_aux_ptr[i * ws + j] - I0xx_aux_ptr[(i - patch_size) * ws + j]); sum_yy[j] += (I0yy_aux_ptr[i * ws + j] - I0yy_aux_ptr[(i - patch_size) * ws + j]); sum_xy[j] += (I0xy_aux_ptr[i * ws + j] - I0xy_aux_ptr[(i - patch_size) * ws + j]); sum_x[j] += (I0x_aux_ptr[i * ws + j] - I0x_aux_ptr[(i - patch_size) * ws + j]); sum_y[j] += (I0y_aux_ptr[i * ws + j] - I0y_aux_ptr[(i - patch_size) * ws + j]); } if ((i - patch_size + 1) % patch_stride == 0) { for (int j = 0; j < ws; j++) { I0xx_ptr[is * ws + j] = sum_xx[j]; I0yy_ptr[is * ws + j] = sum_yy[j]; I0xy_ptr[is * ws + j] = sum_xy[j]; I0x_ptr[is * ws + j] = sum_x[j]; I0y_ptr[is * ws + j] = sum_y[j]; } is++; } } } int DISOpticalFlowImpl::autoSelectCoarsestScale(int img_width) { const int fratio = 5; return std::max(0, (int)std::floor(log2((2.0f*(float)img_width) / ((float)fratio * (float)patch_size)))); } void DISOpticalFlowImpl::autoSelectPatchSizeAndScales(int img_width) { switch (finest_scale) { case 1: patch_size = 8; coarsest_scale = autoSelectCoarsestScale(img_width); finest_scale = std::max(coarsest_scale-2, 0); break; case 3: patch_size = 12; coarsest_scale = autoSelectCoarsestScale(img_width); finest_scale = std::max(coarsest_scale-4, 0); break; case 4: patch_size = 12; coarsest_scale = autoSelectCoarsestScale(img_width); finest_scale = std::max(coarsest_scale-5, 0); break; // default case, fall-through. case 2: default: patch_size = 8; coarsest_scale = autoSelectCoarsestScale(img_width); finest_scale = std::max(coarsest_scale-2, 0); break; } } DISOpticalFlowImpl::PatchInverseSearch_ParBody::PatchInverseSearch_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _hs, Mat &dst_Sx, Mat &dst_Sy, Mat &src_Ux, Mat &src_Uy, Mat &_I0, Mat &_I1, Mat &_I0x, Mat &_I0y, int _num_iter, int _pyr_level) : dis(&_dis), nstripes(_nstripes), hs(_hs), Sx(&dst_Sx), Sy(&dst_Sy), Ux(&src_Ux), Uy(&src_Uy), I0(&_I0), I1(&_I1), I0x(&_I0x), I0y(&_I0y), num_iter(_num_iter), pyr_level(_pyr_level) { stripe_sz = (int)ceil(hs / (double)nstripes); } /////////////////////////////////////////////* Patch processing functions *///////////////////////////////////////////// /* Some auxiliary macros */ #define HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION \ v_float32x4 w00v = v_setall_f32(w00); \ v_float32x4 w01v = v_setall_f32(w01); \ v_float32x4 w10v = v_setall_f32(w10); \ v_float32x4 w11v = v_setall_f32(w11); \ \ v_uint8x16 I0_row_16, I1_row_16, I1_row_shifted_16, I1_row_next_16, I1_row_next_shifted_16; \ v_uint16x8 I0_row_8, I1_row_8, I1_row_shifted_8, I1_row_next_8, I1_row_next_shifted_8, tmp; \ v_uint32x4 I0_row_4_left, I1_row_4_left, I1_row_shifted_4_left, I1_row_next_4_left, I1_row_next_shifted_4_left; \ v_uint32x4 I0_row_4_right, I1_row_4_right, I1_row_shifted_4_right, I1_row_next_4_right, \ I1_row_next_shifted_4_right; \ v_float32x4 I_diff_left, I_diff_right; \ \ /* Preload and expand the first row of I1: */ \ I1_row_16 = v_load(I1_ptr); \ I1_row_shifted_16 = v_extract<1>(I1_row_16, I1_row_16); \ v_expand(I1_row_16, I1_row_8, tmp); \ v_expand(I1_row_shifted_16, I1_row_shifted_8, tmp); \ v_expand(I1_row_8, I1_row_4_left, I1_row_4_right); \ v_expand(I1_row_shifted_8, I1_row_shifted_4_left, I1_row_shifted_4_right); \ I1_ptr += I1_stride; #define HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION \ /* Load the next row of I1: */ \ I1_row_next_16 = v_load(I1_ptr); \ /* Circular shift left by 1 element: */ \ I1_row_next_shifted_16 = v_extract<1>(I1_row_next_16, I1_row_next_16); \ /* Expand to 8 ushorts (we only need the first 8 values): */ \ v_expand(I1_row_next_16, I1_row_next_8, tmp); \ v_expand(I1_row_next_shifted_16, I1_row_next_shifted_8, tmp); \ /* Separate the left and right halves: */ \ v_expand(I1_row_next_8, I1_row_next_4_left, I1_row_next_4_right); \ v_expand(I1_row_next_shifted_8, I1_row_next_shifted_4_left, I1_row_next_shifted_4_right); \ \ /* Load current row of I0: */ \ I0_row_16 = v_load(I0_ptr); \ v_expand(I0_row_16, I0_row_8, tmp); \ v_expand(I0_row_8, I0_row_4_left, I0_row_4_right); \ \ /* Compute diffs between I0 and bilinearly interpolated I1: */ \ I_diff_left = w00v * v_cvt_f32(v_reinterpret_as_s32(I1_row_4_left)) + \ w01v * v_cvt_f32(v_reinterpret_as_s32(I1_row_shifted_4_left)) + \ w10v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_4_left)) + \ w11v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_shifted_4_left)) - \ v_cvt_f32(v_reinterpret_as_s32(I0_row_4_left)); \ I_diff_right = w00v * v_cvt_f32(v_reinterpret_as_s32(I1_row_4_right)) + \ w01v * v_cvt_f32(v_reinterpret_as_s32(I1_row_shifted_4_right)) + \ w10v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_4_right)) + \ w11v * v_cvt_f32(v_reinterpret_as_s32(I1_row_next_shifted_4_right)) - \ v_cvt_f32(v_reinterpret_as_s32(I0_row_4_right)); #define HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW \ I0_ptr += I0_stride; \ I1_ptr += I1_stride; \ \ I1_row_4_left = I1_row_next_4_left; \ I1_row_4_right = I1_row_next_4_right; \ I1_row_shifted_4_left = I1_row_next_shifted_4_left; \ I1_row_shifted_4_right = I1_row_next_shifted_4_right; /* This function essentially performs one iteration of gradient descent when finding the most similar patch in I1 for a * given one in I0. It assumes that I0_ptr and I1_ptr already point to the corresponding patches and w00, w01, w10, w11 * are precomputed bilinear interpolation weights. It returns the SSD (sum of squared differences) between these patches * and computes the values (dst_dUx, dst_dUy) that are used in the flow vector update. HAL acceleration is implemented * only for the default patch size (8x8). Everything is processed in floats as using fixed-point approximations harms * the quality significantly. */ inline float processPatch(float &dst_dUx, float &dst_dUy, uchar *I0_ptr, uchar *I1_ptr, short *I0x_ptr, short *I0y_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz) { float SSD = 0.0f; #if CV_SIMD128 if (patch_sz == 8) { /* Variables to accumulate the sums */ v_float32x4 Ux_vec = v_setall_f32(0); v_float32x4 Uy_vec = v_setall_f32(0); v_float32x4 SSD_vec = v_setall_f32(0); v_int16x8 I0x_row, I0y_row; v_int32x4 I0x_row_4_left, I0x_row_4_right, I0y_row_4_left, I0y_row_4_right; HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; I0x_row = v_load(I0x_ptr); v_expand(I0x_row, I0x_row_4_left, I0x_row_4_right); I0y_row = v_load(I0y_ptr); v_expand(I0y_row, I0y_row_4_left, I0y_row_4_right); /* Update the sums: */ Ux_vec += I_diff_left * v_cvt_f32(I0x_row_4_left) + I_diff_right * v_cvt_f32(I0x_row_4_right); Uy_vec += I_diff_left * v_cvt_f32(I0y_row_4_left) + I_diff_right * v_cvt_f32(I0y_row_4_right); SSD_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; I0x_ptr += I0_stride; I0y_ptr += I0_stride; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } /* Final reduce operations: */ dst_dUx = v_reduce_sum(Ux_vec); dst_dUy = v_reduce_sum(Uy_vec); SSD = v_reduce_sum(SSD_vec); } else { #endif dst_dUx = 0.0f; dst_dUy = 0.0f; float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; SSD += diff * diff; dst_dUx += diff * I0x_ptr[i * I0_stride + j]; dst_dUy += diff * I0y_ptr[i * I0_stride + j]; } #if CV_SIMD128 } #endif return SSD; } /* Same as processPatch, but with patch mean normalization, which improves robustness under changing * lighting conditions */ inline float processPatchMeanNorm(float &dst_dUx, float &dst_dUy, uchar *I0_ptr, uchar *I1_ptr, short *I0x_ptr, short *I0y_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz, float x_grad_sum, float y_grad_sum) { float sum_diff = 0.0, sum_diff_sq = 0.0; float sum_I0x_mul = 0.0, sum_I0y_mul = 0.0; float n = (float)patch_sz * patch_sz; #if CV_SIMD128 if (patch_sz == 8) { /* Variables to accumulate the sums */ v_float32x4 sum_I0x_mul_vec = v_setall_f32(0); v_float32x4 sum_I0y_mul_vec = v_setall_f32(0); v_float32x4 sum_diff_vec = v_setall_f32(0); v_float32x4 sum_diff_sq_vec = v_setall_f32(0); v_int16x8 I0x_row, I0y_row; v_int32x4 I0x_row_4_left, I0x_row_4_right, I0y_row_4_left, I0y_row_4_right; HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; I0x_row = v_load(I0x_ptr); v_expand(I0x_row, I0x_row_4_left, I0x_row_4_right); I0y_row = v_load(I0y_ptr); v_expand(I0y_row, I0y_row_4_left, I0y_row_4_right); /* Update the sums: */ sum_I0x_mul_vec += I_diff_left * v_cvt_f32(I0x_row_4_left) + I_diff_right * v_cvt_f32(I0x_row_4_right); sum_I0y_mul_vec += I_diff_left * v_cvt_f32(I0y_row_4_left) + I_diff_right * v_cvt_f32(I0y_row_4_right); sum_diff_sq_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; sum_diff_vec += I_diff_left + I_diff_right; I0x_ptr += I0_stride; I0y_ptr += I0_stride; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } /* Final reduce operations: */ sum_I0x_mul = v_reduce_sum(sum_I0x_mul_vec); sum_I0y_mul = v_reduce_sum(sum_I0y_mul_vec); sum_diff = v_reduce_sum(sum_diff_vec); sum_diff_sq = v_reduce_sum(sum_diff_sq_vec); } else { #endif float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; sum_diff += diff; sum_diff_sq += diff * diff; sum_I0x_mul += diff * I0x_ptr[i * I0_stride + j]; sum_I0y_mul += diff * I0y_ptr[i * I0_stride + j]; } #if CV_SIMD128 } #endif dst_dUx = sum_I0x_mul - sum_diff * x_grad_sum / n; dst_dUy = sum_I0y_mul - sum_diff * y_grad_sum / n; return sum_diff_sq - sum_diff * sum_diff / n; } /* Similar to processPatch, but compute only the sum of squared differences (SSD) between the patches */ inline float computeSSD(uchar *I0_ptr, uchar *I1_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz) { float SSD = 0.0f; #if CV_SIMD128 if (patch_sz == 8) { v_float32x4 SSD_vec = v_setall_f32(0); HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; SSD_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } SSD = v_reduce_sum(SSD_vec); } else { #endif float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; SSD += diff * diff; } #if CV_SIMD128 } #endif return SSD; } /* Same as computeSSD, but with patch mean normalization */ inline float computeSSDMeanNorm(uchar *I0_ptr, uchar *I1_ptr, int I0_stride, int I1_stride, float w00, float w01, float w10, float w11, int patch_sz) { float sum_diff = 0.0f, sum_diff_sq = 0.0f; float n = (float)patch_sz * patch_sz; #if CV_SIMD128 if (patch_sz == 8) { v_float32x4 sum_diff_vec = v_setall_f32(0); v_float32x4 sum_diff_sq_vec = v_setall_f32(0); HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION; for (int row = 0; row < 8; row++) { HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION; sum_diff_sq_vec += I_diff_left * I_diff_left + I_diff_right * I_diff_right; sum_diff_vec += I_diff_left + I_diff_right; HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW; } sum_diff = v_reduce_sum(sum_diff_vec); sum_diff_sq = v_reduce_sum(sum_diff_sq_vec); } else { #endif float diff; for (int i = 0; i < patch_sz; i++) for (int j = 0; j < patch_sz; j++) { diff = w00 * I1_ptr[i * I1_stride + j] + w01 * I1_ptr[i * I1_stride + j + 1] + w10 * I1_ptr[(i + 1) * I1_stride + j] + w11 * I1_ptr[(i + 1) * I1_stride + j + 1] - I0_ptr[i * I0_stride + j]; sum_diff += diff; sum_diff_sq += diff * diff; } #if CV_SIMD128 } #endif return sum_diff_sq - sum_diff * sum_diff / n; } #undef HAL_INIT_BILINEAR_8x8_PATCH_EXTRACTION #undef HAL_PROCESS_BILINEAR_8x8_PATCH_EXTRACTION #undef HAL_BILINEAR_8x8_PATCH_EXTRACTION_NEXT_ROW /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void DISOpticalFlowImpl::PatchInverseSearch_ParBody::operator()(const Range &range) const { // force separate processing of stripes if we are using spatial propagation: if (dis->use_spatial_propagation && range.end > range.start + 1) { for (int n = range.start; n < range.end; n++) (*this)(Range(n, n + 1)); return; } int psz = dis->patch_size; int psz2 = psz / 2; int w_ext = dis->w + 2 * dis->border_size; //!< width of I1_ext int bsz = dis->border_size; /* Input dense flow */ float *Ux_ptr = Ux->ptr<float>(); float *Uy_ptr = Uy->ptr<float>(); /* Output sparse flow */ float *Sx_ptr = Sx->ptr<float>(); float *Sy_ptr = Sy->ptr<float>(); uchar *I0_ptr = I0->ptr<uchar>(); uchar *I1_ptr = I1->ptr<uchar>(); short *I0x_ptr = I0x->ptr<short>(); short *I0y_ptr = I0y->ptr<short>(); /* Precomputed structure tensor */ float *xx_ptr = dis->I0xx_buf.ptr<float>(); float *yy_ptr = dis->I0yy_buf.ptr<float>(); float *xy_ptr = dis->I0xy_buf.ptr<float>(); /* And extra buffers for mean-normalization: */ float *x_ptr = dis->I0x_buf.ptr<float>(); float *y_ptr = dis->I0y_buf.ptr<float>(); bool use_temporal_candidates = false; float *initial_Ux_ptr = NULL, *initial_Uy_ptr = NULL; if (!dis->initial_Ux.empty()) { initial_Ux_ptr = dis->initial_Ux[pyr_level].ptr<float>(); initial_Uy_ptr = dis->initial_Uy[pyr_level].ptr<float>(); use_temporal_candidates = true; } int i, j, dir; int start_is, end_is, start_js, end_js; int start_i, start_j; float i_lower_limit = bsz - psz + 1.0f; float i_upper_limit = bsz + dis->h - 1.0f; float j_lower_limit = bsz - psz + 1.0f; float j_upper_limit = bsz + dis->w - 1.0f; float dUx, dUy, i_I1, j_I1, w00, w01, w10, w11, dx, dy; #define INIT_BILINEAR_WEIGHTS(Ux, Uy) \ i_I1 = min(max(i + Uy + bsz, i_lower_limit), i_upper_limit); \ j_I1 = min(max(j + Ux + bsz, j_lower_limit), j_upper_limit); \ \ w11 = (i_I1 - floor(i_I1)) * (j_I1 - floor(j_I1)); \ w10 = (i_I1 - floor(i_I1)) * (floor(j_I1) + 1 - j_I1); \ w01 = (floor(i_I1) + 1 - i_I1) * (j_I1 - floor(j_I1)); \ w00 = (floor(i_I1) + 1 - i_I1) * (floor(j_I1) + 1 - j_I1); #define COMPUTE_SSD(dst, Ux, Uy) \ INIT_BILINEAR_WEIGHTS(Ux, Uy); \ if (dis->use_mean_normalization) \ dst = computeSSDMeanNorm(I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, dis->w, w_ext, w00, \ w01, w10, w11, psz); \ else \ dst = computeSSD(I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, dis->w, w_ext, w00, w01, \ w10, w11, psz); int num_inner_iter = (int)floor(dis->grad_descent_iter / (float)num_iter); for (int iter = 0; iter < num_iter; iter++) { if (iter % 2 == 0) { dir = 1; start_is = min(range.start * stripe_sz, hs); end_is = min(range.end * stripe_sz, hs); start_js = 0; end_js = dis->ws; start_i = start_is * dis->patch_stride; start_j = 0; } else { dir = -1; start_is = min(range.end * stripe_sz, hs) - 1; end_is = min(range.start * stripe_sz, hs) - 1; start_js = dis->ws - 1; end_js = -1; start_i = start_is * dis->patch_stride; start_j = (dis->ws - 1) * dis->patch_stride; } i = start_i; for (int is = start_is; dir * is < dir * end_is; is += dir) { j = start_j; for (int js = start_js; dir * js < dir * end_js; js += dir) { if (iter == 0) { /* Using result form the previous pyramid level as the very first approximation: */ Sx_ptr[is * dis->ws + js] = Ux_ptr[(i + psz2) * dis->w + j + psz2]; Sy_ptr[is * dis->ws + js] = Uy_ptr[(i + psz2) * dis->w + j + psz2]; } float min_SSD = INF, cur_SSD; if (use_temporal_candidates || dis->use_spatial_propagation) { COMPUTE_SSD(min_SSD, Sx_ptr[is * dis->ws + js], Sy_ptr[is * dis->ws + js]); } if (use_temporal_candidates) { /* Try temporal candidates (vectors from the initial flow field that was passed to the function) */ COMPUTE_SSD(cur_SSD, initial_Ux_ptr[(i + psz2) * dis->w + j + psz2], initial_Uy_ptr[(i + psz2) * dis->w + j + psz2]); if (cur_SSD < min_SSD) { min_SSD = cur_SSD; Sx_ptr[is * dis->ws + js] = initial_Ux_ptr[(i + psz2) * dis->w + j + psz2]; Sy_ptr[is * dis->ws + js] = initial_Uy_ptr[(i + psz2) * dis->w + j + psz2]; } } if (dis->use_spatial_propagation) { /* Try spatial candidates: */ if (dir * js > dir * start_js) { COMPUTE_SSD(cur_SSD, Sx_ptr[is * dis->ws + js - dir], Sy_ptr[is * dis->ws + js - dir]); if (cur_SSD < min_SSD) { min_SSD = cur_SSD; Sx_ptr[is * dis->ws + js] = Sx_ptr[is * dis->ws + js - dir]; Sy_ptr[is * dis->ws + js] = Sy_ptr[is * dis->ws + js - dir]; } } /* Flow vectors won't actually propagate across different stripes, which is the reason for keeping * the number of stripes constant. It works well enough in practice and doesn't introduce any * visible seams. */ if (dir * is > dir * start_is) { COMPUTE_SSD(cur_SSD, Sx_ptr[(is - dir) * dis->ws + js], Sy_ptr[(is - dir) * dis->ws + js]); if (cur_SSD < min_SSD) { min_SSD = cur_SSD; Sx_ptr[is * dis->ws + js] = Sx_ptr[(is - dir) * dis->ws + js]; Sy_ptr[is * dis->ws + js] = Sy_ptr[(is - dir) * dis->ws + js]; } } } /* Use the best candidate as a starting point for the gradient descent: */ float cur_Ux = Sx_ptr[is * dis->ws + js]; float cur_Uy = Sy_ptr[is * dis->ws + js]; /* Computing the inverse of the structure tensor: */ float detH = xx_ptr[is * dis->ws + js] * yy_ptr[is * dis->ws + js] - xy_ptr[is * dis->ws + js] * xy_ptr[is * dis->ws + js]; if (abs(detH) < EPS) detH = EPS; float invH11 = yy_ptr[is * dis->ws + js] / detH; float invH12 = -xy_ptr[is * dis->ws + js] / detH; float invH22 = xx_ptr[is * dis->ws + js] / detH; float prev_SSD = INF, SSD; float x_grad_sum = x_ptr[is * dis->ws + js]; float y_grad_sum = y_ptr[is * dis->ws + js]; for (int t = 0; t < num_inner_iter; t++) { INIT_BILINEAR_WEIGHTS(cur_Ux, cur_Uy); if (dis->use_mean_normalization) SSD = processPatchMeanNorm(dUx, dUy, I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, I0x_ptr + i * dis->w + j, I0y_ptr + i * dis->w + j, dis->w, w_ext, w00, w01, w10, w11, psz, x_grad_sum, y_grad_sum); else SSD = processPatch(dUx, dUy, I0_ptr + i * dis->w + j, I1_ptr + (int)i_I1 * w_ext + (int)j_I1, I0x_ptr + i * dis->w + j, I0y_ptr + i * dis->w + j, dis->w, w_ext, w00, w01, w10, w11, psz); dx = invH11 * dUx + invH12 * dUy; dy = invH12 * dUx + invH22 * dUy; cur_Ux -= dx; cur_Uy -= dy; /* Break when patch distance stops decreasing */ if (SSD >= prev_SSD) break; prev_SSD = SSD; } /* If gradient descent converged to a flow vector that is very far from the initial approximation * (more than patch size) then we don't use it. Noticeably improves the robustness. */ if (norm(Vec2f(cur_Ux - Sx_ptr[is * dis->ws + js], cur_Uy - Sy_ptr[is * dis->ws + js])) <= psz) { Sx_ptr[is * dis->ws + js] = cur_Ux; Sy_ptr[is * dis->ws + js] = cur_Uy; } j += dir * dis->patch_stride; } i += dir * dis->patch_stride; } } #undef INIT_BILINEAR_WEIGHTS #undef COMPUTE_SSD } DISOpticalFlowImpl::Densification_ParBody::Densification_ParBody(DISOpticalFlowImpl &_dis, int _nstripes, int _h, Mat &dst_Ux, Mat &dst_Uy, Mat &src_Sx, Mat &src_Sy, Mat &_I0, Mat &_I1) : dis(&_dis), nstripes(_nstripes), h(_h), Ux(&dst_Ux), Uy(&dst_Uy), Sx(&src_Sx), Sy(&src_Sy), I0(&_I0), I1(&_I1) { stripe_sz = (int)ceil(h / (double)nstripes); } /* This function transforms a sparse optical flow field obtained by PatchInverseSearch (which computes flow values * on a sparse grid defined by patch_stride) into a dense optical flow field by weighted averaging of values from the * overlapping patches. */ void DISOpticalFlowImpl::Densification_ParBody::operator()(const Range &range) const { int start_i = min(range.start * stripe_sz, h); int end_i = min(range.end * stripe_sz, h); /* Input sparse flow */ float *Sx_ptr = Sx->ptr<float>(); float *Sy_ptr = Sy->ptr<float>(); /* Output dense flow */ float *Ux_ptr = Ux->ptr<float>(); float *Uy_ptr = Uy->ptr<float>(); uchar *I0_ptr = I0->ptr<uchar>(); uchar *I1_ptr = I1->ptr<uchar>(); int psz = dis->patch_size; int pstr = dis->patch_stride; int i_l, i_u; int j_l, j_u; float i_m, j_m, diff; /* These values define the set of sparse grid locations that contain patches overlapping with the current dense flow * location */ int start_is, end_is; int start_js, end_js; /* Some helper macros for updating this set of sparse grid locations */ #define UPDATE_SPARSE_I_COORDINATES \ if (i % pstr == 0 && i + psz <= h) \ end_is++; \ if (i - psz >= 0 && (i - psz) % pstr == 0 && start_is < end_is) \ start_is++; #define UPDATE_SPARSE_J_COORDINATES \ if (j % pstr == 0 && j + psz <= dis->w) \ end_js++; \ if (j - psz >= 0 && (j - psz) % pstr == 0 && start_js < end_js) \ start_js++; start_is = 0; end_is = -1; for (int i = 0; i < start_i; i++) { UPDATE_SPARSE_I_COORDINATES; } for (int i = start_i; i < end_i; i++) { UPDATE_SPARSE_I_COORDINATES; start_js = 0; end_js = -1; for (int j = 0; j < dis->w; j++) { UPDATE_SPARSE_J_COORDINATES; float coef, sum_coef = 0.0f; float sum_Ux = 0.0f; float sum_Uy = 0.0f; /* Iterate through all the patches that overlap the current location (i,j) */ for (int is = start_is; is <= end_is; is++) for (int js = start_js; js <= end_js; js++) { j_m = min(max(j + Sx_ptr[is * dis->ws + js], 0.0f), dis->w - 1.0f - EPS); i_m = min(max(i + Sy_ptr[is * dis->ws + js], 0.0f), dis->h - 1.0f - EPS); j_l = (int)j_m; j_u = j_l + 1; i_l = (int)i_m; i_u = i_l + 1; diff = (j_m - j_l) * (i_m - i_l) * I1_ptr[i_u * dis->w + j_u] + (j_u - j_m) * (i_m - i_l) * I1_ptr[i_u * dis->w + j_l] + (j_m - j_l) * (i_u - i_m) * I1_ptr[i_l * dis->w + j_u] + (j_u - j_m) * (i_u - i_m) * I1_ptr[i_l * dis->w + j_l] - I0_ptr[i * dis->w + j]; coef = 1 / max(1.0f, abs(diff)); sum_Ux += coef * Sx_ptr[is * dis->ws + js]; sum_Uy += coef * Sy_ptr[is * dis->ws + js]; sum_coef += coef; } CV_DbgAssert(sum_coef != 0); Ux_ptr[i * dis->w + j] = sum_Ux / sum_coef; Uy_ptr[i * dis->w + j] = sum_Uy / sum_coef; } } #undef UPDATE_SPARSE_I_COORDINATES #undef UPDATE_SPARSE_J_COORDINATES } #ifdef HAVE_OPENCL bool DISOpticalFlowImpl::ocl_PatchInverseSearch(UMat &src_Ux, UMat &src_Uy, UMat &I0, UMat &I1, UMat &I0x, UMat &I0y, int num_iter, int pyr_level) { size_t globalSize[] = {(size_t)ws, (size_t)hs}; size_t localSize[] = {16, 16}; int idx; int num_inner_iter = (int)floor(grad_descent_iter / (float)num_iter); String subgroups_build_options; if (ocl::Device::getDefault().isExtensionSupported("cl_khr_subgroups")) subgroups_build_options = "-DCV_USE_SUBGROUPS=1"; for (int iter = 0; iter < num_iter; iter++) { if (iter == 0) { ocl::Kernel k1("dis_patch_inverse_search_fwd_1", ocl::video::dis_flow_oclsrc, subgroups_build_options); size_t global_sz[] = {(size_t)hs * 8}; size_t local_sz[] = {8}; idx = 0; idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(src_Ux)); idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(src_Uy)); idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k1.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k1.set(idx, (int)border_size); idx = k1.set(idx, (int)patch_size); idx = k1.set(idx, (int)patch_stride); idx = k1.set(idx, (int)w); idx = k1.set(idx, (int)h); idx = k1.set(idx, (int)ws); idx = k1.set(idx, (int)hs); idx = k1.set(idx, (int)pyr_level); idx = k1.set(idx, ocl::KernelArg::PtrWriteOnly(u_Sx)); idx = k1.set(idx, ocl::KernelArg::PtrWriteOnly(u_Sy)); if (!k1.run(1, global_sz, local_sz, false)) return false; ocl::Kernel k2("dis_patch_inverse_search_fwd_2", ocl::video::dis_flow_oclsrc); idx = 0; idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(src_Ux)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(src_Uy)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0x)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(I0y)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xx_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0yy_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xy_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0x_buf)); idx = k2.set(idx, ocl::KernelArg::PtrReadOnly(u_I0y_buf)); idx = k2.set(idx, (int)border_size); idx = k2.set(idx, (int)patch_size); idx = k2.set(idx, (int)patch_stride); idx = k2.set(idx, (int)w); idx = k2.set(idx, (int)h); idx = k2.set(idx, (int)ws); idx = k2.set(idx, (int)hs); idx = k2.set(idx, (int)num_inner_iter); idx = k2.set(idx, (int)pyr_level); idx = k2.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx)); idx = k2.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy)); if (!k2.run(2, globalSize, localSize, false)) return false; } else { ocl::Kernel k3("dis_patch_inverse_search_bwd_1", ocl::video::dis_flow_oclsrc, subgroups_build_options); size_t global_sz[] = {(size_t)hs * 8}; size_t local_sz[] = {8}; idx = 0; idx = k3.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k3.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k3.set(idx, (int)border_size); idx = k3.set(idx, (int)patch_size); idx = k3.set(idx, (int)patch_stride); idx = k3.set(idx, (int)w); idx = k3.set(idx, (int)h); idx = k3.set(idx, (int)ws); idx = k3.set(idx, (int)hs); idx = k3.set(idx, (int)pyr_level); idx = k3.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx)); idx = k3.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy)); if (!k3.run(1, global_sz, local_sz, false)) return false; ocl::Kernel k4("dis_patch_inverse_search_bwd_2", ocl::video::dis_flow_oclsrc); idx = 0; idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I1)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0x)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(I0y)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xx_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0yy_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0xy_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0x_buf)); idx = k4.set(idx, ocl::KernelArg::PtrReadOnly(u_I0y_buf)); idx = k4.set(idx, (int)border_size); idx = k4.set(idx, (int)patch_size); idx = k4.set(idx, (int)patch_stride); idx = k4.set(idx, (int)w); idx = k4.set(idx, (int)h); idx = k4.set(idx, (int)ws); idx = k4.set(idx, (int)hs); idx = k4.set(idx, (int)num_inner_iter); idx = k4.set(idx, ocl::KernelArg::PtrReadWrite(u_Sx)); idx = k4.set(idx, ocl::KernelArg::PtrReadWrite(u_Sy)); if (!k4.run(2, globalSize, localSize, false)) return false; } } return true; } bool DISOpticalFlowImpl::ocl_Densification(UMat &dst_Ux, UMat &dst_Uy, UMat &src_Sx, UMat &src_Sy, UMat &_I0, UMat &_I1) { size_t globalSize[] = {(size_t)w, (size_t)h}; size_t localSize[] = {16, 16}; ocl::Kernel kernel("dis_densification", ocl::video::dis_flow_oclsrc); kernel.args(ocl::KernelArg::PtrReadOnly(src_Sx), ocl::KernelArg::PtrReadOnly(src_Sy), ocl::KernelArg::PtrReadOnly(_I0), ocl::KernelArg::PtrReadOnly(_I1), (int)patch_size, (int)patch_stride, (int)w, (int)h, (int)ws, ocl::KernelArg::PtrWriteOnly(dst_Ux), ocl::KernelArg::PtrWriteOnly(dst_Uy)); return kernel.run(2, globalSize, localSize, false); } void DISOpticalFlowImpl::ocl_prepareBuffers(UMat &I0, UMat &I1, UMat &flow, bool use_flow) { u_I0s.resize(coarsest_scale + 1); u_I1s.resize(coarsest_scale + 1); u_I1s_ext.resize(coarsest_scale + 1); u_I0xs.resize(coarsest_scale + 1); u_I0ys.resize(coarsest_scale + 1); u_Ux.resize(coarsest_scale + 1); u_Uy.resize(coarsest_scale + 1); vector<UMat> flow_uv(2); if (use_flow) { split(flow, flow_uv); u_initial_Ux.resize(coarsest_scale + 1); u_initial_Uy.resize(coarsest_scale + 1); } int fraction = 1; int cur_rows = 0, cur_cols = 0; for (int i = 0; i <= coarsest_scale; i++) { /* Avoid initializing the pyramid levels above the finest scale, as they won't be used anyway */ if (i == finest_scale) { cur_rows = I0.rows / fraction; cur_cols = I0.cols / fraction; u_I0s[i].create(cur_rows, cur_cols, CV_8UC1); resize(I0, u_I0s[i], u_I0s[i].size(), 0.0, 0.0, INTER_AREA); u_I1s[i].create(cur_rows, cur_cols, CV_8UC1); resize(I1, u_I1s[i], u_I1s[i].size(), 0.0, 0.0, INTER_AREA); /* These buffers are reused in each scale so we initialize them once on the finest scale: */ u_Sx.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_Sy.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0xx_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0yy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0xy_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0x_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0y_buf.create(cur_rows / patch_stride, cur_cols / patch_stride, CV_32FC1); u_I0xx_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0yy_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0xy_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0x_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_I0y_buf_aux.create(cur_rows, cur_cols / patch_stride, CV_32FC1); u_U.create(cur_rows, cur_cols, CV_32FC2); } else if (i > finest_scale) { cur_rows = u_I0s[i - 1].rows / 2; cur_cols = u_I0s[i - 1].cols / 2; u_I0s[i].create(cur_rows, cur_cols, CV_8UC1); resize(u_I0s[i - 1], u_I0s[i], u_I0s[i].size(), 0.0, 0.0, INTER_AREA); u_I1s[i].create(cur_rows, cur_cols, CV_8UC1); resize(u_I1s[i - 1], u_I1s[i], u_I1s[i].size(), 0.0, 0.0, INTER_AREA); } if (i >= finest_scale) { u_I1s_ext[i].create(cur_rows + 2 * border_size, cur_cols + 2 * border_size, CV_8UC1); copyMakeBorder(u_I1s[i], u_I1s_ext[i], border_size, border_size, border_size, border_size, BORDER_REPLICATE); u_I0xs[i].create(cur_rows, cur_cols, CV_16SC1); u_I0ys[i].create(cur_rows, cur_cols, CV_16SC1); spatialGradient(u_I0s[i], u_I0xs[i], u_I0ys[i]); u_Ux[i].create(cur_rows, cur_cols, CV_32FC1); u_Uy[i].create(cur_rows, cur_cols, CV_32FC1); variational_refinement_processors[i]->setAlpha(variational_refinement_alpha); variational_refinement_processors[i]->setDelta(variational_refinement_delta); variational_refinement_processors[i]->setGamma(variational_refinement_gamma); variational_refinement_processors[i]->setSorIterations(5); variational_refinement_processors[i]->setFixedPointIterations(variational_refinement_iter); if (use_flow) { resize(flow_uv[0], u_initial_Ux[i], Size(cur_cols, cur_rows)); divide(u_initial_Ux[i], static_cast<float>(fraction), u_initial_Ux[i]); resize(flow_uv[1], u_initial_Uy[i], Size(cur_cols, cur_rows)); divide(u_initial_Uy[i], static_cast<float>(fraction), u_initial_Uy[i]); } } fraction *= 2; } } bool DISOpticalFlowImpl::ocl_precomputeStructureTensor(UMat &dst_I0xx, UMat &dst_I0yy, UMat &dst_I0xy, UMat &dst_I0x, UMat &dst_I0y, UMat &I0x, UMat &I0y) { size_t globalSizeX[] = {(size_t)h}; size_t localSizeX[] = {16}; ocl::Kernel kernelX("dis_precomputeStructureTensor_hor", ocl::video::dis_flow_oclsrc); kernelX.args(ocl::KernelArg::PtrReadOnly(I0x), ocl::KernelArg::PtrReadOnly(I0y), (int)patch_size, (int)patch_stride, (int)w, (int)h, (int)ws, ocl::KernelArg::PtrWriteOnly(u_I0xx_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0yy_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0xy_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0x_buf_aux), ocl::KernelArg::PtrWriteOnly(u_I0y_buf_aux)); if (!kernelX.run(1, globalSizeX, localSizeX, false)) return false; size_t globalSizeY[] = {(size_t)ws}; size_t localSizeY[] = {16}; ocl::Kernel kernelY("dis_precomputeStructureTensor_ver", ocl::video::dis_flow_oclsrc); kernelY.args(ocl::KernelArg::PtrReadOnly(u_I0xx_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0yy_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0xy_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0x_buf_aux), ocl::KernelArg::PtrReadOnly(u_I0y_buf_aux), (int)patch_size, (int)patch_stride, (int)w, (int)h, (int)ws, ocl::KernelArg::PtrWriteOnly(dst_I0xx), ocl::KernelArg::PtrWriteOnly(dst_I0yy), ocl::KernelArg::PtrWriteOnly(dst_I0xy), ocl::KernelArg::PtrWriteOnly(dst_I0x), ocl::KernelArg::PtrWriteOnly(dst_I0y)); return kernelY.run(1, globalSizeY, localSizeY, false); } bool DISOpticalFlowImpl::ocl_calc(InputArray I0, InputArray I1, InputOutputArray flow) { UMat I0Mat = I0.getUMat(); UMat I1Mat = I1.getUMat(); bool use_input_flow = false; if (flow.sameSize(I0) && flow.depth() == CV_32F && flow.channels() == 2) use_input_flow = true; else flow.create(I1Mat.size(), CV_32FC2); UMat &u_flowMat = flow.getUMatRef(); coarsest_scale = min((int)(log(max(I0Mat.cols, I0Mat.rows) / (4.0 * patch_size)) / log(2.0) + 0.5), /* Original code search for maximal movement of width/4 */ (int)(log(min(I0Mat.cols, I0Mat.rows) / patch_size) / log(2.0))); /* Deepest pyramid level greater or equal than patch*/ if (coarsest_scale<0) CV_Error(cv::Error::StsBadSize, "The input image must have either width or height >= 12"); if (coarsest_scale<finest_scale) { // choose the finest level based on coarsest level. // Refs: https://github.com/tikroeger/OF_DIS/blob/2c9f2a674f3128d3a41c10e41cc9f3a35bb1b523/run_dense.cpp#L239 int original_img_width = I0.size().width; autoSelectPatchSizeAndScales(original_img_width); } ocl_prepareBuffers(I0Mat, I1Mat, u_flowMat, use_input_flow); u_Ux[coarsest_scale].setTo(0.0f); u_Uy[coarsest_scale].setTo(0.0f); for (int i = coarsest_scale; i >= finest_scale; i--) { w = u_I0s[i].cols; h = u_I0s[i].rows; ws = 1 + (w - patch_size) / patch_stride; hs = 1 + (h - patch_size) / patch_stride; if (!ocl_precomputeStructureTensor(u_I0xx_buf, u_I0yy_buf, u_I0xy_buf, u_I0x_buf, u_I0y_buf, u_I0xs[i], u_I0ys[i])) return false; if (!ocl_PatchInverseSearch(u_Ux[i], u_Uy[i], u_I0s[i], u_I1s_ext[i], u_I0xs[i], u_I0ys[i], 2, i)) return false; if (!ocl_Densification(u_Ux[i], u_Uy[i], u_Sx, u_Sy, u_I0s[i], u_I1s[i])) return false; if (variational_refinement_iter > 0) variational_refinement_processors[i]->calcUV(u_I0s[i], u_I1s[i], u_Ux[i].getMat(ACCESS_WRITE), u_Uy[i].getMat(ACCESS_WRITE)); if (i > finest_scale) { resize(u_Ux[i], u_Ux[i - 1], u_Ux[i - 1].size()); resize(u_Uy[i], u_Uy[i - 1], u_Uy[i - 1].size()); multiply(u_Ux[i - 1], 2, u_Ux[i - 1]); multiply(u_Uy[i - 1], 2, u_Uy[i - 1]); } } vector<UMat> uxy(2); uxy[0] = u_Ux[finest_scale]; uxy[1] = u_Uy[finest_scale]; merge(uxy, u_U); resize(u_U, u_flowMat, u_flowMat.size()); multiply(u_flowMat, 1 << finest_scale, u_flowMat); return true; } #endif void DISOpticalFlowImpl::calc(InputArray I0, InputArray I1, InputOutputArray flow) { CV_Assert(!I0.empty() && I0.depth() == CV_8U && I0.channels() == 1); CV_Assert(!I1.empty() && I1.depth() == CV_8U && I1.channels() == 1); CV_Assert(I0.sameSize(I1)); CV_Assert(I0.isContinuous()); CV_Assert(I1.isContinuous()); CV_OCL_RUN(flow.isUMat() && (patch_size == 8) && (use_spatial_propagation == true), ocl_calc(I0, I1, flow)); Mat I0Mat = I0.getMat(); Mat I1Mat = I1.getMat(); bool use_input_flow = false; if (flow.sameSize(I0) && flow.depth() == CV_32F && flow.channels() == 2) use_input_flow = true; else flow.create(I1Mat.size(), CV_32FC2); Mat flowMat = flow.getMat(); coarsest_scale = min((int)(log(max(I0Mat.cols, I0Mat.rows) / (4.0 * patch_size)) / log(2.0) + 0.5), /* Original code search for maximal movement of width/4 */ (int)(log(min(I0Mat.cols, I0Mat.rows) / patch_size) / log(2.0))); /* Deepest pyramid level greater or equal than patch*/ if (coarsest_scale<0) CV_Error(cv::Error::StsBadSize, "The input image must have either width or height >= 12"); if (coarsest_scale<finest_scale) { // choose the finest level based on coarsest level. // Refs: https://github.com/tikroeger/OF_DIS/blob/2c9f2a674f3128d3a41c10e41cc9f3a35bb1b523/run_dense.cpp#L239 int original_img_width = I0.size().width; autoSelectPatchSizeAndScales(original_img_width); } int num_stripes = getNumThreads(); prepareBuffers(I0Mat, I1Mat, flowMat, use_input_flow); Ux[coarsest_scale].setTo(0.0f); Uy[coarsest_scale].setTo(0.0f); for (int i = coarsest_scale; i >= finest_scale; i--) { w = I0s[i].cols; h = I0s[i].rows; ws = 1 + (w - patch_size) / patch_stride; hs = 1 + (h - patch_size) / patch_stride; precomputeStructureTensor(I0xx_buf, I0yy_buf, I0xy_buf, I0x_buf, I0y_buf, I0xs[i], I0ys[i]); if (use_spatial_propagation) { /* Use a fixed number of stripes regardless the number of threads to make inverse search * with spatial propagation reproducible */ parallel_for_(Range(0, 8), PatchInverseSearch_ParBody(*this, 8, hs, Sx, Sy, Ux[i], Uy[i], I0s[i], I1s_ext[i], I0xs[i], I0ys[i], 2, i)); } else { parallel_for_(Range(0, num_stripes), PatchInverseSearch_ParBody(*this, num_stripes, hs, Sx, Sy, Ux[i], Uy[i], I0s[i], I1s_ext[i], I0xs[i], I0ys[i], 1, i)); } parallel_for_(Range(0, num_stripes), Densification_ParBody(*this, num_stripes, I0s[i].rows, Ux[i], Uy[i], Sx, Sy, I0s[i], I1s[i])); if (variational_refinement_iter > 0) variational_refinement_processors[i]->calcUV(I0s[i], I1s[i], Ux[i], Uy[i]); if (i > finest_scale) { resize(Ux[i], Ux[i - 1], Ux[i - 1].size()); resize(Uy[i], Uy[i - 1], Uy[i - 1].size()); Ux[i - 1] *= 2; Uy[i - 1] *= 2; } } Mat uxy[] = {Ux[finest_scale], Uy[finest_scale]}; merge(uxy, 2, U); resize(U, flowMat, flowMat.size()); flowMat *= 1 << finest_scale; } void DISOpticalFlowImpl::collectGarbage() { I0s.clear(); I1s.clear(); I1s_ext.clear(); I0xs.clear(); I0ys.clear(); Ux.clear(); Uy.clear(); U.release(); Sx.release(); Sy.release(); I0xx_buf.release(); I0yy_buf.release(); I0xy_buf.release(); I0xx_buf_aux.release(); I0yy_buf_aux.release(); I0xy_buf_aux.release(); #ifdef HAVE_OPENCL u_I0s.clear(); u_I1s.clear(); u_I1s_ext.clear(); u_I0xs.clear(); u_I0ys.clear(); u_Ux.clear(); u_Uy.clear(); u_U.release(); u_Sx.release(); u_Sy.release(); u_I0xx_buf.release(); u_I0yy_buf.release(); u_I0xy_buf.release(); u_I0xx_buf_aux.release(); u_I0yy_buf_aux.release(); u_I0xy_buf_aux.release(); #endif for (int i = finest_scale; i <= coarsest_scale; i++) variational_refinement_processors[i]->collectGarbage(); variational_refinement_processors.clear(); } Ptr<DISOpticalFlow> DISOpticalFlow::create(int preset) { Ptr<DISOpticalFlow> dis = makePtr<DISOpticalFlowImpl>(); dis->setPatchSize(8); if (preset == DISOpticalFlow::PRESET_ULTRAFAST) { dis->setFinestScale(2); dis->setPatchStride(4); dis->setGradientDescentIterations(12); dis->setVariationalRefinementIterations(0); } else if (preset == DISOpticalFlow::PRESET_FAST) { dis->setFinestScale(2); dis->setPatchStride(4); dis->setGradientDescentIterations(16); dis->setVariationalRefinementIterations(5); } else if (preset == DISOpticalFlow::PRESET_MEDIUM) { dis->setFinestScale(1); dis->setPatchStride(3); dis->setGradientDescentIterations(25); dis->setVariationalRefinementIterations(5); } return dis; } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_1309_0
crossvul-cpp_data_good_2812_1
/***************************************************************** | | AP4 - stsz Atoms | | Copyright 2002-2008 Axiomatic Systems, LLC | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4StszAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Utils.h" /*---------------------------------------------------------------------- | dynamic cast support +---------------------------------------------------------------------*/ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_StszAtom) /*---------------------------------------------------------------------- | AP4_StszAtom::Create +---------------------------------------------------------------------*/ AP4_StszAtom* AP4_StszAtom::Create(AP4_Size size, AP4_ByteStream& stream) { AP4_UI08 version; AP4_UI32 flags; if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL; if (version != 0) return NULL; return new AP4_StszAtom(size, version, flags, stream); } /*---------------------------------------------------------------------- | AP4_StszAtom::AP4_StszAtom +---------------------------------------------------------------------*/ AP4_StszAtom::AP4_StszAtom() : AP4_Atom(AP4_ATOM_TYPE_STSZ, AP4_FULL_ATOM_HEADER_SIZE+8, 0, 0), m_SampleSize(0), m_SampleCount(0) { } /*---------------------------------------------------------------------- | AP4_StszAtom::AP4_StszAtom +---------------------------------------------------------------------*/ AP4_StszAtom::AP4_StszAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_STSZ, size, version, flags) { stream.ReadUI32(m_SampleSize); stream.ReadUI32(m_SampleCount); if (m_SampleSize == 0) { // means that the samples have different sizes // check for overflow if (m_SampleCount > (size-8)/4) { m_SampleCount = 0; return; } // read the entries AP4_Cardinal sample_count = m_SampleCount; m_Entries.SetItemCount(sample_count); unsigned char* buffer = new unsigned char[sample_count*4]; AP4_Result result = stream.Read(buffer, sample_count*4); if (AP4_FAILED(result)) { delete[] buffer; return; } for (unsigned int i=0; i<sample_count; i++) { m_Entries[i] = AP4_BytesToUInt32BE(&buffer[i*4]); } delete[] buffer; } } /*---------------------------------------------------------------------- | AP4_StszAtom::WriteFields +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::WriteFields(AP4_ByteStream& stream) { AP4_Result result; // sample size result = stream.WriteUI32(m_SampleSize); if (AP4_FAILED(result)) return result; // sample count result = stream.WriteUI32(m_SampleCount); if (AP4_FAILED(result)) return result; // entries if needed (the samples have different sizes) if (m_SampleSize == 0) { for (AP4_UI32 i=0; i<m_SampleCount; i++) { result = stream.WriteUI32(m_Entries[i]); if (AP4_FAILED(result)) return result; } } return result; } /*---------------------------------------------------------------------- | AP4_StszAtom::GetSampleCount +---------------------------------------------------------------------*/ AP4_UI32 AP4_StszAtom::GetSampleCount() { return m_SampleCount; } /*---------------------------------------------------------------------- | AP4_StszAtom::GetSampleSize +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::GetSampleSize(AP4_Ordinal sample, AP4_Size& sample_size) { // check the sample index if (sample > m_SampleCount || sample == 0) { sample_size = 0; return AP4_ERROR_OUT_OF_RANGE; } else { // find the size if (m_SampleSize != 0) { // constant size sample_size = m_SampleSize; } else { sample_size = m_Entries[sample - 1]; } return AP4_SUCCESS; } } /*---------------------------------------------------------------------- | AP4_StszAtom::SetSampleSize +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::SetSampleSize(AP4_Ordinal sample, AP4_Size sample_size) { // check the sample index if (sample > m_SampleCount || sample == 0) { return AP4_ERROR_OUT_OF_RANGE; } else { if (m_Entries.ItemCount() == 0) { // all samples must have the same size if (sample_size != m_SampleSize) { // not the same if (sample == 1) { // if this is the first sample, update the global size m_SampleSize = sample_size; return AP4_SUCCESS; } else { // can't have different sizes return AP4_ERROR_INVALID_PARAMETERS; } } } else { // each sample has a different size m_Entries[sample - 1] = sample_size; } return AP4_SUCCESS; } } /*---------------------------------------------------------------------- | AP4_StszAtom::AddEntry +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::AddEntry(AP4_UI32 size) { m_Entries.Append(size); m_SampleCount++; m_Size32 += 4; return AP4_SUCCESS; } /*---------------------------------------------------------------------- | AP4_StszAtom::InspectFields +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::InspectFields(AP4_AtomInspector& inspector) { inspector.AddField("sample_size", m_SampleSize); inspector.AddField("sample_count", m_Entries.ItemCount()); if (inspector.GetVerbosity() >= 2) { char header[32]; for (AP4_Ordinal i=0; i<m_Entries.ItemCount(); i++) { AP4_FormatString(header, sizeof(header), "entry %8d", i); inspector.AddField(header, m_Entries[i]); } } return AP4_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_2812_1
crossvul-cpp_data_good_1183_2
// This file is part of The New Aspell // Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #include <string.h> #include "getdata.hpp" #include "string.hpp" #include "asc_ctype.hpp" #include "iostream.hpp" namespace acommon { unsigned int linenumber = 0 ; bool getdata_pair(IStream & in, DataPair & d, String & buf) { char * p; // get first non blank line and count all read ones do { buf.clear(); buf.append('\0'); // to avoid some special cases if (!in.append_line(buf)) return false; d.line_num++; p = buf.mstr() + 1; while (*p == ' ' || *p == '\t') ++p; } while (*p == '#' || *p == '\0'); // get key d.key.str = p; while (*p != '\0' && ((*p != ' ' && *p != '\t' && *p != '#') || *(p-1) == '\\')) ++p; d.key.size = p - d.key.str; // figure out if there is a value and add terminate key d.value.str = p; // in case there is no value d.value.size = 0; if (*p == '#' || *p == '\0') {*p = '\0'; return true;} *p = '\0'; // skip any whitespace ++p; while (*p == ' ' || *p == '\t') ++p; if (*p == '\0' || *p == '#') {return true;} // get value d.value.str = p; while (*p != '\0' && (*p != '#' || *(p-1) == '\\')) ++p; // remove trailing white space and terminate value --p; while (*p == ' ' || *p == '\t') --p; if (*p == '\\' && *(p + 1) != '\0') ++p; ++p; d.value.size = p - d.value.str; *p = '\0'; return true; } char * unescape(char * dest, const char * src) { while (*src) { if (*src == '\\' && src[1]) { ++src; switch (*src) { case 'n': *dest = '\n'; break; case 'r': *dest = '\r'; break; case 't': *dest = '\t'; break; case 'f': *dest = '\f'; break; case 'v': *dest = '\v'; break; default: *dest = *src; } } else { *dest = *src; } ++src; ++dest; } *dest = '\0'; return dest; } bool escape(char * dest, const char * src, size_t limit, const char * others) { const char * begin = src; const char * end = dest + limit; if (asc_isspace(*src)) { if (dest == end) return false; *dest++ = '\\'; if (dest == end) return false; *dest++ = *src++; } while (*src) { if (dest == end) return false; switch (*src) { case '\n': *dest++ = '\\'; *dest = 'n'; break; case '\r': *dest++ = '\\'; *dest = 'r'; break; case '\t': *dest++ = '\\'; *dest = 't'; break; case '\f': *dest++ = '\\'; *dest = 'f'; break; case '\v': *dest++ = '\\'; *dest = 'v'; break; case '\\': *dest++ = '\\'; *dest = '\\'; break; case '#' : *dest++ = '\\'; *dest = '#'; break; default: if (others && strchr(others, *src)) *dest++ = '\\'; *dest = *src; } ++src; ++dest; } if (src > begin + 1 && asc_isspace(src[-1])) { --dest; *dest++ = '\\'; if (dest == end) return false; *dest++ = src[-1]; } *dest = '\0'; return true; } void to_lower(char * str) { for (; *str; str++) *str = asc_tolower(*str); } void to_lower(String & res, const char * str) { for (; *str; str++) res += asc_tolower(*str); } bool split(DataPair & d) { char * p = d.value; char * end = p + d.value.size; d.key.str = p; while (p != end) { ++p; if ((*p == ' ' || *p == '\t') && *(p-1) != '\\') break; } d.key.size = p - d.key.str; *p = 0; if (p != end) { ++p; while (p != end && (*p == ' ' || *p == '\t')) ++p; } d.value.str = p; d.value.size = end - p; return d.key.size != 0; } void init(ParmString str, DataPair & d, String & buf) { const char * s = str; while (*s == ' ' || *s == '\t') ++s; size_t l = str.size() - (s - str); buf.assign(s, l); d.value.str = buf.mstr(); d.value.size = l; } bool getline(IStream & in, DataPair & d, String & buf) { if (!in.getline(buf)) return false; d.value.str = buf.mstr(); d.value.size = buf.size(); return true; } char * get_nb_line(IStream & in, String & buf) { char * p; // get first non blank line do { if (!in.getline(buf)) return 0; p = buf.mstr(); while (*p == ' ' || *p == '\t') ++p; } while (*p == '#' || *p == '\0'); return p; } void remove_comments(String & buf) { char * p = buf.mstr(); char * b = p; while (*p && *p != '#') ++p; if (*p == '#') {--p; while (p >= b && asc_isspace(*p)) --p; ++p;} buf.resize(p - b); } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_1183_2
crossvul-cpp_data_bad_2946_1
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol(int row, int col) { static const char filter[16][16] = { {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2}, {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1}, {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1}, {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3}, {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2}, {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0}, {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1}, {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}}; if (filters == 1) return filter[(row + top_margin) & 15][(col + left_margin) & 15]; if (filters == 9) return xtrans[(row + 6) % 6][(col + 6) % 6]; return FC(row, col); } #if !defined(__FreeBSD__) static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return (p ? p - s : n); } /* add OS X version check here ?? */ #define strnlen(a, b) local_strnlen(a, b) #endif #ifdef LIBRAW_LIBRARY_BUILD static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten}; static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int); static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300, 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300, 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000}; static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1, LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11, LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35, LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83}; static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int); static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather, LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW}; static int Oly_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Tungsten, 3000, 0x100, 3300, 0x100, 3600, 0x100, 3900, LIBRAW_WBI_FL_W, 4000, 0x100, 4300, LIBRAW_WBI_FL_D, 4500, 0x100, 4800, LIBRAW_WBI_FineWeather, 5300, LIBRAW_WBI_Cloudy, 6000, LIBRAW_WBI_FL_N, 6600, LIBRAW_WBI_Shade, 7500, LIBRAW_WBI_Custom1, 0, LIBRAW_WBI_Custom2, 0, LIBRAW_WBI_Custom3, 0, LIBRAW_WBI_Custom4, 0}; static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash}; static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L}; static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int); static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf, len, 1); buf[len - 1] = 0; return r; } #define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp) #endif #if !defined(__GLIBC__) && !defined(__FreeBSD__) char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp(c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr(char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf, sizeof(buf) - 1) ushort CLASS sget2(uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define nonDNG 0 #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords, int maxlen) { line[maxlen - 1] = 0; char *p = line; int nwords = 0; while (1) { while (isspace(*p)) p++; if (*p == '\0') return nwords; words[nwords++] = p; while (!isspace(*p) && *p != '\0') p++; if (*p == '\0') return nwords; *p++ = '\0'; if (nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f) { if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data) { if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03" "\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5" "\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53" "\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea" "\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3" "\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7" "\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63" "\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd" "\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = {0xff, 0xff}; fread(str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4(uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = {0xff, 0xff, 0xff, 0xff}; fread(str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float(int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal(int type) { union { char c[8]; double d; } u, v; int i, rev; switch (type) { case 3: return (unsigned short)get2(); case 4: return (unsigned int)get4(); case 5: u.d = (unsigned int)get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short)get2(); case 9: return (signed int)get4(); case 10: u.d = (signed int)get4(); v.d = (signed int)get4(); return u.d / (v.d ? v.d : 1); case 11: return int_to_float(get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i = 0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts(ushort *pixel, int count) { if (fread(pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)pixel, (char *)pixel, count * 2); } void CLASS cubic_spline(const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len); if (!A) return; A[0] = (float *)(A + 2 * len); for (i = 1; i < 2 * len; i++) A[i] = A[0] + 2 * len * i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len - 1; i > 0; i--) { b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); d[i - 1] = x[i] - x[i - 1]; } for (i = 1; i < len - 1; i++) { A[i][i] = 2 * (d[i - 1] + d[i]); if (i > 1) { A[i][i - 1] = d[i - 1]; A[i - 1][i] = d[i - 1]; } A[i][len - 1] = 6 * (b[i + 1] - b[i]); } for (i = 1; i < len - 2; i++) { float v = A[i + 1][i] / A[i][i]; for (j = 1; j <= len - 1; j++) A[i + 1][j] -= v * A[i][j]; } for (i = len - 2; i > 0; i--) { float acc = 0; for (j = i; j <= len - 2; j++) acc += A[i][j] * c[j]; c[i] = (A[i][len - 1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len - 1; j++) { if (x[j] <= x_out && x_out <= x[j + 1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v + ((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free(A); } void CLASS canon_600_fixed_wb(int temp) { static const short mul[4][5] = { {667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}}; int lo, hi, i; float frac = 0; for (lo = 4; --lo;) if (*mul[lo] <= temp) break; for (hi = 0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i = 1; i < 5; i++) pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color(int ratio[2], int mar) { int clipped = 0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar * 4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = {0, 0}; int test[8], total[2][8], ratio[2][2], stat[2]; memset(&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row = 14; row < height - 14; row += 4) for (col = 10; col < width; col += 2) { for (i = 0; i < 8; i++) test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1)); for (i = 0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i = 0; i < 4; i++) if (abs(test[i] - test[i + 4]) > 50) goto next; for (i = 0; i < 2; i++) { for (j = 0; j < 4; j += 2) ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j]; stat[i] = canon_600_color(ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i = 0; i < 2; i++) if (stat[i]) for (j = 0; j < 2; j++) test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10; for (i = 0; i < 8; i++) total[st][i] += test[i]; count[st]++; next:; } if (count[0] | count[1]) { st = count[0] * 200 < count[1]; for (i = 0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409}, {-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007}, {-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528}, {-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}}; int t = 0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t = 1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t = 3; else if (yc <= 2) t = 4; } if (flash_used) t = 5; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow = row = 0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row * raw_width; for (dp = data; dp < data + 1120; dp += 10, pix += 8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6); } if ((row += 2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}}; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { if ((val = BAYER(row, col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row, col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row = 0; row < 100; row++) { fseek(ifp, row * 3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff(int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf = 0; static int vbits = 0, reset = 0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar)c; vbits += 8; } c = bitbuf << (32 - vbits) >> (32 - nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar)huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n, 0) #define gethuff(h) getbithuff(*h, h + 1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort *CLASS make_decoder_ref(const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max = 16; max && !count[max]; max--) ; huff = (ushort *)calloc(1 + (1 << max), sizeof *huff); merror(huff, "make_decoder()"); huff[0] = max; for (h = len = 1; len <= max; len++) for (i = 0; i < count[len]; i++, ++*source) for (j = 0; j < 1 << (max - len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); } void CLASS crw_init_tables(unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff}, {0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff}, {0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff}, }; static const uchar second_tree[3][180] = { {0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04, 0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0, 0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29, 0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9, 0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91, 0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4, 0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7, 0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64, 0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3, 0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff}, {0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03, 0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32, 0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61, 0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59, 0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56, 0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85, 0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82, 0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9, 0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64, 0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff}, {0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05, 0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22, 0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58, 0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48, 0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88, 0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94, 0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a, 0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62, 0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1, 0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}}; if (table > 2) table = 2; huff[0] = make_decoder(first_tree[table]); huff[1] = make_decoder(second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret = 1, i; fseek(ifp, 0, SEEK_SET); fread(test, 1, sizeof test, ifp); for (i = 540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i + 1]) return 1; ret = 0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2]; crw_init_tables(tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; nblocks = MIN(8, raw_height - row) * raw_width >> 6; for (block = 0; block < nblocks; block++) { memset(diffbuf, 0, sizeof diffbuf); for (i = 0; i < 64; i++) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i = 0; i < 64; i++) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek(ifp, 26 + row * raw_width / 4, SEEK_SET); for (prow = pixel, i = 0; i < raw_width * 2; i++) { c = fgetc(ifp); for (r = 0; r < 8; r += 2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free(huff[c]); throw; } #endif FORC(2) free(huff[c]); } int CLASS ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end(struct jhead *jh) { int c; FORC4 if (jh->free[c]) free(jh->free[c]); free(jh->row); } int CLASS ljpeg_diff(ushort *huff) { int len, diff; if (!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; return diff; } ushort *CLASS ljpeg_row(int jrow, struct jhead *jh) { int col, c, diff, pred, spred = 0; ushort mark = 0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits - 1); if (jrow) { fseek(ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1); for (col = 0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff(jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0; struct jhead jh; ushort *rp; if (!ljpeg_start(&jh, 0)) return; if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if (jh.clrs == 4 && jwide >= raw_width * 2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2; for (jcol = 0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow * jwide + jcol; i = jidx / (cr2_slice[1] * raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1] * raw_height); row = jidx / cr2_slice[1 + j]; col = jidx % cr2_slice[1 + j] + i * cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--, raw_width); if (row > raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 3); #endif if ((unsigned)row < raw_height) RAW(row, col) = val; if (++col >= raw_width) col = (row++, 0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif ljpeg_end(&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp = 0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c; int v[3] = {0, 0, 0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start(&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if (load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol = slice = 0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width - 1) ecol = raw_width & -2; for (row = 0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short(*)[4])image + row * width; for (col = scol; col < ecol; col += 2, jcol += jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *)ljpeg_row(jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC(jh.clrs - 2) { ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else #endif { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 16384; ip[col][2] = rp[jcol + jh.clrs - 1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end(&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp = model2; *cp && !isdigit(*cp); cp++) ; sscanf(cp, "%d.%d.%d", v, v + 1, v + 2); ver = (v[0] * 1000 + v[1]) * 1000 + v[2]; hue = (jh.sraw + 1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short(*)[4])image; rp = ip[0]; for (row = 0; row < height; row++, ip += width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col = 0; col < width; col += 2) for (c = 1; c < 3; c++) if (row == height - 1) { ip[col][c] = ip[col - width][c]; } else { ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1; } } for (col = 1; col < width; col += 2) for (c = 1; c < 3; c++) if (col == width - 1) ip[col][c] = ip[col - 1][c]; else ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)) #endif for (; rp < ip[0]; rp += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14); pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14); pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } height = saved_h; width = saved_w; #endif ljpeg_end(&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row, col) = curve[**rp]; *rp += tiff_samples; } else { #ifdef LIBRAW_LIBRARY_BUILD if (row < raw_height && col < raw_width) FORC(tiff_samples) image[row * raw_width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #else if (row < height && col < width) FORC(tiff_samples) image[row * width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #endif } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct(struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = {0}; static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; if (!cs[0]) FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2; memset(work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0]; for (i = 1; i < 64; i++) { len = gethuff(jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len - 1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c]; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); if (!ljpeg_start(&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN(is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow = 0; jrow + 7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol = 0; jcol + 7 < jh.wide; jcol += 8) { ljpeg_idct(&jh); rp = jh.idct; row = trow + jcol / tile_width + jrow * 2; col = tcol + jcol % tile_width; for (i = 0; i < 16; i += 2) for (j = 0; j < 8; j++) adobe_copy_pixel(row + i, col + j, &rp); } } break; case 0xc3: for (row = col = jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); for (jcol = 0; jcol < jwide; jcol++) { adobe_copy_pixel(trow + row, tcol + col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif fseek(ifp, save + 4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end(&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel); merror(pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts(pixel, raw_width * tiff_samples); else { getbits(-1); for (col = 0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp = pixel, col = 0; col < raw_width; col++) adobe_copy_pixel(row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek(ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek(ifp, data_offset, SEEK_SET); getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width * 3 * tiff_bps / 8; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for (int row = 0; row < raw_height; row++) { int red = fread(buf, 1, bufsize, ifp); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (tiff_bps <= 8) for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } else for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */ 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */ 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}, {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */ 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}, {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */ 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */ 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}, {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */ 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff; fseek(ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek(ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts(vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize - 1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i = 0; i < csize; i++) curve[i * step] = get2(); for (i = 0; i < max; i++) curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; fseek(ifp, meta_offset + 562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts(curve, max = csize); while (curve[max - 2] == curve[max - 1]) max--; huff = make_decoder(nikon_tree[tree]); fseek(ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min = row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free(huff); huff = make_decoder(nikon_tree[tree + 1]); max += (min = 16) << 1; } for (col = 0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len - shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(huff); throw; } #endif free(huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf = 0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; } for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8; FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705 * yuv[3]; rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3]; rgb[2] = yuv[b] + 1.732446 * yuv[2]; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = {0x00, 0x55, 0xaa, 0xff}; memset(histo, 0, sizeof histo); fseek(ifp, -2000, SEEK_END); for (i = 0; i < 2000; i++) histo[fgetc(ifp)]++; for (i = 0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek(ifp, 0, SEEK_SET); for (i = 0; i < 1024; i++) { fread(t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { {0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}}; fseek(ifp, 3072, SEEK_SET); fread(dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i = 0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy(make, table[i].t_make); strcpy(model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek(ifp, -sizeof tail, SEEK_END); fread(tail, 1, sizeof tail, ifp); for (nz = i = 0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)malloc(thumb_length); merror(thumb, "ppm_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread(thumb, 1, thumb_length, ifp); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)calloc(thumb_length, 2); merror(thumb, "ppm16_thumb()"); read_shorts((ushort *)thumb, thumb_length); for (i = 0; i < thumb_length; i++) thumb[i] = ((ushort *)thumb)[i] >> 8; fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = {"012", "102"}; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width * thumb_height; thumb = (char *)calloc(colors, thumb_length); merror(thumb, "layer_thumb()"); fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread(thumb, thumb_length, colors, ifp); for (i = 0; i < thumb_length; i++) FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp); free(thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *)calloc(thumb_length, 2); merror(thumb, "rollei_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts(thumb, thumb_length); for (i = 0; i < thumb_length; i++) { putc(thumb[i] << 3, ofp); putc(thumb[i] >> 5 << 2, ofp); putc(thumb[i] >> 11 << 3, ofp); } free(thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread(pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i = 0; i < 10; i += 2) { todo[i] = iten++; todo[i + 1] = pixel[i] << 8 | pixel[i + 1]; buffer = pixel[i] >> 2 | buffer << 6; } for (; i < 16; i += 2) { todo[i] = isix++; todo[i + 1] = buffer >> (14 - i) * 5; } for (i = 0; i < 16; i += 2) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; } void CLASS phase_one_flat_field(int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts(head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *)calloc(nc * wide, sizeof *mrow); merror(mrow, "phase_one_flat_field()"); for (y = 0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) { num = is_float ? getreal(11) : get2() / 32768.0; if (y == 0) mrow[c * wide + x] = num; else mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5]; } if (y == 0) continue; rend = head[1] + y * head[5]; for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++) { for (x = 1; x < wide; x++) { for (c = 0; c < nc; c += 2) { mult[c] = mrow[c * wide + x - 1]; mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4]; } cend = head[0] + x * head[4]; for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++) { c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0; if (!(c & 1)) { c = RAW(row, col) * mult[c]; RAW(row, col) = LIM(c, 0, 65535); } for (c = 0; c < nc; c += 2) mult[c] += mult[c + 1]; } } for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) mrow[c * wide + x] += mrow[(c + 1) * wide + x]; } } free(mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff = INT_MAX, off_412 = 0; /* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2}, {0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Phase One correction...\n")); #endif fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i = 0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i = 0; i < 0x10000; i++) { num = (poly[5] * i + poly[3]) * i + poly[1]; curve[i] = LIM(num, 0, 65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i = 0; i < 4; i++) poly[i] = getreal(11); for (i = 0; i < 0x10000; i++) { for (num = 0, j = 4; j--;) num = num * i + poly[j]; curve[i] = LIM(num + i, 0, 65535); } apply: /* apply to whole image */ for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1) * ph1.split_col; col < raw_width; col++) RAW(row, col) = curve[RAW(row, col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row = 0; row < raw_height; row++) if (FC(row - top_margin, col - left_margin) == 1) { for (sum = i = 0; i < 4; i++) sum += val[i] = raw(row + dir[i][0], col + dir[i][1]); for (max = i = 0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row, col) = (sum - val[max]) / 3.0 + 0.5; } else { for (sum = 0, i = 8; i < 12; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row - top_margin, col - left_margin) != 1) * 4; for (sum = 0, i = j; i < j + 8; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field(1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field(0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field(0, 4); } else if (tag == 0x412) { fseek(ifp, 36, SEEK_CUR); diff = abs(get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1 + i] = lc[qr][qc][i]; cf[1 + i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = {{1, 1}, {1, 1}}; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col); RAW(row, col) = LIM(i, 0, 65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1 + i] = ref[i]; cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek(ifp, save, SEEK_SET); } if (off_412) { fseek(ifp, off_412, SEEK_SET); for (i = 0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6); merror(yval[0], "phase_one_correct()"); yval[1] = (float *)(yval[0] + head[1] * head[3]); xval[0] = (ushort *)(yval[1] + head[2] * head[4]); xval[1] = (ushort *)(xval[0] + head[1] * head[3]); get2(); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) yval[i][j] = getreal(11); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) xval[i][j] = get2(); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { cfrac = (float)col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row, col) * 0.5; for (i = cip; i < cip + 2; i++) { for (k = j = 0; j < head[1]; j++) if (num < xval[0][k = head[1] * i + j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]); mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac); } i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row, col) = LIM(i, 0, 65535); } } free(yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek(ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555 : 0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()"); if (ph1.black_col) { fseek(ifp, ph1.black_col, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2); } if (ph1.black_row) { fseek(ifp, ph1.black_row, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2); } } #endif fseek(ifp, data_offset, SEEK_SET); read_shorts(raw_image, raw_width * raw_height); if (ph1.format) for (i = 0; i < raw_width * raw_height; i += 2) { a = raw_image[i + 0] ^ akey; b = raw_image[i + 1] ^ bkey; raw_image[i + 0] = (a & t_mask) | (b & ~t_mask); raw_image[i + 1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff(int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf = 0; static int vbits = 0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64 - vbits) >> (64 - nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar)huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n, 0) #define ph1_huff(h) ph1_bithuff(*h, h + 1) void CLASS phase_one_load_raw_c() { static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13}; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short(*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2); merror(pixel, "phase_one_load_raw_c()"); offset = (int *)(pixel + raw_width); fseek(ifp, strip_offset, SEEK_SET); for (row = 0; row < raw_height; row++) offset[row] = get4(); c_black = (short(*)[2])(offset + raw_height); fseek(ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts((ushort *)c_black[0], raw_height * 2); r_black = c_black + raw_height; fseek(ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts((ushort *)r_black[0], raw_width * 2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort)); } #endif for (i = 0; i < 256; i++) curve[i] = i * i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col = 0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i = 0; i < 2; i++) { for (j = 0; j < 5 && !ph1_bits(1); j++) ; if (j--) len[i] = length[j * 2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col = 0; col < raw_width; col++) { int shift = ph1.format == 8 ? 0 : 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row, col) = i; } #else if (ph1.format == 8) memmove(&RAW(row, 0), &pixel[0], raw_width * 2); else for (col = 0; col < raw_width; col++) RAW(row, col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start(&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *)calloc(raw_width, 3 * sizeof **back); merror(back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c * raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c + 3) & 3] = back[c]; for (col = 0; col < raw_width; col += 2) { for (s = 0; s < tiff_samples * 2; s += 2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s + c] = ph1_bits(len[c]); if ((diff[s + c] & (1 << (len[c] - 1))) == 0) diff[s + c] -= (1 << len[c]) - 1; if (diff[s + c] == 65535) diff[s + c] = -32768; } } for (s = col; s < col + 2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s - 2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s] / 2 - back[0][s - 2] / 2; break; } f = (row & 1) * 3 ^ ((col + s) & 1); FORC(tiff_samples) { pred += diff[(s & 1) * tiff_samples + c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row, s) = upix; if (image) { urow = row - top_margin + (c & 1); ucol = col - left_margin - ((c >> 1) & 1); ip = &image[urow * width + ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(back[4]); ljpeg_end(&jh); throw; } #endif free(back[4]); ljpeg_end(&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel = 0; unsigned tile = 0, r, c, row, col; if (!filters || !raw_image) { pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r = 0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek(ifp, data_offset + 4 * tile++, SEEK_SET); fseek(ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters && raw_image) pixel = raw_image + r * raw_width; read_shorts(pixel, raw_width); if (!filters && image && (row = r - top_margin) < height) for (col = 0; col < width; col++) image[row * width + col][c] = pixel[col + left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free(pixel); } } void CLASS unpacked_load_raw() { int row, col, bits = 0; while (1 << ++bits < maximum) ; read_shorts(raw_image, raw_width * raw_height); if (maximum < 0xffff || load_flags) for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < maximum) ; for (row = raw_height - 1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM(shot_select, 1, 4) - 1; fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot = 0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); for (row = 0; row < raw_height; row++) { read_shorts(pixel, raw_width); if ((r = row - top_margin - (shot >> 1 & 1)) >= height) continue; for (col = 0; col < raw_width; col++) { if ((c = col - left_margin - (shot & 1)) >= width) continue; image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short)); merror(buf, "imacon_full_load_raw"); #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf, width * 3); unsigned short(*rowp)[4] = &image[row * width]; for (col = 0; col < width; col++) { rowp[col][0] = buf[col * 3]; rowp[col][1] = buf[col * 3 + 1]; rowp[col][2] = buf[col * 3 + 2]; rowp[col][3] = 0; } #else for (col = 0; col < width; col++) read_shorts(image[row * width + col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf = 0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height + 1) >> 1; for (irow = 0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits = 0, tiff_compress) fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET); else { fseek(ifp, 0, SEEK_END); fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col = 0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); RAW(row, col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom() { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek(ifp, 0xb0 - 0x20, SEEK_CUR); fread(&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = {0, 0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *)malloc(dwide * 2); merror(data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } #endif free(data); maximum = 0x3ff; if (strncmp(make, "OmniVision", 10)) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1)); merror(words, "canon_rmf_load_raw"); #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words, sizeof(int), raw_width / 3, ifp); for (col = 0; col < raw_width - 2; col += 3) { bits = words[col / 3]; FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #else for (col = 0; col < raw_width - 2; col += 3) { bits = get4(); FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits(int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits = 0; if (!vbits) { fread(buf + load_flags, 1, 0x4000 - load_flags, ifp); fread(buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS panasonic_16x10_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_DECODE_RAW; #endif } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n = 0] = 0xc0c; for (i = 12; i--;) FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i; fseek(ifp, 7, SEEK_CUR); getbits(-1); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(acarry, 0, sizeof acarry); for (col = 0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++) ; low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12, huff)) == 12) high = getbits(16 - nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row, col - 2); else if (col < 2) pred = RAW(row - 2, col); else { w = RAW(row, col - 2); n = RAW(row - 2, col); nw = RAW(row - 2, col - 2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w - nw) > 32 || ABS(n - nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w - nw) > ABS(n - nw) ? w : n; } if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow = 0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col = 0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1; RAW(row, 1) = pixel[1] << 1; RAW(row, 1533) = pixel[765] << 1; } else for (col = row & 1; col < 1534; col += 2) RAW(row, col) = pixel[col / 2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89}; static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8}, {-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}}; static const short t_curve[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99, 101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261, 265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357, 361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453, 457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620, 631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866, 878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023}; int rb, row, col, sharp, val = 0; getbits(-1); memset(pixel, 0x80, sizeof pixel); for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 2 + (row & 1); col < width + 2; col += 2) { val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val, 0, 255); if (col < 4) pixel[row][col - 2] = pixel[row + 1][~row & 1] = val; if (row == 2) pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val; } pixel[row][col] = val; } for (rb = 0; rb < 2; rb++) for (row = 2 + rb; row < height + 2; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) + ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val, 0, 255); if (row < 4) pixel[row - 2][col + 2] = val; if (col < 4) pixel[row + 2][col - 2] = val; } } for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100; pixel[row][col] = LIM(val, 0, 255); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = t_curve[pixel[row + 2][col + 2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char)getbithuff(8, huff[tree])) #define FORYX \ for (y = 1; y < 3; y++) \ for (x = col + 1; x >= col; x--) #define PREDICTOR \ (c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4) #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC optimize("no-aggressive-loop-optimizations") #endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6, 8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2, 4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3, 3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7, 5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5, 3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0, 2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2, 2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55, 6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37}; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = {16, 16, 16}, mul[3], buf[3][3][386]; static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383}; for (i = 2; i < 12; i += 2) for (c = pt[i - 2]; c <= pt[i]; c++) curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5; for (s = i = 0; i < sizeof src; i += 2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1); getbits(-1); for (i = 0; i < sizeof(buf) / sizeof(short); i++) ((short *)buf)[i] = 2048; for (row = 0; row < height; row += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10 : 12; x = ~((~0u) << (s - 1)); val <<= 12 - s; for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r = 0; r <= !c; r++) { buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7; for (tree = 1, col = width / 2; col > 0;) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y = 0; y < 2; y++) for (x = 0; x < width / 2; x++) { val = (buf[c][y + 1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val; else RAW(row + r * 2 + y, x * 2 + y) = val; } memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c); } } for (y = row; y < row + 4; y++) for (x = 0; x < width; x++) if ((x + y) & 1) { r = x ? x - 1 : x + 1; s = x + 1 < width ? x + 1 : x - 1; val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2; if (val < 0) val = 0; RAW(y, x) = val; } } for (i = 0; i < height * width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread(jpeg_buffer, 1, 4096, ifp); swab(jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; int row, col; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress(&cinfo); longjmp(failure, 3); } buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if (data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf, "kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char *)malloc(width * 3); jpeg_create_decompress(&cinfo); merror(pixel_buf, "kodak_jpeg_load_raw"); fread(jpg_buf, data_size, 1, ifp); swab((char *)jpg_buf, (char *)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } } catch (...) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve(double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; unsigned sorder = order, ntags, opcode, deg, i, j, c; unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek(ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek(ifp, get4(), SEEK_CUR); continue; } fseek(ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek(ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i = 0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i = 0; i < 256; i++) { for (tot = j = 0; j <= deg; j++) tot += coeff[j] * pow(i / 255.0, (int)j); cur[c][i] = tot * 0xffff; } } order = sorder; } else { gamma_curve(1 / 2.4, 12.92, 1, 255); FORC3 memcpy(cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); while (trow < raw_height) { fseek(ifp, save += 4, SEEK_SET); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src(&cinfo, ifp); #endif jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < cinfo.output_width && tcol + col < width; col++) { FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { jpeg_destroy_decompress(&cinfo); throw; } #endif jpeg_abort_decompress(&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress(&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = {162, 192, 187, 92}; static const int add[4] = {0, 636, 424, 212}; uchar pixel[848]; int row, shift, col; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col = 0; col < width; col++) RAW(row, col) = (ushort)pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *)calloc(raw_width, sizeof *pixel); merror(pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, raw_width, ifp) < raw_width) derror(); for (col = 0; col < raw_width; col++) RAW(row, col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel); merror(pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek(ifp, raw_width * 32, SEEK_CUR); for (col = 0; col < width; col++) { y = pixel[col * 2]; cb = pixel[(col * 2 & -4) | 1] - 128; cr = pixel[(col * 2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel); merror(pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread(pixel, raw_width, 3, ifp) < 3) derror(); for (col = 0; col < width; col++) { y = pixel[width * 2 * (row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2) + 1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { {0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder(kodak_tree[c]); ns = (raw_height + 63) >> 5; pixel = (uchar *)malloc(raw_width * 32 + ns * 4); merror(pixel, "kodak_262_load_raw()"); strip = (int *)(pixel + raw_width * 32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek(ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col = 0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi - 2 : pi - raw_width - 1; pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi - 2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff(huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row, col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); FORC(2) free(huff[c]); } int CLASS kodak_65000_decode(short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf = 0; int save, bits = 0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i = 0; i < bsize; i += 2) { c = fgetc(ifp); if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12) { fseek(ifp, save, SEEK_SET); for (i = 0; i < bsize; i += 8) { read_shorts(raw, 6); out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j = 0; j < 6; j++) out[i + 2 + j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i = 0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j = 0; j < 32; j += 8) bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8)); bits += 32; } diff = bitbuf & (0xffff >> (16 - len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* 264 looks enough */ int row, col, len, pred[2], ret, i; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { pred[0] = pred[1] = 0; len = MIN(256, width - col); ret = kodak_65000_decode(buf, len); for (i = 0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx < 0xffff) { if ((RAW(row, col + i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10; for (row = 0; row < height; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 128) { len = MIN(128, width - col); kodak_65000_decode(buf, len * 3); y[0][1] = y[1][1] = cb = cr = 0; for (bp = buf, i = 0; i < len; i += 2, bp += 2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) { if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits) derror(); ip = image[(row + j) * width + col + i + k]; FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3], ret; ushort *ip = image[0]; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { len = MIN(256, width - col); ret = kodak_65000_decode(buf, len * 3); memset(rgb, 0, sizeof rgb); for (bp = buf, i = 0; i < len; i++, ip += 4) #ifdef LIBRAW_LIBRARY_BUILD if (load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row = 0; row < height; row++) for (col = 0; col < width; col++) read_shorts(image[row * width + col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt(unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p = 0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31; for (p = 4; p < 127; p++) pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31; for (p = 0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek(ifp, 200896, SEEK_SET); fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek(ifp, 164600, SEEK_SET); fread(head, 1, 40, ifp); sony_decrypt((unsigned *)head, 10, 1, key); for (i = 26; i-- > 22;) key = key << 8 | head[i]; fseek(ifp, data_offset, SEEK_SET); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; if (fread(pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key); for (col = 0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809, 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201}; int i, c, n, col, row, sum = 0; huff[0] = 15; for (n = i = 0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--;) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row = 0; row < raw_height + 1; row += 2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row, col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *)malloc(raw_width + 1); merror(data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread(data, 1, raw_width, ifp); for (dp = data, col = 0; col < raw_width - 30; dp += 16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++) ; #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i] = 0; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i = 0; i < 16; i++, col += 2) { unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2]; unsigned step = 1 << sh; RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr ? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000) : 0; } } else { for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1]; } #else for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1 : 31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum = 10000; #endif free(data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, strip_offset + row * 4, SEEK_SET); fseek(ifp, data_offset + get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7 : 4; for (col = 0; col < raw_width; col += 16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); if (c == 14) c = -1; } } } for (row = 0; row < raw_height - 1; row += 2) for (col = 0; col < raw_width - 1; col += 2) SWAP(RAW(row, col + 1), RAW(row + 1, col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709, 0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402}; ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n = i = 0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek(ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(), get2()); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4; prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green prow[~row & 1] = &RAW(row - 2, 0); // red and blue for (tab = 0; tab + 15 < raw_width; tab += 16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4 * ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row, tab - 2 + (col & 1)) : init) : (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1; diff = ph1_bits(i = len[c >> 2]); if (diff >> (i - 1)) diff -= 1 << i; diff = diff * (mag * 2 + 1) + mag; RAW(row, col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment(unsigned seg[2][2], int holes) { uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {3, 3, 0, 0, 63, 47, 31, 15, 0}}; int low, high = 0xff, carry = 0, nbits = 8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[] = {0, 0}; ushort data = 0, range = 0; fseek(ifp, seg[0][1] + 1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width * raw_height) seg[1][0] = raw_width * raw_height; for (pix = seg[0][0]; pix < seg[1][0]; pix++) { for (s = 0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits - 1)) - 1)) << 1) | ((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4); for (bin = 0; hist[s][bin + 5] > count; bin++) ; low = hist[s][bin + 5] * (high >> 4) >> 2; if (bin) high = hist[s][bin + 4] * (high >> 4) >> 2; high -= low; for (nbits = 0; high << nbits < 128; nbits++) ; range = (range + low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next + 1) & hist[s][0]; hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1) { if (bin < hist[s][1]) for (i = bin; i < hist[s][1]; i++) hist[s][i + 5]--; else if (next <= bin) for (i = hist[s][1]; i < bin; i++) hist[s][i + 5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if (pix >= raw_width * raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek(ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment(seg, 0); } int CLASS median4(int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i = 1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes(int holes) { int row, col, val[4]; for (row = 2; row < height - 2; row++) { if (!HOLE(row)) continue; for (col = 1; col < width - 1; col += 4) { val[0] = RAW(row - 1, col - 1); val[1] = RAW(row - 1, col + 1); val[2] = RAW(row + 1, col - 1); val[3] = RAW(row + 1, col + 1); RAW(row, col) = median4(val); } for (col = 2; col < width - 2; col += 4) if (HOLE(row - 2) || HOLE(row + 2)) RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1; else { val[0] = RAW(row, col - 2); val[1] = RAW(row, col + 2); val[2] = RAW(row - 2, col); val[3] = RAW(row + 2, col); RAW(row, col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek(ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar)fgetc(ifp); fseek(ifp, offset, SEEK_SET); for (i = 0; i < nseg * 2; i++) ((unsigned *)seg)[i] = get4() + data_offset * (i & 1); fseek(ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek(ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i = 0; i < nseg; i++) smal_decode_segment(seg + i, holes); if (holes) fill_holes(holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen(ifname, "rb"); #else in = (jas_stream_t *)ifp->make_jas_stream(); if (!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek(in, data_offset + 20, SEEK_SET); jimg = jas_image_decode(in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp(failure, 3); #else if (!jimg) { jas_stream_close(in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create(height / 2, width / 2); merror(jmat, "redcine_load_raw()"); img = (ushort *)calloc((height + 2), (width + 2) * 2); merror(img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat); data = jas_matrix_getref(jmat, 0, 0); for (row = c >> 1; row < height; row += 2) for (col = c & 1; col < width; col += 2) img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2]; } for (col = 1; col <= width; col++) { img[col] = img[2 * (width + 2) + col]; img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col]; } for (row = 0; row < height + 2; row++) { img[row * (width + 2)] = img[row * (width + 2) + 2]; img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3]; } for (row = 1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1)); for (; col <= width; col += 2, pix += 2) { c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c, 0, 4095); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag = true; } #endif free(img); jas_matrix_destroy(jmat); jas_image_destroy(jimg); jas_stream_close(in); #ifdef LIBRAW_LIBRARY_BUILD if (fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width * 2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row = 0; row < raw_height - top_margin * 2; row++) { for (col = 0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < height && c < width) BAYER(r, c) = RAW(row + top_margin, col + left_margin); } } } else { for (row = 0; row < height; row++) for (col = 0; col < width; col++) BAYER2(row, col) = RAW(row + top_margin, col + left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin + height; mask[0][3] += left_margin; mask[1][1] += left_margin + width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset(mblack, 0, sizeof mblack); for (zero = m = 0; m < 8; m++) for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++) for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++) { c = FC(row - top_margin, col - left_margin); mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)]; mblack[4 + c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4 + c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2); #endif for (row = 0; row < height; row++) for (col = 0; col < width; col++) if (BAYER(row, col) == 0) { tot = n = 0; for (r = row - 2; r <= row + 2; r++) for (c = col - 2; c <= col + 2; c++) if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c)) tot += (n++, BAYER(r, c)); if (n) BAYER(row, col) = tot / n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2); #endif } static const uchar xlat[2][256] = { {0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3, 0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d, 0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b, 0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b, 0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95, 0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b, 0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d, 0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43, 0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f, 0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad, 0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3, 0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17, 0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07, 0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7}, {0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9, 0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68, 0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95, 0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68, 0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42, 0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca, 0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87, 0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45, 0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94, 0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26, 0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe, 0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25, 0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65, 0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}}; void CLASS gamma_curve(double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2] = {0, 0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0) { for (i = 0; i < 48; i++) { g[2] = (bnd[0] + bnd[1]) / 2; if (g[0]) bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2]; else bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1 / g[0] - 1); } if (g[0]) g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1; else g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1; if (!mode--) { memcpy(gamm, g, sizeof gamm); return; } for (i = 0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double)i / imax) < 1) curve[i] = 0x10000 * (mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1)) : (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2])))); } } void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) work[i][j] = j == i + 3; for (j = 0; j < 3; j++) for (k = 0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i = 0; i < 3; i++) { num = work[i][i]; for (j = 0; j < 6; j++) work[i][j] /= num; for (k = 0; k < 3; k++) { if (k == i) continue; num = work[k][i]; for (j = 0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i = 0; i < size; i++) for (j = 0; j < 3; j++) for (out[i][j] = k = 0; k < 3; k++) out[i][j] += work[j][k + 3] * in[i][k]; } void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j = 0; j < 3; j++) for (cam_rgb[i][j] = k = 0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i = 0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if (num > 0.00001) { for (j = 0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j = 0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse(cam_rgb, inverse, colors); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin {0.377, 0.345, 35.8}, // Light Skin {0.247, 0.251, 19.3}, // Blue Sky {0.337, 0.422, 13.3}, // Foliage {0.265, 0.240, 24.3}, // Blue Flower {0.261, 0.343, 43.1}, // Bluish Green {0.506, 0.407, 30.1}, // Orange {0.211, 0.175, 12.0}, // Purplish Blue {0.453, 0.306, 19.8}, // Moderate Red {0.285, 0.202, 6.6}, // Purple {0.380, 0.489, 44.3}, // Yellow Green {0.473, 0.438, 43.1}, // Orange Yellow {0.187, 0.129, 6.1}, // Blue {0.305, 0.478, 23.4}, // Green {0.539, 0.313, 12.0}, // Red {0.448, 0.470, 59.1}, // Yellow {0.364, 0.233, 19.8}, // Magenta {0.196, 0.252, 19.8}, // Cyan {0.310, 0.316, 90.0}, // White {0.310, 0.316, 59.1}, // Neutral 8 {0.310, 0.316, 36.2}, // Neutral 6.5 {0.310, 0.316, 19.8}, // Neutral 5 {0.310, 0.316, 9.0}, // Neutral 3.5 {0.310, 0.316, 3.1}}; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset(gmb_cam, 0, sizeof gmb_cam); for (sq = 0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++) for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++) { c = FC(row, col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row, col); BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse(gmb_xyz, inverse, NSQ); for (pass = 0; pass < 2; pass++) { for (raw_color = i = 0; i < colors; i++) for (j = 0; j < 3; j++) for (cam_xyz[i][j] = k = 0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff(rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq = 0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf(" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5)); puts(" } },"); } #undef NSQ } #endif void CLASS hat_transform(float *temp, float *base, int st, int size, int sc) { int i; for (i = 0; i < sc; i++) temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)]; for (; i + sc < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)]; for (; i < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size) #endif { temp = (float *)malloc((iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #endif // green equilibration void CLASS green_matching() { int i, j; double m1, m2, c1, c2; int o1_1, o1_2, o1_3, o1_4; int o2_1, o2_2, o2_3, o2_4; ushort(*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if (half_size || shrink) return; if (FC(oj, oi) != 3) oj++; if (FC(oj, oi) != 3) oi++; if (FC(oj, oi) != 3) oj--; img = (ushort(*)[4])calloc(height * width, sizeof *image); merror(img, "green_matching()"); memcpy(img, image, height * width * sizeof *image); for (j = oj; j < height - margin; j += 2) for (i = oi; i < width - margin; i += 2) { o1_1 = img[(j - 1) * width + i - 1][1]; o1_2 = img[(j - 1) * width + i + 1][1]; o1_3 = img[(j + 1) * width + i - 1][1]; o1_4 = img[(j + 1) * width + i + 1][1]; o2_1 = img[(j - 2) * width + i][3]; o2_2 = img[(j + 2) * width + i][3]; o2_3 = img[j * width + i - 2][3]; o2_4 = img[j * width + i + 2][3]; m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0; m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0; c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) + abs(o1_2 - o1_4)) / 6.0; c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) + abs(o2_2 - o2_4)) / 6.0; if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr)) { f = image[j * width + i][3] * m1 / m2; image[j * width + i][3] = f > 0xffff ? 0xffff : f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img = 0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2); #endif if (user_mul[0]) memcpy(pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset(dsum, 0, sizeof dsum); bottom = MIN(greybox[1] + greybox[3], height); right = MIN(greybox[0] + greybox[2], width); for (row = greybox[1]; row < bottom; row += 8) for (col = greybox[0]; col < right; col += 8) { memset(sum, 0, sizeof sum); for (y = row; y < row + 8 && y < bottom; y++) for (x = col; x < col + 8 && x < right; x++) FORC4 { if (filters) { c = fcol(y, x); val = BAYER2(y, x); } else val = image[y * width + x][c]; if (val > maximum - 25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c + 4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block:; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset(sum, 0, sizeof sum); for (row = 0; row < 8; row++) for (col = 0; col < 8; col++) { c = FC(row, col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c + 4]++; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy(pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f) { for (c = 0; c < 3; c++) pre_mul[c] /= cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf(stderr, " %f", pre_mul[c]); fputc('\n', stderr); } #endif if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1) { FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight * iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i = 0; i < size * 4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Correcting chromatic aberration...\n")); #endif for (c = 0; c < 4; c += 2) { if (aber[c] == 1) continue; img = (ushort *)malloc(size * sizeof *img); merror(img, "scale_colors()"); for (i = 0; i < size; i++) img[i] = image[i][c]; for (row = 0; row < iheight; row++) { ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5; if (ur > iheight - 2) continue; fr -= ur; for (col = 0; col < iwidth; col++) { uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5; if (uc > iwidth - 2) continue; fc -= uc; pix = img + ur * iwidth + uc; image[row * iwidth + col][c] = (pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2); #endif } void CLASS pre_interpolate() { ushort(*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row = 0; row < 3; row++) for (col = 1; col < 4; col++) if (!(image[row * width + col][0] | image[row * width + col][2])) goto break2; break2: for (; row < height; row += 3) for (col = (col - 1) % 3 + 1; col < width - 1; col += 3) { img = image + row * width + col; for (c = 0; c < 3; c += 2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort(*)[4])calloc(height, width * sizeof *img); merror(img, "pre_interpolate()"); for (row = 0; row < height; row++) for (col = 0; col < width; col++) { c = fcol(row, col); img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c]; } free(image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1, 0) >> 1; row < height; row += 2) for (col = FC(row, 1) & 1; col < width; col += 2) image[row * width + col][1] = image[row * width + col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2); #endif } void CLASS border_interpolate(int border) { unsigned row, col, y, x, f, c, sum[8]; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { if (col == border && row >= border && row < height - border) col = width - border; memset(sum, 0, sizeof sum); for (y = row - 1; y != row + 2; y++) for (x = col - 1; x != col + 2; x++) if (y < height && x < width) { f = fcol(y, x); sum[f] += image[y * width + x][f]; sum[f + 4]++; } f = fcol(row, col); FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4]; } } void CLASS lin_interpolate_loop(int code[16][16][32], int size) { int row; for (row = 1; row < height - 1; row++) { int col, *ip; ushort *pix; for (col = 1; col < width - 1; col++) { int i; int sum[4]; pix = image[row * width + col]; ip = code[row % size][col % size]; memset(sum, 0, sizeof sum); for (i = *ip++; i--; ip += 3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i = colors; --i; ip += 2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size = 16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row = 0; row < size; row++) for (col = 0; col < size; col++) { ip = code[row][col] + 1; f = fcol(row, col); memset(sum, 0, sizeof sum); for (y = -1; y <= 1; y++) for (x = -1; x <= 1; x++) { shift = (y == 0) + (x == 0); color = fcol(row + y, col + x); if (color == f) continue; *ip++ = (width * y + x) * 4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c] > 0 ? 256 / sum[c] : 0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #endif lin_interpolate_loop(code, size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02, -2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02, -2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06, -2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128, -1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120, -1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11, -1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40, -1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10, -1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10, -1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128, +0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40, +0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08, +0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30, +0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40, +0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128, +1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10}, chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1}; ushort(*brow[5])[4], *pix; int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *)calloc(prow * pcol, 1280); merror(ip, "vng_interpolate()"); for (row = 0; row < prow; row++) /* Precalculate for VNG */ for (col = 0; col < pcol; col++) { code[row][col] = ip; for (cp = terms, t = 0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row + y1, col + x1); if (fcol(row + y2, col + x2) != color) continue; diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1; if (abs(y1 - y2) == diag && abs(x1 - x2) == diag) continue; *ip++ = (y1 * width + x1) * 4 + color; *ip++ = (y2 * width + x2) * 4 + color; *ip++ = weight; for (g = 0; g < 8; g++) if (grads & 1 << g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp = chood, g = 0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y * width + x) * 4; color = fcol(row, col); if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color) *ip++ = (y * width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow); merror(brow[4], "vng_interpolate()"); for (row = 0; row < 3; row++) brow[row] = brow[4] + row * width; for (row = 2; row < height - 2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if (!((row - 2) % 256)) RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1); #endif for (col = 2; col < width - 2; col++) { pix = image[row * width + col]; ip = code[row % prow][col % pcol]; memset(gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g = 1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy(brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset(sum, 0, sizeof sum); color = fcol(row, col); for (num = g = 0; g < 8; g++, ip += 2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); for (g = 0; g < 4; g++) brow[(g - 1) & 3] = brow[g]; } memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image); free(brow[4]); free(code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = {1, width, -1, -width, 1}; int row, col, diff[2], guess[2], c, d, i; ushort(*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 3; row < height - 3; row++) for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c]; diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 + (ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0] + guess[1]) >> 2); } } void CLASS cielab(ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if (cbrt[0] < -1.0f) #endif for (i = 0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f; } for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (xyz_cam[i][j] = k = 0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int)xyz[0])]; xyz[1] = cbrt[CLIP((int)xyz[1])]; xyz[2] = cbrt[CLIP((int)xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate(int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1}, patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0}, {0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}}, dir[4] = {1, TS, TS + 1, TS - 1}; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][3], (*lix)[3]; float(*drv)[TS][TS], diff[6], tr; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif cielab(0, 0); ndir = 4 << (passes > 1); buffer = (char *)malloc(TS * TS * (ndir * 11 + 6)); merror(buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6)); drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6)); homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6)); /* Map a green hexagon around each non-green pixel and vice versa: */ for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) for (ng = d = 0; d < 10; d += 2) { g = fcol(row, col) == 1; if (fcol(row + orth[d], col + orth[d + 2]) == 1) ng = 0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g + 1) FORC(8) { v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1]; h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1]; allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width; allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS; } } /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row = 2; row < height - 2; row++) for (min = ~(max = 0), col = 2; col < width - 2; col++) { if (fcol(row, col) == 1 && (min = ~(max = 0))) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row - sgrow) % 3) { case 1: if (row < height - 3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) row--; } } for (top = 3; top < height - 19; top += TS - 16) for (left = 3; left < width - 19; left += TS - 16) { mrow = MIN(top + TS, height - 3); mcol = MIN(left + TS, width - 3); for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) memcpy(rgb[0][row - top][col - left], image[row * width + col], 6); FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]); color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]); FORC(2) color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] + 33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]); FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]); } for (pass = 0; pass < passes; pass++) { if (pass == 1) memcpy(rgb += 4, buffer, 4 * sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row = top + 2; row < mrow - 2; row++) for (col = left + 2; col < mcol - 2; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][1]; for (d = 3; d < 6; d++) { rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left]; val = rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f]; rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3) for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3) { rix = &rgb[0][row - top][col - left]; h = fcol(row, col + 1); memset(diff, 0, sizeof diff); for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2) { for (c = 0; c < 2; c++, h ^= 2) { g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1]; color[h][d] = g + rix[i << c][h] + rix[-i << c][h]; if (d > 1) diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d - 1] < diff[d]) FORC(2) color[c * 2][d] = color[c * 2][d - 1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2); rix += TS * TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row = top + 3; row < mrow - 3; row++) for (col = left + 3; col < mcol - 3; col++) { if ((f = 2 - fcol(row, col)) == 1) continue; rix = &rgb[0][row - top][col - left]; c = (row - sgrow) % 3 ? TS : 1; h = 3 * (c ^ TS ^ 1); for (d = 0; d < 4; d++, rix += TS * TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) < 2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1]))) ? c : h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row = top + 2; row < mrow - 2; row++) if ((row - sgrow) % 3) for (col = left + 2; col < mcol - 2; col++) if ((col - sgcol) % 3) { rix = &rgb[0][row - top][col - left]; hex = allhex[row % 3][col % 3][1]; for (d = 0; d < ndir; d += 2, rix += TS * TS) if (hex[d] + hex[d + 1]) { g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3); } else { g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2); } } } rgb = (ushort(*)[TS][TS][3])buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d = 0; d < ndir; d++) { for (row = 2; row < mrow - 2; row++) for (col = 2; col < mcol - 2; col++) cielab(rgb[d][row][col], lab[row][col]); for (f = dir[d & 3], row = 3; row < mrow - 3; row++) for (col = 3; col < mcol - 3; col++) { lix = &lab[row][col]; g = 2 * lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) + SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir * TS * TS); for (row = 4; row < mrow - 4; row++) for (col = 4; col < mcol - 4; col++) { for (tr = FLT_MAX, d = 0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d = 0; d < ndir; d++) for (v = -1; v <= 1; v++) for (h = -1; h <= 1; h++) if (drv[d][row + v][col + h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height - top < TS + 4) mrow = height - top + 2; if (width - left < TS + 4) mcol = width - left + 2; for (row = MIN(top, 8); row < mrow - 8; row++) for (col = MIN(left, 8); col < mcol - 8; col++) { for (d = 0; d < ndir; d++) for (hm[d] = 0, v = -2; v <= 2; v++) for (h = -2; h <= 2; h++) hm[d] += homo[d][row + v][col + h]; for (d = 0; d < ndir - 4; d++) if (hm[d] < hm[d + 4]) hm[d] = 0; else if (hm[d] > hm[d + 4]) hm[d + 4] = 0; for (max = hm[0], d = 1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset(avg, 0, sizeof avg); for (d = 0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort(*pix)[4]; const int rowlimit = MIN(top + TS, height - 2); const int collimit = MIN(left + TS, width - 2); for (row = top; row < rowlimit; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < collimit; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort(*pix)[4]; ushort(*rix)[3]; short(*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4 * width; const unsigned rowlimit = MIN(top + TS - 1, height - 3); const unsigned collimit = MIN(left + TS - 1, width - 3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top + 1; row < rowlimit; row++) { pix = image + row * width + left; rix = &inout_rgb[row - top][0]; lix = &out_lab[row - top][0]; for (col = left + 1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row + 1, col); t1 = 2 - c; val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1); } else { t1 = -4 + c; /* -4+c: pixel of color c to the left */ t2 = 4 + c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short(*lix)[3]; short(*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = {-1, 1, -TS, TS}; const int rowlimit = MIN(top + TS - 2, height - 4); const int collimit = MIN(left + TS - 2, width - 4); int homogeneity; char(*homogeneity_map_p)[2]; memset(out_homogeneity_map, 0, 2 * TS * TS); for (row = top + 2; row < rowlimit; row++) { tr = row - top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction = 0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col = left + 2; col < collimit; col++) { tc = col - left; homogeneity_map_p++; for (direction = 0; direction < 2; direction++) { lix = ++lixs[direction]; for (i = 0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (direction = 0; direction < 2; direction++) { homogeneity = 0; for (i = 0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top + TS - 3, height - 5); const int collimit = MIN(left + TS - 3, width - 5); ushort(*pix)[4]; ushort(*rix[2])[3]; for (row = top + 3; row < rowlimit; row++) { tr = row - top; pix = &image[row * width + left + 2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col = left + 3; col < collimit; col++) { tc = col - left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction = 0; direction < 2; direction++) { hm[direction] = 0; for (i = tr - 1; i <= tr + 1; i++) { for (j = tc - 1; j <= tc + 1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4], r; char *buffer; ushort(*rgb)[TS][TS][3]; short(*lab)[TS][TS][3]; char(*homo)[TS][2]; int terminate_flag = 0; cielab(0, 0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag) #endif #endif { buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */ merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][2])(buffer + 24 * TS * TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top = 2; top < height - 5; top += TS - 6) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if (0 == omp_get_thread_num()) #endif if (callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7); if (rr) terminate_flag = 1; } #endif for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free(buffer); } #ifdef LIBRAW_LIBRARY_BUILD if (terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = {-1, 1, -TS, TS}; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][TS][3], (*lix)[3]; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("AHD interpolation...\n")); #endif cielab(0, 0); border_interpolate(5); buffer = (char *)malloc(26 * TS * TS); merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][TS])(buffer + 24 * TS * TS); for (top = 2; top < height - 5; top += TS - 6) for (left = 2; left < width - 5; left += TS - 6) { /* Interpolate green horizontally and vertically: */ for (row = top; row < top + TS && row < height - 2; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < left + TS && col < width - 2; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d = 0; d < 2; d++) for (row = top + 1; row < top + TS - 1 && row < height - 3; row++) for (col = left + 1; col < left + TS - 1 && col < width - 3; col++) { pix = image + row * width + col; rix = &rgb[d][row - top][col - left]; lix = &lab[d][row - top][col - left]; if ((c = 2 - FC(row, col)) == 1) { c = FC(row + 1, col); val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1); rix[0][2 - c] = CLIP(val); val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1); } else val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset(homo, 0, 2 * TS * TS); for (row = top + 2; row < top + TS - 2 && row < height - 4; row++) { tr = row - top; for (col = left + 2; col < left + TS - 2 && col < width - 4; col++) { tc = col - left; for (d = 0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i = 0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (d = 0; d < 2; d++) for (i = 0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row = top + 3; row < top + TS - 3 && row < height - 5; row++) { tr = row - top; for (col = left + 3; col < left + TS - 3 && col < width - 5; col++) { tc = col - left; for (d = 0; d < 2; d++) for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++) for (j = tc - 1; j <= tc + 1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free(buffer); } #endif #undef TS void CLASS median_filter() { ushort(*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ {1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0, 3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2}; for (pass = 1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Median filter pass %d...\n"), pass); #endif for (c = 0; c < 3; c += 2) { for (pix = image; pix < image + width * height; pix++) pix[0][3] = pix[0][c]; for (pix = image + width; pix < image + width * (height - 1); pix++) { if ((pix - image + 1) % width < 2) continue; for (k = 0, i = -width; i <= width; i += width) for (j = i - 1; j <= i + 1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i = 0; i < sizeof opt; i += 2) if (med[opt[i]] > med[opt[i + 1]]) SWAP(med[opt[i]], med[opt[i + 1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip = INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned)(colors - 3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2); #endif FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { FORCC if (image[row * width + col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row * width + col][c]; cam[1][c] = MIN(cam[0][c], clip); } for (i = 0; i < 2; i++) { FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j]; for (sum[i] = 0, c = 1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1] / sum[0]); for (c = 1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j]; FORCC image[row * width + col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rebuilding highlights...\n")); #endif grow = pow(2.0, 4 - highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc = 0, c = 1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *)calloc(high, wide * sizeof *map); merror(map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1); #endif memset(map, 0, high * wide * sizeof *map); for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE * SCALE) map[mrow * wide + mcol] = sum / wgt; } for (spread = 32 / grow; spread--;) { for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { if (map[mrow * wide + mcol]) continue; sum = count = 0; for (d = 0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y * wide + x] > 0) { sum += (1 + (d & 1)) * map[y * wide + x]; count += 1 + (d & 1); } } if (count > 3) map[mrow * wide + mcol] = -(sum + grow) / (count + grow); } for (change = i = 0; i < high * wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i = 0; i < high * wide; i++) if (map[i] == 0) map[i] = 1; for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow * wide + mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free(map); } #undef SCALE void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4) fseek(ifp, get4() + base, SEEK_SET); } void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4() + base; if (tag == tlen) thumb_length = get4(); fseek(ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); } static float powf64(float a, float b) { return powf_lim(a, b, 64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in / 64.0); } static float _CanonConvertEV(short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float)Frac; return ((float)Sign * ((float)EV + Frac_f)) / 32.0f; } unsigned CLASS setCanonBodyFeatures(unsigned id) { if (id == 0x03740000) // EOS M3 id = 0x80000374; else if (id == 0x03840000) // EOS M10 id = 0x80000384; else if (id == 0x03940000) // EOS M5 id = 0x80000394; else if (id == 0x04070000) // EOS M6 id = 0x80000407; else if (id == 0x03980000) // EOS M100 id = 0x80000398; imgdata.lens.makernotes.CamID = id; if ((id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) || // M5 (id == 0x80000407) || // M6 (id == 0x80000398) // M100 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ((id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return id; } void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short CameraInfo[0] = 0; CameraInfo[1] = 0; if (type == 4) { if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) || (maxlen == 171) || (maxlen == 264) || (maxlen > 400)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-3)<<2)); else if (maxlen == 72) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-1)<<2)); else if ((maxlen == 85) || (maxlen == 93)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-2)<<2)); else if ((maxlen == 96) || (maxlen == 104)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-4)<<2)); } switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); imgdata.other.CameraTemperature = 0.0f; break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if (iCanonFocalType >= maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if (iCanonCurFocal >= maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if (iCanonLensID >= maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if (iCanonMinFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if (iCanonMaxFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if (iCanonLens + 64 >= maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings() { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets(int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets(short WBCTversion) { if (WBCTversion == 0) for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x80000407) || // M6 (unique_id == 0x80000398) || // M100 (unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000))) // G1 X Mark III for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData(uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 | (unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 | (unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 | (unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures(unsigned long long id) { imgdata.lens.makernotes.CamID = id; if (id == 0x5330303638ULL) { strcpy (model, "E-M10MarkIII"); } if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 24, SEEK_CUR); tempAp = get2(); if (tempAp != 0) imgdata.other.CameraTemperature = (float)(tempAp-128); tempAp = get2(); if (tempAp != -1) imgdata.other.FlashGN = ((float)tempAp) / 32; get2(); // fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8 - 32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); int c; fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(), get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek(ifp, save1 + (0x1e << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x41 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x46 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x23 << 1), SEEK_SET); Canon_WBpresets(2, 2); fseek(ifp, save1 + (0x4b << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek(ifp, save1 + (0x18 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x90 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x95 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x9a << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x27 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa4 << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x71 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x76 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x7b << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x4e << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x53 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa8 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek(ifp, save1 + (0x2b9 << 1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek(ifp, save1 + (0x2d0 << 1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek(ifp, save1 + (0x2d4 << 1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6 { if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000) || // G1 X Mark III (unique_id == 0x80000394) || // EOS M5 (unique_id == 0x80000398) || // EOS M100 (unique_id == 0x80000407)) // EOS M6 { fseek(ifp, save1 + (0x4f << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8, 24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets(2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { fseek(ifp, save1 + (0x4c << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xba << 1), SEEK_SET); Canon_WBCTpresets(2); // BCADT fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short } int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x67 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xbc << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } fseek(ifp, save1 + (0x1e4 << 1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xd5 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek(ifp, save1 + (0x1fd << 1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek(ifp, save1 + (0x2dd << 1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D case 1560: case 1592: case 1353: case 1602: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x107 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek(ifp, save1 + (0x231 << 1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek(ifp, save1 + (0x30f << 1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek(ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: case 0x1322c: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO(ushort c) { int code[] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code) / sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar *)malloc(MAX(len, 128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10 * (table_buf[iLensData + 9] >> 2) * powf64(4, (table_buf[iLensData + 9] & 0x03) - 2); if (table_buf[iLensData + 10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f); if (table_buf[iLensData + 10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07); if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures(unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333, "Mamiya"}, {329, "Universal"}, {330, "Hasselblad H1/H2"}, {332, "Contax"}, {336, "AFi"}, {327, "Mamiya"}, {324, "Universal"}, {325, "Hasselblad H1/H2"}, {326, "Contax"}, {335, "AFi"}, {340, "Mamiya"}, {337, "Universal"}, {338, "Hasselblad H1/H2"}, {339, "Contax"}, {323, "Mamiya"}, {320, "Universal"}, {322, "Hasselblad H1/H2"}, {321, "Contax"}, {334, "AFi"}, {369, "Universal"}, {370, "Mamiya"}, {371, "Hasselblad H1/H2"}, {372, "Contax"}, {373, "Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes(unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 358) || // ILCE-9 (id == 362) || // ILCE-7RM3 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 358) || (id == 360) || (id == 362)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2(uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a) << 8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf))) void CLASS parseSonyLensFeatures(uchar a, uchar b) { ushort features; features = (((ushort)a) << 8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA"); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1); return; } #undef strnXcat void CLASS process_Sony_0x0116(uchar *buf, unsigned id) { if ((id == 257) || (id == 262) || (id == 269) || (id == 270)) imgdata.other.BatteryTemperature = (float) (buf[1]-32) / 1.8f; else if ((id != 263) && (id != 264) && (id != 265) && (id != 266)) imgdata.other.BatteryTemperature = (float) (buf[2]-32) / 1.8f; return; } void CLASS process_Sony_0x9402(uchar *buf) { if (buf[2] != 0xff) return; short bufx = SonySubstitution[buf[0]]; if ((bufx < 0x0f) || (bufx > 0x1a) || (bufx == 0x16) || (bufx == 0x18)) return; imgdata.other.AmbientTemperature = (float) ((short) SonySubstitution[buf[4]]); return; } void CLASS process_Sony_0x9403(uchar *buf) { short bufx = SonySubstitution[buf[4]]; if ((bufx == 0x00) || (bufx == 0x94)) return; imgdata.other.SensorTemperature = (float) ((short) SonySubstitution[buf[5]]); return; } void CLASS process_Sony_0x9406(uchar *buf) { short bufx = SonySubstitution[buf[0]]; if ((bufx != 0x00) && (bufx == 0x01) && (bufx == 0x03)) return; bufx = SonySubstitution[buf[2]]; if ((bufx != 0x02) && (bufx == 0x03)) return; imgdata.other.BatteryTemperature = (float) (SonySubstitution[buf[5]]-32) / 1.8f; return; } void CLASS process_Sony_0x940c(uchar *buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050(uchar *buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x9050, ushort &table_buf_0x9050_present, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_present, uchar *&table_buf_0x0116, ushort &table_buf_0x0116_present, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_present, uchar *&table_buf_0x9403, ushort &table_buf_0x9403_present, uchar *&table_buf_0x9406, ushort &table_buf_0x9406_present) { ushort lid; uchar *table_buf; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x0116_present) { process_Sony_0x0116(table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free(table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x9402_present) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } if (table_buf_0x9403_present) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } if (table_buf_0x9406_present) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if ((!dng_writer) || (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x0116 && len < 256000) { table_buf_0x0116 = (uchar *)malloc(len); table_buf_0x0116_present = 1; fread(table_buf_0x0116, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x0116 (table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x9402 && len < 256000) { table_buf_0x9402 = (uchar *)malloc(len); table_buf_0x9402_present = 1; fread(table_buf_0x9402, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } } else if (tag == 0x9403 && len < 256000) { table_buf_0x9403 = (uchar *)malloc(len); table_buf_0x9403_present = 1; fread(table_buf_0x9403, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } } else if (tag == 0x9406 && len < 256000) { table_buf_0x9406 = (uchar *)malloc(len); table_buf_0x9406_present = 1; fread(table_buf_0x9406, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if (len > 8 && pos + len > 2 * fsize) continue; tag |= uptag << 16; if (len > 100 * 1024 * 1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes(tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) && strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) || (((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 | (unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */} #endif void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make, "Nokia", 5)) return; fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */ !strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4)) return; if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */ !strncmp(buf, "MLY", 3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, "SAMSUNG", 7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) continue; if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2) ystr[j / 2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) || !strncasecmp(model, "Hasselblad A6D", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) / (float)c; } else if (tag == 0x003b) // all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) // Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, "NIKON") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * powf64(2.0f, float(cc) / 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i / 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i / 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short)i / -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, "Canon", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 /* Canon rotation data is handled by EXIF.Orientation */ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = "065"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, "Olympus", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, "NRW ", 4)) { fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, "PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) // Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) // Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, "NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, "Samsung", 7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } /* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); } */ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp(int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i = 19; i--;) str[i] = fgetc(ifp); else fread(str, 19, 1, ifp); memset(&t, 0, sizeof t); if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif(int base) { unsigned kodak, entries, tag, type, len, save, c; double expo, ape; kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34865: if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4)) iso_speed = getreal(type); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = powf64(2.0, ape / 2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; pos = strtok(ccms, ","); for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok(NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote(base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29 + tag / 2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag / 3 * 6 + c] = get4(); break; case 6: FORC(2) gpsdata[18 + c] = get4(); break; case 18: case 29: fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp); } fseek(ifp, save, SEEK_SET); } } void CLASS romm_coeff(float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ {{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}}; int i, j, k; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) for (cmatrix[i][j] = k = 0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos(int offset) { char data[40]; int skip, from, i, c, neut[4], planes = 0, frot = 0; static const char *mod[] = {"", "DCB2", "Volare", "Cantare", "CMost", "Valeo 6", "Valeo 11", "Valeo 22", "Valeo 11p", "Valeo 17", "", "Aptus 17", "Aptus 22", "Aptus 75", "Aptus 65", "Aptus 54S", "Aptus 65S", "Aptus 75S", "AFi 5", "AFi 6", "AFi 7", "AFi-II 7", "Aptus-II 7", "", "Aptus-II 6", "", "", "Aptus-II 10", "Aptus-II 5", "", "", "", "", "Aptus-II 10R", "Aptus-II 8", "", "Aptus-II 12", "", "AFi-II 12"}; float romm_cam[3][3]; fseek(ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread(data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data, "CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data, "back_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial)); strcpy(imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data, "CaptProf_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data, "JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data, "icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data, "ShootObj_back_type")) { fscanf(ifp, "%d", &i); if ((unsigned)i < sizeof mod / sizeof(*mod)) strcpy(model, mod[i]); } if (!strcmp(data, "icc_camera_to_tone_matrix")) { for (i = 0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_color_matrix")) { for (i = 0; i < 9; i++) fscanf(ifp, "%f", (float *)romm_cam + i); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_number_of_planes")) fscanf(ifp, "%d", &planes); if (!strcmp(data, "CaptProf_raw_data_rotation")) fscanf(ifp, "%d", &flip); if (!strcmp(data, "CaptProf_mosaic_pattern")) FORC4 { fscanf(ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data, "ImgProf_rotation_angle")) { fscanf(ifp, "%d", &i); flip = i - flip; } if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf(ifp, "%d", neut + c); FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1]; } if (!strcmp(data, "Rows_data")) load_flags = get4(); parse_mos(from); fseek(ifp, skip + from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3]; } void CLASS linear_table(unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts(curve, len); for (i = len; i < 0x10000; i++) curve[i] = curve[i - 1]; maximum = curve[len < 0x1000 ? 0xfff : len - 1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags(int wb, unsigned type) { float mul[3] = {1, 1, 1}, num, mul2; int c; FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; // int a_blck = 0; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > 2 * fsize) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2()); wbi = -2; } if ((tag == 1030) && (len == 1)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 1043) && (len == 1)) imgdata.other.SensorTemperature = getreal(type); if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C"))) black = get2(); if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C"))) { if (black) // already set by tag 0x03ef black = (black + get2()) / 2; else black = get2(); } INT64 _pos2 = ftell(ifp); if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x084c) Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type); if (tag == 0x084d) Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } fseek(ifp, _pos2, SEEK_SET); if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table(len); if (tag == 0x903) iso_speed = getreal(type); // if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2, wbtemp = 6500; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num = i = 0; i < 4; i++) num += getreal(type) * pow(wbtemp / 100.0, i); cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c])); } if (tag == 2317) linear_table(len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > fsize * 2) continue; // skip tag pointing out of 2xfile if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = get2(); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread(desc, 512, 1, ifp); break; case 271: /* Make */ fgets(make, 64, ifp); break; case 272: /* Model */ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: // FujiFilm "As Shot" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets(software, 64, ifp); if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) || !strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: /* SubIFDs */ if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP(cam_mul[i], cam_mul[i + 1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets(model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, "\003\004\005", 3); /* CMY */ if (cfa == 072) memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread(software, 1, 7, ifp); if (strncmp(software, "MATRIX", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1, num); } break; case 34310: /* Leaf metadata */ parse_mos(ftell(ifp)); case 34303: strcpy(make, "Leaf"); break; case 34665: /* EXIF tag */ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy(make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, "Ixpress %d-Mp", height * width / 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n')) if (!strncmp(++cp, "Neutral ", 8)) sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5; tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_black = #endif black = getreal(type); } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) cblack[6 + c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); black += num / len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) // Linear DNG case for (i = 1; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: /* DefaultCropOrigin */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); } break; case 50720: /* DefaultCropSize */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORCC for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: /* PreviewColorSpace */ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: /* OpcodeList2 */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length / 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff(int base) { int doff; fseek(ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek(ifp, doff + base, SEEK_SET); if (parse_tiff_ifd(base)) break; } return 1; } void CLASS apply_tiff() { int max_samp = 0, ties = 0, raw = -1, thm = -1, i; unsigned long long ns, os; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i = tiff_nifds; i--;) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i = 0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width * raw_height; ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i = tiff_nifds; i--;) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width * raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3) load_flags = 24; if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); memset(cblack, 0, sizeof cblack); filters = 0; } else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; load_flags = 80; } else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last if (tiff_ifd[raw].strip_byte_counts[i] * 2 != tiff_ifd[raw].rows_per_strip * raw_width * 3) { fit = 0; break; } if (fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") && !strstr(model2, "DEBUG RAW"))) && strncmp(software, "Nikon Scan", 10)) is_raw = 0; for (i = 0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) > thumb_width * thumb_height / (SQR(thumb_misc) + 1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make, "Imacon", 6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta(int base) { int save, tag, len, offset, high = 0, wide = 0, i, c; short sorder = order; fseek(ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save = ftell(ifp)) < offset) { for (tag = i = 0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek(ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model, "DiMAGE A200") ? 0 : 3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff(ftell(ifp)); data_offset = offset; } fseek(ifp, save + len + 8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save = ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if (ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length() - 3, 3, L"JPG"); if (!ifp->subfile_open(rawfile.c_str())) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif if (!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif ext = strrchr(ifname, '.'); file = strrchr(ifname, '/'); if (!file) file = strrchr(ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname - 1; #else if (!file) file = (char *)ifname - 1; #endif file++; if (!ext || strlen(ext) != 4 || ext - file != 8) return; jname = (char *)malloc(strlen(ifname) + 1); merror(jname, "parse_external_jpeg()"); strcpy(jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp(ext, ".jpg")) { strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg"); if (isdigit(*file)) { memcpy(jfile, file + 4, 4); memcpy(jfile + 4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp(jname, ifname)) { if ((ifp = fopen(jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Reading metadata from %s ...\n"), jname); #endif parse_tiff(12); thumb_offset = 0; is_raw = 1; fclose(ifp); } } #else if (strcmp(jname, ifname)) { if (!ifp->subfile_open(jname)) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("Failed to read metadata from %s\n"), jname); #endif } free(jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = {0x410, 0x45f3}; int i, bpp, row, col, vbits = 0; unsigned long bitbuf = 0; if ((get2(), get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i = row = 0; row < 8; row++) for (col = 0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff(int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi = -1; ushort key[] = {0x410, 0x45f3}; fseek(ifp, offset + length - 4, SEEK_SET); tboff = get4() + offset; fseek(ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek(ifp, offset + get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff(ftell(ifp), len, depth + 1); #endif if (type == 0x0810) fread(artist, 64, 1, ifp); if (type == 0x080a) { fread(make, 64, 1, ifp); fseek(ifp, strbuflen(make) - 63, SEEK_CUR); fread(model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(), get4()))); aperture = powf64(2.0f, int_to_float(get4()) / 2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(), get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(), (short)get2()) / 64.0); #endif shutter = powf64(2.0, -((short)get2()) / 32.0); wbi = (get2(), get2()); if (wbi > 17) wbi = 0; fseek(ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2() / 10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek(ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek(ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, o, SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp, o, SEEK_SET); } if (type == 0x580b) { if (strcmp(model, "Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek(ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0, wbi, 17)] - '0'; key[0] = key[1] = 0; } fseek(ifp, 78 + c * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0, wbi, 9)] - '0'; fseek(ifp, 2 + wbi * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(), get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if (imgdata.lens.makernotes.CanonFocalUnits > 1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD unique_id = setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime(gmtime(&timestamp)); #endif fseek(ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek(ifp, 0, SEEK_SET); memset(&t, 0, sizeof t); do { fgets(line, 128, ifp); if ((val = strchr(line, '='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line, "DAT")) sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line, "TIM")) sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line, "HDR")) thumb_offset = atoi(val); if (!strcmp(line, "X ")) raw_width = atoi(val); if (!strcmp(line, "Y ")) raw_height = atoi(val); if (!strcmp(line, "TX ")) thumb_width = atoi(val); if (!strcmp(line, "TY ")) thumb_height = atoi(val); } while (strncmp(line, "EOHD", 4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy(make, "Rollei"); strcpy(model, "d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek(ifp, 4, SEEK_SET); entries = get4(); fseek(ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread(str, 8, 1, ifp); if (!strcmp(str, "META")) meta_offset = off; if (!strcmp(str, "THUMB")) thumb_offset = off; if (!strcmp(str, "RAW0")) data_offset = off; } fseek(ifp, meta_offset + 20, SEEK_SET); fread(make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(), get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one(int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset(&ph1, 0, sizeof ph1); fseek(ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek(ifp, get4() + base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, base + data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0211: imgdata.other.SensorTemperature2 = int_to_float(data); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data) / 2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type) / 2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3] - '0'; break; case 0x106: for (i = 0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i] = #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff(romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data + base; break; case 0x110: meta_offset = data + base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.SensorTemperature = ph1.tag_210; #endif break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data + base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data + base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data + base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i = 0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread(model, 1, 63, ifp); if ((cp = strstr(model, " camera"))) *cp = 0; } fseek(ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek(ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy(make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy(model, "LightPhase"); break; case 2682: strcpy(model, "H 10"); break; case 4128: strcpy(model, "H 20"); break; case 5488: strcpy(model, "H 25"); break; } } void CLASS parse_fuji(int offset) { unsigned entries, tag, len, save, c; fseek(ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); // IB start #ifdef LIBRAW_LIBRARY_BUILD } else if (tag == 0x9650) { short a = (short)get2(); float b = fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2f00) { int nWBs = get4(); nWBs = MIN(nWBs, 6); for (int wb_ind = 0; wb_ind < nWBs; wb_ind++) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2(); fseek(ifp, 8, SEEK_CUR); } } else if (tag == 0x2000) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2(); } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } else if (tag == 0x2410) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2(); #endif // IB end } else if (tag == 0xc000) /* 0xc000 tag versions, second ushort; valid if the first ushort is 0 X100F 0x0259 X100T 0x0153 X-E2 0x014f 0x024f depends on firmware X-A1 0x014e XQ2 0x0150 XQ1 0x0150 X100S 0x0149 0x0249 depends on firmware X30 0x0152 X20 0x0146 X-T10 0x0154 X-T2 0x0258 X-M1 0x014d X-E2s 0x0355 X-A2 0x014e X-T20 0x025b GFX 50S 0x025a X-T1 0x0151 0x0251 0x0351 depends on firmware X70 0x0155 X-Pro2 0x0255 */ { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { int wb[4]; int nWB, tWB, pWB; int iCCT = 0; int cnt; fseek(ifp, save + 0x200, SEEK_SET); for (int wb_ind = 0; wb_ind < 42; wb_ind++) { nWB = get4(); tWB = get4(); wb[0] = get4() << 1; wb[1] = get4(); wb[3] = get4(); wb[2] = get4() << 1; if (tWB && (iCCT < 255)) { imgdata.color.WBCT_Coeffs[iCCT][0] = tWB; for (cnt = 0; cnt < 4; cnt++) imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt]; iCCT++; } if (nWB != 70) { for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2) { if (Fuji_wb_list2[pWB] == nWB) { for (cnt = 0; cnt < 4; cnt++) imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt]; break; } } } } } else { libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len >> 1); } #endif order = c; } fseek(ifp, save + len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save + hlen) >= 0 && (save + hlen) <= ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm t; order = 0x4949; fread(tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4)) { int maxloop = 1000; get4(); while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag, "nctg", 4)) { while (ftell(ifp) + 7 < end) { i = get2(); size = get2(); if ((i + 1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek(ifp, size, SEEK_CUR); } } else if (!memcmp(tag, "IDIT", 4) && size < 64) { fread(date, 64, 1, ifp); date[size] = 0; memset(&t, 0, sizeof t); if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i = 0; i < 12 && strcasecmp(mon[i], month); i++) ; t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek(ifp, size, SEEK_CUR); } void CLASS parse_qt(int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp) + 7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread(tag, 4, 1, ifp); if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4)) parse_qt(save + size); if (!memcmp(tag, "CNDA", 4)) parse_jpeg(ftell(ifp)); fseek(ifp, save + size, SEEK_SET); } } void CLASS parse_smal(int offset, int fsize) { int ver; fseek(ifp, offset + 2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek(ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy(make, "SMaL"); sprintf(model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek(ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek(ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek(ifp, off_head + 4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(), get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek(ifp, off_setup + 792, SEEK_SET); strcpy(make, "CINE"); sprintf(model, "%d", get4()); fseek(ifp, 12, SEEK_CUR); switch ((i = get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek(ifp, 72, SEEK_CUR); switch ((get4() + 3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek(ifp, 668, SEEK_CUR); shutter = get4() / 1000000000.0; fseek(ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek(ifp, shot_select * 8, SEEK_CUR); data_offset = (INT64)get4() + 8; data_offset += (INT64)get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek(ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek(ifp, 0, SEEK_END); fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek(ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek(ifp, len - 8, SEEK_CUR); } } else { rdvo = get4(); fseek(ifp, 12, SEEK_CUR); is_raw = get4(); fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff(const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD , int internal_only #endif ) { // clang-format off static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, /* updated */ { 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } }, { "Canon EOS D60", 0, 0xfa0, /* updated */ { 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } }, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D Mark II", 0, 0x38de, /* updated */ { 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } }, { "Canon EOS 6D", 0, 0x3c82, /* skipped update */ { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 77D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 800D", 0, 0, { 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 200D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60Da", 0, 0x2ff7, /* added */ { 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } }, { "Canon EOS M6", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M5", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M2", 0, 0, /* added */ { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M100", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, /* updated */ { 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */ { 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, {"Canon PowerShot 600", 0, 0, /* added */ { -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, /* updated */ { 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } }, { "Canon PowerShot G1 X Mark III", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, /* updated */ { -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } }, { "Canon PowerShot G2", 0, 0, /* updated */ { 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, /* updated */ { 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, /* updated */ { 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X Mark II", 0, 0, { 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, /* updated */ { -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } }, { "Canon PowerShot Pro90", 0, 0, /* updated */ { -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } }, { "Canon PowerShot S30", 0, 0, /* updated */ { 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } }, { "Canon PowerShot S40", 0, 0, /* updated */ { 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } }, { "Canon PowerShot S45", 0, 0, /* updated */ { 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } }, { "Canon PowerShot S50", 0, 0, /* updated */ { 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot D10", 127, 0, /* DJC */ { 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-F1", 0, 0, /* added */ { 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } }, { "Casio EX-FH100", 0, 0, /* added */ { 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, /* updated */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F810", 0, 0, /* added */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, /* updated */ { 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100F", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A10", 0, 0, { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-A3", 0, 0, { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-E3", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T20", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T10", 0, 0, /* updated */ { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm GFX 50S", 0, 0, { 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } }, { "GITUP GIT2P", 4160, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "GITUP GIT2", 3200, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Hasselblad HV", 0, 0, /* added */ { 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } }, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Lusso", 0, 0, /* added */ { 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad 500 mech.", 0, 0, /* added */ { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad CFV", 0, 0, { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad 39-Coated", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H-39MP",0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H2D-39", 0, 0, /* added */ { 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } }, { "Hasselblad H3D-50", 0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H3D", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, { 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } }, { "Hasselblad H5D-50c",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "Hasselblad H5D-50",0, 0, { 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } }, { "Hasselblad H6D-100c",0, 0, { 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } }, { "Hasselblad X1D",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Photo Control Camerz ZDS 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf C-Most", 0, 0, /* updated */ { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus-II 8", 0, 0, /* added */ { 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } }, { "Leaf AFi-II 7", 0, 0, /* added */ { 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } }, { "Leaf Aptus-II 5", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 65S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 75S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 50", 0, 0, { 3984,0,0,0,10000,0,0,0,7666 } }, { "Leaf Credo 60", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leica M10", 0, 0, /* added */ { 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } }, { "Leica M9", 0, 0, /* added */ { 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } }, { "Leica M8", 0, 0, /* added */ { 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } }, { "Leica M (Typ 240)", 0, 0, /* added */ { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica M (Typ 262)", 0, 0, { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Leica S2", 0, 0, /* added */ { 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } }, {"Leica S-E (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, {"Leica S (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica Q (Typ 116)", 0, 0, /* updated */ { 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } }, { "Leica T (Typ 701)", 0, 0, /* added */ { 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } }, { "Leica X2", 0, 0, /* added */ { 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } }, { "Leica X1", 0, 0, /* added */ { 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } }, { "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */ { 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } }, { "Mamiya M31", 0, 0, /* added */ { 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } }, { "Mamiya M22", 0, 0, /* added */ { 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } }, { "Mamiya M18", 0, 0, /* added */ { 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, /* updated */ { 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */ { 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } }, { "Minolta DiMAGE 7i", 0, 0xf7d, /* added */ { 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } }, { "Minolta DiMAGE 7", 0, 0xf7d, /* updated */ { 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } }, { "Minolta DiMAGE A1", 0, 0xf8b, /* updated */ { 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta Maxxum 5D", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta Maxxum 7D", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, /* updated */ { 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } }, { "Nikon D2X", 0, 0, /* updated */ { 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D5600", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, /* updated */ { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D850", 0, 0, { 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } }, { "Nikon D810A", 0, 0, { 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, /* updated */ { -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } }, { "Nikon E5400", 0, 0, /* updated */ { 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } }, { "Nikon E5700", 0, 0, /* updated */ { -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Kalon", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Deneb", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, /* updated */ { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, /* updated */ { 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, /* updated */ { 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, /* updated */ { 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, { 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } }, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP565UZ", 0, 0, /* added */ { 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, /* updated */ { 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus TG-5", 0, 0, { 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax GR", 0, 0, /* added */ { 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } }, { "Pentax K-01", 0, 0, /* added */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K10D", 0, 0, /* updated */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax K-m", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax KP", 0, 0, { 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, /* updated */ { 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } }, { "Pentax K-30", 0, 0, /* updated */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K-3 II", 0, 0, /* updated */ { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-500", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-50", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, { 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } }, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax KP", 0, 0, /* temp */ { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax Q7", 0, 0, /* added */ { 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } }, { "Pentax Q10", 0, 0, /* updated */ { 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } }, { "Pentax Q", 0, 0, /* added */ { 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } }, { "Pentax MX-1", 0, 0, /* updated */ { 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* updated */ { 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } }, { "Panasonic DMC-CM10", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */ { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Leica V-LUX 1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX3", 0, 0xf7f, /* added */ { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX2", 0, 0, /* added */ { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-LUX 2", 0, 0xf7f, /* added */ { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX 3", 0, 0, /* added */ { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */ { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ2500", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZH1", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-FX180", -15, 0xfff, /* added */ { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-G9", -15, 0, /* temp */ { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic AG-GH4", -15, 0, /* added */ { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DC-GH5", -15, 0, { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One H25", 0, 0, /* added */ { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ280", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ260", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ250",0, 0, // {3984,0,0,0,10000,0,0,0,7666}}, {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */ { "Phase One IQ180", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ160", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ150", 0, 0, /* added */ {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */ // { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ140", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P 45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P 30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P 21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ3 100MP", 0, 0, /* added */ // {2423,0,0,0,9901,0,0,0,7989}}, { 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */ { "Phase One IQ3 80MP", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ3 60MP", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ3 50MP", 0, 0, /* added */ // { 3984,0,0,0,10000,0,0,0,7666 } }, {10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */ { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Polaroid x530", 0, 0, { 13458,-2556,-510,-5444,15081,205,0,0,12120 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */ { 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } }, { "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */ { 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } }, { "Ricoh GR DIGITAL 3", 0, 0, /* added */ { 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } }, { "Ricoh GR DIGITAL 4", 0, 0, /* added */ { 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Ricoh GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh RICOH GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh GXR MOUNT A12", 0, 0, /* added */ { 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } }, { "Ricoh GXR A16", 0, 0, /* added */ { 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } }, { "Ricoh GXR A12", 0, 0, /* added */ { 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } }, { "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN120", 0, 0, /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung Galaxy S7 Edge", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy S7", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy NX", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX U", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* used for NX10/NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NXF1", 0, 0, /* added */ { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */ { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma sd Quattro", 2047, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma SD9", 15, 4095, /* updated */ { 13564,-2537,-751,-5465,15154,194,-67,116,10425 } }, { "Sigma SD10", 15, 16383, /* updated */ { 6787,-1682,575,-3091,8357,160,217,-369,12314 } }, { "Sigma SD14", 15, 16383, /* updated */ { 13589,-2509,-739,-5440,15104,193,-61,105,10554 } }, { "Sigma SD15", 15, 4095, /* updated */ { 13556,-2537,-730,-5462,15144,195,-61,106,10577 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP1X", 0, 4095, /* updated */ { 13704,-2452,-857,-5413,15073,186,-89,151,9820 } }, { "Sigma DP1", 0, 4095, /* updated */ { 12774,-2591,-394,-5333,14676,207,15,-21,12127 } }, { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, {"Sony DSC-RX10M4", -800, 0, /* prelim */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX10",0, 0, /* same for M2/M3 */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, /* updated */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, {"Sony DSC-RX0", -800, 0, /* temp */ { 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, { 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } }, { "Sony ILCE-9", 0, 0, { 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } }, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM3", 0, 0, /* temp */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony MODEL-NAME", 0, 0, /* added */ { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-VG30", 0, 0, /* added */ { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-VG900", 0, 0, /* added */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; // clang-format on double cam_xyz[4][3]; char name[130]; int i, j; if (colors > 4 || colors < 1) return; int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0; if (cblack[4] * cblack[5] > 0) { for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) bl64 += cblack[c + 6]; bl64 /= cblack[4] * cblack[5]; } int rblack = black + bl4 + bl64; sprintf(name, "%s %s", t_make, t_model); for (i = 0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (!dng_version) { if (table[i].t_black > 0) { black = (ushort)table[i].t_black; memset(cblack, 0, sizeof(cblack)); } else if (table[i].t_black < 0 && rblack == 0) { black = (ushort)(-table[i].t_black); memset(cblack, 0, sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort)table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j = 0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if (internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if (!internal_only) #endif cam_xyz_coeff(rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff(int index) { static const float table[][12] = {/* index 0 -- all Foveon cameras */ {1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113}, /* index 1 -- Kodak DC20 and DC25 */ {2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25}, /* index 2 -- Logitech Fotoman Pixtura */ {1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672}, /* index 3 -- Nikon E880, E900, and E990 */ {-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705}}; int i, c; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i * colors + c]; } short CLASS guess_byte_order(int words) { uchar test[4][2]; int t = 2, msb; double diff, sum[2] = {0, 0}; fread(test[0], 2, 2, ifp); for (words -= 2; words--;) { fread(test[t], 2, 1, ifp); for (msb = 0; msb < 2; msb++) { diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]); sum[msb] += diff * diff; } t = (t + 1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green(int bps, int bite, int off0, int off1) { UINT64 bitbuf = 0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; FORC(2) { fseek(ifp, c ? off1 : off0, SEEK_SET); for (vbits = col = 0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps); } } FORC(width - 1) { sum[c & 1] += ABS(img[0][c] - img[1][c + 1]); sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]); } return 100 * log(sum[0] / sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace(string[i])) string[i] = 0; else break; } } void CLASS initdata() { tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } for (int i = 0; i < 0x10000; i++) curve[i] = i; memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { {3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0}, {3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0}, {3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4}, {3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21}, {3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2}, {3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0}, {4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19}, {4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6}, }; static const ushort canon[][11] = { {1944, 1416, 0, 0, 48, 0}, {2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25}, {2224, 1456, 48, 6, 0, 2}, {2376, 1728, 12, 6, 52, 2}, {2672, 1968, 12, 6, 44, 2}, {3152, 2068, 64, 12, 0, 0, 16}, {3160, 2344, 44, 12, 4, 4}, {3344, 2484, 4, 6, 52, 6}, {3516, 2328, 42, 14, 0, 0}, {3596, 2360, 74, 12, 0, 0}, {3744, 2784, 52, 12, 8, 12}, {3944, 2622, 30, 18, 6, 2}, {3948, 2622, 42, 18, 0, 2}, {3984, 2622, 76, 20, 0, 2, 14}, {4104, 3048, 48, 12, 24, 12}, {4116, 2178, 4, 2, 0, 0}, {4152, 2772, 192, 12, 0, 0}, {4160, 3124, 104, 11, 8, 65}, {4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49}, {4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49}, {4312, 2876, 22, 18, 0, 2}, {4352, 2874, 62, 18, 0, 0}, {4476, 2954, 90, 34, 0, 0}, {4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49}, {4480, 3366, 80, 50, 0, 0}, {4496, 3366, 80, 50, 12, 0}, {4768, 3516, 96, 16, 0, 0, 0, 16}, {4832, 3204, 62, 26, 0, 0}, {4832, 3228, 62, 51, 0, 0}, {5108, 3349, 98, 13, 0, 0}, {5120, 3318, 142, 45, 62, 0}, {5280, 3528, 72, 52, 0, 0}, /* EOS M */ {5344, 3516, 142, 51, 0, 0}, {5344, 3584, 126, 100, 0, 2}, {5360, 3516, 158, 51, 0, 0}, {5568, 3708, 72, 38, 0, 0}, {5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49}, {5712, 3774, 62, 20, 10, 2}, {5792, 3804, 158, 51, 0, 0}, {5920, 3950, 122, 80, 2, 0}, {6096, 4056, 72, 34, 0, 0}, /* EOS M3 */ {6288, 4056, 266, 36, 0, 0}, /* EOS 80D */ {6384, 4224, 120, 44, 0, 0}, /* 6D II */ {6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */ {8896, 5920, 160, 64, 0, 0}, }; static const struct { ushort id; char t_model[20]; } unique[] = { {0x001, "EOS-1D"}, {0x167, "EOS-1DS"}, {0x168, "EOS 10D"}, {0x169, "EOS-1D Mark III"}, {0x170, "EOS 300D"}, {0x174, "EOS-1D Mark II"}, {0x175, "EOS 20D"}, {0x176, "EOS 450D"}, {0x188, "EOS-1Ds Mark II"}, {0x189, "EOS 350D"}, {0x190, "EOS 40D"}, {0x213, "EOS 5D"}, {0x215, "EOS-1Ds Mark III"}, {0x218, "EOS 5D Mark II"}, {0x232, "EOS-1D Mark II N"}, {0x234, "EOS 30D"}, {0x236, "EOS 400D"}, {0x250, "EOS 7D"}, {0x252, "EOS 500D"}, {0x254, "EOS 1000D"}, {0x261, "EOS 50D"}, {0x269, "EOS-1D X"}, {0x270, "EOS 550D"}, {0x281, "EOS-1D Mark IV"}, {0x285, "EOS 5D Mark III"}, {0x286, "EOS 600D"}, {0x287, "EOS 60D"}, {0x288, "EOS 1100D"}, {0x289, "EOS 7D Mark II"}, {0x301, "EOS 650D"}, {0x302, "EOS 6D"}, {0x324, "EOS-1D C"}, {0x325, "EOS 70D"}, {0x326, "EOS 700D"}, {0x327, "EOS 1200D"}, {0x328, "EOS-1D X Mark II"}, {0x331, "EOS M"}, {0x335, "EOS M2"}, {0x374, "EOS M3"}, /* temp */ {0x384, "EOS M10"}, /* temp */ {0x394, "EOS M5"}, /* temp */ {0x398, "EOS M100"}, /* temp */ {0x346, "EOS 100D"}, {0x347, "EOS 760D"}, {0x349, "EOS 5D Mark IV"}, {0x350, "EOS 80D"}, {0x382, "EOS 5DS"}, {0x393, "EOS 750D"}, {0x401, "EOS 5DS R"}, {0x404, "EOS 1300D"}, {0x405, "EOS 800D"}, {0x406, "EOS 6D Mark II"}, {0x407, "EOS M6"}, {0x408, "EOS 77D"}, {0x417, "EOS 200D"}, }, sonique[] = { {0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"}, {0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"}, {0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"}, {0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"}, {0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"}, {0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"}, {0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"}, {0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"}, {0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"}, {0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"}, {0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"}, {0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"}, {0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"}, {0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"}, {0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"}, {0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"}, {0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"}, {0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16c, "DSC-RX0"}, {0x16d, "DSC-RX10M4"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { {786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"}, {1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"}, {1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"}, {5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"}, {5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12}, {10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"}, {10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12}, {16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"}, {15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"}, {31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"}, {23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"}, {32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"}, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb {1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"}, {2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"}, {2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"}, {2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"}, {3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"}, {3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"}, {5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"}, {5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"}, {6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"}, {6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"}, {9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"}, {10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"}, {10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"}, {10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"}, {10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"}, {15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"}, {16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"}, {16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"}, {17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"}, {17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"}, {19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"}, {19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"}, {20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"}, {20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"}, {21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"}, {26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"}, {26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"}, {26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"}, {41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"}, {42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"}, // Android Raw dumps id end {20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff}, {2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078}, {5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"}, {6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"}, {6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"}, {6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"}, {7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"}, {9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"}, {9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"}, {10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"}, {10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"}, {12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"}, {15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"}, {15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"}, {15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"}, {18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"}, {18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"}, {19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"}, {21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"}, {24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"}, {30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"}, {1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"}, {3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"}, {6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"}, {7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"}, {2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"}, {4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"}, {6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"}, {7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"}, {7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"}, {7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"}, {7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"}, {7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"}, {9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"}, {10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"}, {10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"}, {10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"}, {12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"}, {12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"}, {15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"}, {18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"}, {7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"}, {787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"}, {28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"}, {15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"}, {3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"}, {307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"}, {62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"}, {4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"}, {4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160}, {2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"}, {6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160}, {460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"}, {12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556}, {18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"}, {614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"}, {15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"}, {3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212}, {1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513}, {1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"}, {2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"}, {2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"}, {4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"}, {4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"}, {5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"}, {5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"}, {7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"}, {8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"}, {5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"}, {3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"}, {4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"}, {6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"}, {10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"}, {4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"}, {4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8}, {13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"}, {6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"}, {311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"}, {16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, {2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])]; #endif static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"}; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize = 1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings); for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++) memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0])); camera_count += sizeof(const_table) / sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 = imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature = imgdata.other.exifAmbientTemperature = -1000.0f; for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } #endif memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i = 0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i = 0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek(ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread(head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread(head, 1, 32, ifp); #endif fseek(ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4))) { parse_phase_one(cp - head); if (cp - head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp(head + 6, "HEAPCCDR", 8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(hlen, flen - hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4)) { fseek(ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek(ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp(head + 25, "ARECOYK", 7)) { strcpy(make, "Contax"); strcpy(model, "N Digital"); fseek(ifp, 33, SEEK_SET); get_timestamp(1); fseek(ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4()) / 8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek(ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp(head, "PXN")) { strcpy(make, "Logitech"); strcpy(model, "Fotoman Pixtura"); } else if (!strcmp(head, "qktk")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp(head, "qktn")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp(head, "FUJIFILM", 8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head + 0x1c); memcpy(model2, head + 0x3c, 4); model2[4] = 0; #endif fseek(ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek(ifp, 92, SEEK_SET); parse_fuji(get4()); if (thumb_offset > 120) { fseek(ifp, 120, SEEK_SET); is_raw += (i = get4()) ? 1 : 0; if (is_raw == 2 && shot_select) parse_fuji(i); } load_raw = &CLASS unpacked_load_raw; fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET); parse_tiff(data_offset = get4()); parse_tiff(thumb_offset + 12); apply_tiff(); } else if (!memcmp(head, "RIFF", 4)) { fseek(ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp(head + 4, "ftypqt ", 9)) { fseek(ifp, 0, SEEK_SET); parse_qt(fsize); is_raw = 0; } else if (!memcmp(head, "\0\001\0\001\0@", 6)) { fseek(ifp, 6, SEEK_SET); fread(make, 1, 8, ifp); fread(model, 1, 8, ifp); fread(model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp(head, "NOKIARAW", 8)) { strcpy(make, "NOKIA"); order = 0x4949; fseek(ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); // bytes count width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // Data integrity check if(width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width*height) || i > (2* width*height)) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif switch (tiff_bps = i * 8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp(head, "ARRI", 4)) { order = 0x4949; fseek(ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy(make, "ARRI"); fseek(ifp, 668, SEEK_SET); fread(model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp(head, "XPDS", 4)) { order = 0x4949; fseek(ifp, 0x800, SEEK_SET); fread(make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek(ifp, 56, SEEK_CUR); fread(model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve(0, 12.25, 1, 1023); } else if (!memcmp(head + 4, "RED1", 4)) { strcpy(make, "Red"); strcpy(model, "One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp(head, "DSC-Image", 9)) parse_rollei(); else if (!memcmp(head, "PWAD", 4)) parse_sinar_ia(); else if (!memcmp(head, "\0MRM", 4)) parse_minolta(0); else if (!memcmp(head, "FOVb", 4)) { #ifdef LIBRAW_LIBRARY_BUILD /* no foveon support for dcraw build from libraw source */ parse_x3f(); #endif } else if (!memcmp(head, "CI", 2)) parse_cine(); if (make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize = i = 0; i < camera_count; i++) #else for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy(make, table[i].t_make); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon", 5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy(model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff ? 0 : table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); break; } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal(0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp, 0, SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); strcpy(model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); if (!strncmp(model, "ov5647", 6)) strcpy(model, "RPi OV5647 v.1"); else strcpy(model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) && fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn")) { strcpy(make, "OmniVision"); data_offset = ftell(ifp) + 0x8000 - 32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i = 0; i < sizeof corp / sizeof *corp; i++) if (strcasestr(make, corp[i])) /* Simplify company names */ strcpy(make, corp[i]); if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) && ((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION")))) *cp = 0; if (!strncasecmp(model, "PENTAX", 6)) strcpy(make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make, sizeof(make)); remove_trailing_spaces(model, sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp(model, make, i) && model[i++] == ' ') memmove(model, model + i, 64 - i); if (!strncmp(model, "FinePix ", 8)) strcpy(model, model + 8); if (!strncmp(model, "Digital Camera ", 15)) strcpy(model, model + 15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model, "K-5", 3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model, "K-70")) { height = 4016; top_margin = 32; width = 6020; left_margin = 60; } if (width == 4736 && !strcmp(model, "K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6112 && !strcmp(model, "KP")) { /* From DNG, maybe too strict */ left_margin = 54; top_margin = 28; width = 6028; height = raw_height - top_margin; } if (width == 6080 && !strcmp(model, "K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model, "645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i = 0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff("Canon", unique[i].t_model); strcpy(model, unique[i].t_model); } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff("Sony", sonique[i].t_model); strcpy(model, sonique[i].t_model); } } if (!strncmp(make, "Nikon", 5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy(model, "C603"); } #ifndef LIBRAW_LIBRARY_BUILD if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); #else /* Always 512 for arw2_load_raw */ if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12)); #endif if (is_foveon) { if (height * 2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; } else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3)) { top_margin = 18; height = raw_height - top_margin; if (raw_width == 7392) { left_margin = 6; width = 7376; } } else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height, width); SWAP(raw_height, raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model, "PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256 / 235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model, "PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model, "PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model, "PowerShot A610")) { if (canon_s2is()) strcpy(model + 10, "S2 IS"); } else if (!strcmp(model, "PowerShot SX220 HS")) { mask[1][3] = -4; top_margin = 16; left_margin = 92; } else if (!strcmp(model, "PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model, "PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width - left_margin - 48; height = raw_height - top_margin - 14; } else if (!strcmp(model, "PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model, "EOS D2000C")) { filters = 0x61616161; if (!black) black = curve[200]; } else if (!strcmp(model, "D1")) { cam_mul[0] *= 256 / 527.0; cam_mul[2] *= 256 / 317.0; } else if (!strcmp(model, "D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000")) { height -= 3; width -= 4; } else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model, "D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model, "D5000") || !strcmp(model, "D90")) { width -= 42; } else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A")) { width -= 44; } else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4)) { width -= 46; } else if (!strcmp(model, "D4") || !strcmp(model, "Df")) { width -= 52; left_margin = 2; } else if (!strcmp(model, "D500")) { // Empty - to avoid width-1 below } else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3)) { width--; } else if (!strcmp(model, "D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model, "D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model, "D2H", 3)) { left_margin = 6; width -= 14; } else if (!strncmp(model, "D2X", 3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model, "D300", 4)) { width -= 32; } else if (!strncmp(make, "Nikon", 5) && raw_width == 4032) { if (!strcmp(model, "COOLPIX P7700")) { adobe_coeff("Nikon", "COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P7800")) { adobe_coeff("Nikon", "COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P340")) load_flags = 0; } else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2")) black = 255; } else if (!strncmp(model, "COOLPIX B700", 12)) { load_flags = 24; black = 200; } else if (!strncmp(model, "1 ", 2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy(model, "E995"); if (strcmp(model, "E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy(model, "E2500"); if (!strcmp(model, "E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model + 1) < 3700) filters = 0x49494949; if (!strcmp(model, "Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green(12, 32, 1188864, 3576832); c = find_green(12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i, c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy(make, "Minolta"); strcpy(model, "DiMAGE Z2"); } load_flags = 6 + 24 * (make[0] == 'M'); } else if (fsize == 6291456) { fseek(ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy(make, "ISG"); model[0] = 0; } } else if (!strncmp(make, "Fujifilm", 8)) { if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { left_margin = 0; top_margin = 0; width = raw_width; height = raw_height; } if (!strcmp(model + 7, "S2Pro")) { strcpy(model, "S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2)) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if (!strcmp(model, "GFX 50S")) { left_margin = 0; top_margin = 0; } if (!strcmp(model, "S5500")) { height -= (top_margin = 6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6]; } else if (!strcmp(model, "KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model, "KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make, "Minolta", 7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model, "DiMAGE A", 8)) { if (!strcmp(model, "DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6)) { sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M')); adobe_coeff(make, model + 20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "DiMAGE G", 8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model, "*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model, "*ist DS")) { height -= 2; } else if (!strncmp(make, "Samsung", 7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000")) { top_margin = 38; left_margin = 92; width = 5456; height = 3634; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make, "Samsung", 7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model, "EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model, "WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model, "WB550")) { strcpy(model, "WB550"); } else if (!strcmp(model, "EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin = 24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model, "STV680 VGA")) { black = 16; } else if (!strcmp(model, "N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model, "640x480")) { gamma_curve(0.45, 4.5, 1, 255); } else if (!strncmp(make, "Hasselblad", 10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if (!strncasecmp(model, "H3D", 3)) { adobe_coeff("Hasselblad", "H3DII-39"); strcpy(model, "H3DII-39"); } } else if (raw_width == 12000) // H6D 100c, A6D 100c { left_margin = 64; width = 11608; top_margin = 108; height = raw_height - top_margin; adobe_coeff("Hasselblad", "H6D-100c"); } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad", "H4D-40"); strcpy(model, "H4D-40"); } else if (raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad", "X1D"); maximum = 0xffff; tiff_bps = 16; } else if (raw_width == 9044) { if (black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H4D-60"); strcpy(model, "H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model, "H3DII-60"); } } else if (raw_width == 4090) { strcpy(model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if (!strncasecmp(model, "H5D", 3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model, "H5D-50"); } else if (!strncasecmp(model, "H3D", 3)) { black = 0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H3D-50"); strcpy(model, "H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model, "H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples + 1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make, "Sinar", 5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make, "Leaf", 4)) { maximum = 0x3fff; fseek(ifp, data_offset, SEEK_SET); if (ljpeg_start(&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy(cdesc, "RBTG"); strcpy(model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy(model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width + height == 3144 + 2060) { if (!model[0]) strcpy(model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6)) { if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height)) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; #ifdef LIBRAW_LIBRARY_BUILD float fratio = float(data_size) / (float(raw_height) * float(raw_width)); if(!(raw_width % 10) && !(data_size % 16384) && fratio >= 1.6f && fratio <= 1.6001f) { load_raw = &CLASS panasonic_16x10_load_raw; zero_is_bad = 0; } #endif if ((height += 12) > raw_height) height = raw_height; for (i = 0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model, "C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make, "Olympus", 7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model, "E-300") || !strcmp(model, "E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset(cblack, 0, sizeof cblack); } } else if (!strcmp(model, "STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model, "E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model, "SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model, "TG-4")) { width -= 16; } else if (!strcmp(model, "TG-5")) { width -= 26; } } else if (!strcmp(model, "N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model, "DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy(cdesc, "RGBE"); } else if (!strcmp(model, "DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make, "Sony", 4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make, "Sony", 4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make, "Sony", 4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make, "Sony", 4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make, "Sony", 4) && raw_width == 6048) { width -= 24; if (strstr(model, "RX1") || strstr(model, "A99")) width -= 6; } else if (!strncmp(make, "Sony", 4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make, "Sony", 4) && raw_width == 8000) { width -= 32; } else if (!strcmp(model, "DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model, "PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve(0, 7, 1, 255); } else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP")) { order = 0x4949; if (filters && data_offset) { fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts(curve, 256); } else gamma_curve(0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model, "EasyShare", 9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make, "Kodak", 5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model, "DCS460A")) goto bw; } else if (!strcmp(model, "DCS660M")) { black = 214; goto bw; } else if (!strcmp(model, "DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model + 4, "20X")) strcpy(cdesc, "MYCY"); if (strstr(model, "DC25")) { strcpy(model, "DC25"); data_offset = 15424; } if (!strncmp(model, "DC2", 3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0 * height) / (3.0 * width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0 * height) / (373.0 * width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model, "40")) { strcpy(model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model, "DC50")) { strcpy(model, "DC50"); height = 512; width = 768; iso_speed = 84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model, "DC120")) { strcpy(model, "DC120"); raw_height = height = 976; raw_width = width = 848; iso_speed = 160; pixel_aspect = height / 0.75 / width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model, "DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed = 140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model, "Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model, "QuickTake", 9)) { if (head[5]) strcpy(model + 10, "200"); fseek(ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(), get2()) == 30 ? 738 : 736; if (height > width) { SWAP(height, width); fseek(ifp, data_offset - 6, SEEK_SET); flip = ~get2() & 3 ? 5 : 6; } filters = 0x61616161; } else if (!strncmp(make, "Rollei", 6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model, "GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model, "BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if (!model[0]) sprintf(model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if (dng_version) /* Override black level by DNG tags */ { /* copy DNG data from per-IFD field to color.dng */ int iifd = 0; // Active IFD we'll show to user. for (; iifd < tiff_nifds; iifd++) if (tiff_ifd[iifd].offset == data_offset) // found break; int pifd = -1; for (int ii = 0; ii < tiff_nifds; ii++) if (tiff_ifd[ii].offset == thumb_offset) // found { pifd = ii; break; } #define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < tiff_nifds) { int sidx; // Per field, not per structure if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ maximum = imgdata.color.dng_levels.dng_whitelevel[0]; black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for (int i = 0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125) { memcpy(rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff(make, model); #ifdef LIBRAW_LIBRARY_BUILD else if (imgdata.color.cam_xyz[0][0] < 0.01) adobe_coeff(make, model, 1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff("Apple", "Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY"); if (!raw_height) raw_height = height; if (!raw_width) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if (flip > 89 || flip < -89) { switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { {0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}}; static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static const double adobe_rgb[3][3] = { {0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}}; static const double wide_rgb[3][3] = { {0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}}; static const double prophoto_rgb[3][3] = { {0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}}; static const double aces_rgb[3][3] = { {0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}}; static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb}; static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"}; static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d}; unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20}; /* bXYZ */ static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc}; unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000}; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2); #endif gamma_curve(gamm[0], gamm[1], 0, 0); memcpy(out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *)calloc(phead[0], 1); merror(oprof, "convert_to_rgb()"); memcpy(oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12 * pbody[0]; for (i = 0; i < pbody[0]; i++) { oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i * 3 + 2] = oprof[0]; oprof[0] += (pbody[i * 3 + 3] + 3) & -4; } memcpy(oprof + 32, pbody, sizeof pbody); oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1; memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite); pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16; for (i = 4; i < 7; i++) memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve); pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { for (num = k = 0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5; } for (i = 0; i < phead[0] / 4; i++) oprof[i] = htonl(oprof[i]); strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw"); strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (out_cam[i][j] = k = 0; k < 3; k++) out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color - 1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset(histogram, 0, sizeof histogram); for (img = image[0], row = 0; row < height; row++) for (col = 0; col < width; col++, img += 4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int)out[c]); } else if (document_mode) img[0] = img[fcol(row, col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort(*)[4])calloc(high, wide * sizeof *img); merror(img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2); #endif for (row = 0; row < high; row++) for (col = 0; col < wide; col++) { ur = r = fuji_width + (row - col) * step; uc = c = (row + col) * step; if (ur > height - 2 || uc > width - 2) continue; fr = r - ur; fc = c - uc; pix = image + ur * width + uc; for (i = 0; i < colors; i++) img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) + (pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr; } free(image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort(*)[4])calloc(width, newdim * sizeof *img); merror(img, "stretch()"); for (rc = row = 0; row < newdim; row++, rc += pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c * width]; if (c + 1 < height) pix1 += width * 4; for (col = 0; col < width; col++, pix0 += 4, pix1 += 4) FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort(*)[4])calloc(height, newdim * sizeof *img); merror(img, "stretch()"); for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c + 1 < width) pix1 += 4; for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4) FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } width = newdim; } free(image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2); #endif } int CLASS flip_index(int row, int col) { if (flip & 4) SWAP(row, col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag + 1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count - 1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val + c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head(struct tiff_hdr *th, int full) { int c, psize = 0; struct tm *t; memset(th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4 + c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy(th->t_desc, desc, 512); strncpy(th->t_make, make, 64); strncpy(th->t_model, model, 64); strcpy(th->soft, "dcraw v" DCRAW_VERSION); t = localtime(&timestamp); sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); strncpy(th->t_artist, artist, 64); if (full) { tiff_set(th, &th->ntag, 254, 4, 1, 0); tiff_set(th, &th->ntag, 256, 4, 1, width); tiff_set(th, &th->ntag, 257, 4, 1, height); tiff_set(th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag - 1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set(th, &th->ntag, 259, 3, 1, 1); tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set(th, &th->ntag, 277, 3, 1, colors); tiff_set(th, &th->ntag, 278, 4, 1, height); tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8); } else tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0'); tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set(th, &th->ntag, 284, 3, 1, 1); tiff_set(th, &th->ntag, 296, 3, 1, 2); tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set(th, &th->ngps, 0, 1, 4, 0x202); tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy(th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc(0xff, tfp); fputc(0xd8, tfp); if (strcmp(t_humb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, tfp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, tfp); } fwrite(t_humb + 2, 1, t_humb_length - 2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp, thumb, thumb_length); free(thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); fputc(0xff, ofp); fputc(0xd8, ofp); if (strcmp(thumb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, ofp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, ofp); } fwrite(thumb + 2, 1, thumb_length - 2, ofp); free(thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white = 0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white = c = 0; c < colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height, width); ppm = (uchar *)calloc(width, colors * output_bps / 8); ppm2 = (ushort *)ppm; merror(ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head(&th, 1); fwrite(&th, sizeof th, 1, ofp); if (oprof) fwrite(oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps) - 1, cdesc); else fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1); soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, width); for (row = 0; row < height; row++, soff += rstep) { for (col = 0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col * colors + c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab((char *)ppm2, (char *)ppm2, width * colors * 2); fwrite(ppm, colors * output_bps / 8, width, ofp); } free(ppm); }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_2946_1
crossvul-cpp_data_good_844_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/gd/ext_gd.h" #include <sys/types.h> #include <sys/stat.h> #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/comparisons.h" #include "hphp/runtime/base/plain-file.h" #include "hphp/runtime/base/request-event-handler.h" #include "hphp/runtime/base/runtime-option.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-printf.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/ext/std/ext_std_file.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/util/alloc.h" #include "hphp/util/rds-local.h" #include "hphp/runtime/ext/gd/libgd/gd.h" #include "hphp/runtime/ext/gd/libgd/gdfontt.h" /* 1 Tiny font */ #include "hphp/runtime/ext/gd/libgd/gdfonts.h" /* 2 Small font */ #include "hphp/runtime/ext/gd/libgd/gdfontmb.h" /* 3 Medium bold font */ #include "hphp/runtime/ext/gd/libgd/gdfontl.h" /* 4 Large font */ #include "hphp/runtime/ext/gd/libgd/gdfontg.h" /* 5 Giant font */ #include <zlib.h> #include <set> #include <folly/portability/Stdlib.h> #include <folly/portability/Unistd.h> /* Section Filters Declarations */ /* IMPORTANT NOTE FOR NEW FILTER * Do not forget to update: * IMAGE_FILTER_MAX: define the last filter index * IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments * image_filter array in PHP_FUNCTION(imagefilter) */ #define IMAGE_FILTER_NEGATE 0 #define IMAGE_FILTER_GRAYSCALE 1 #define IMAGE_FILTER_BRIGHTNESS 2 #define IMAGE_FILTER_CONTRAST 3 #define IMAGE_FILTER_COLORIZE 4 #define IMAGE_FILTER_EDGEDETECT 5 #define IMAGE_FILTER_EMBOSS 6 #define IMAGE_FILTER_GAUSSIAN_BLUR 7 #define IMAGE_FILTER_SELECTIVE_BLUR 8 #define IMAGE_FILTER_MEAN_REMOVAL 9 #define IMAGE_FILTER_SMOOTH 10 #define IMAGE_FILTER_PIXELATE 11 #define IMAGE_FILTER_MAX 11 #define IMAGE_FILTER_MAX_ARGS 6 #define IMAGE_TYPE_GIF 1 #define IMAGE_TYPE_JPEG 2 #define IMAGE_TYPE_PNG 4 #define IMAGE_TYPE_WBMP 8 #define IMAGE_TYPE_XPM 16 // #define IM_MEMORY_CHECK namespace HPHP { /////////////////////////////////////////////////////////////////////////////// #define HAS_GDIMAGESETANTIALIASED #if defined(HAS_GDIMAGEANTIALIAS) #define SetAntiAliased(gd, flag) gdImageAntialias(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #elif defined(HAS_GDIMAGESETANTIALIASED) #define SetAntiAliased(gd, flag) ((gd)->AA = (flag)) #define SetupAntiAliasedColor(gd, color) \ ((gd)->AA ? \ gdImageSetAntiAliased(im, color), gdAntiAliased : \ color) #else #define SetAntiAliased(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #endif /////////////////////////////////////////////////////////////////////////////// // sweep() { this->~Image(); } IMPLEMENT_RESOURCE_ALLOCATION(Image) void Image::reset() { if (m_gdImage) { gdImageDestroy(m_gdImage); m_gdImage = nullptr; } } Image::~Image() { reset(); } struct ImageMemoryAlloc final : RequestEventHandler { ImageMemoryAlloc() : m_mallocSize(0) {} void requestInit() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); #endif assertx(m_mallocSize == 0); m_mallocSize = 0; } void requestShutdown() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); assertx(m_mallocSize == 0); #endif m_mallocSize = 0; } void *imMalloc(size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); if (m_mallocSize + size < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &size, sizeof(size)); m_mallocSize += size; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &size, sizeof(size)); m_mallocSize += size; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void *imCalloc(size_t nmemb, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); size_t bytes = nmemb * size; if (m_mallocSize + bytes < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + bytes); if (!ptr) return nullptr; memset(ptr, 0, sizeof(ln) + sizeof(size) + bytes); memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &bytes, sizeof(bytes)); m_mallocSize += bytes; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + bytes); if (!ptr) return nullptr; memcpy(ptr, &bytes, sizeof(bytes)); memset((char *)ptr + sizeof(size), 0, bytes); m_mallocSize += bytes; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void imFree(void *ptr #ifdef IM_MEMORY_CHECK , int ln #endif ) { size_t size; void *sizePtr = (char *)ptr - sizeof(size); memcpy(&size, sizePtr, sizeof(size)); m_mallocSize -= size; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); int count = m_alloced.erase((char*)sizePtr - sizeof(ln)); assertx(count == 1); // double free on failure assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(lnPtr); #else assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(sizePtr); #endif } // wrapper of realloc, the original buffer is freed on failure void *imRealloc(void *ptr, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); #ifdef IM_MEMORY_CHECK if (!ptr) return imMalloc(size, ln); if (!size) { imFree(ptr, ln); return nullptr; } #else if (!ptr) return imMalloc(size); if (!size) { imFree(ptr); return nullptr; } #endif void *sizePtr = (char *)ptr - sizeof(size); size_t oldSize = 0; if (ptr) memcpy(&oldSize, sizePtr, sizeof(oldSize)); int diff = size - oldSize; void *tmp; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(lnPtr, sizeof(ln) + sizeof(size) + size))) { int count = m_alloced.erase(ptr); assertx(count == 1); // double free on failure local_free(lnPtr); return nullptr; } memcpy(tmp, &ln, sizeof(ln)); memcpy((char*)tmp + sizeof(ln), &size, sizeof(size)); m_mallocSize += diff; if (tmp != lnPtr) { int count = m_alloced.erase(lnPtr); assertx(count == 1); m_alloced.insert(tmp); } return ((char *)tmp + sizeof(ln) + sizeof(size)); #else if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(sizePtr, sizeof(size) + size))) { local_free(sizePtr); return nullptr; } memcpy(tmp, &size, sizeof(size)); m_mallocSize += diff; return ((char *)tmp + sizeof(size)); #endif } #ifdef IM_MEMORY_CHECK void imDump(void *ptrs[], int &n) { int i = 0; for (auto iter = m_alloced.begin(); iter != m_alloced.end(); ++i, ++iter) { void *p = *iter; assertx(p); if (i < n) ptrs[i] = p; int ln; size_t size; memcpy(&ln, p, sizeof(ln)); memcpy(&size, (char*)p + sizeof(ln), sizeof(size)); printf("%d: (%p, %lu)\n", ln, p, size); } n = (i < n) ? i : n; } #endif private: size_t m_mallocSize; #ifdef IM_MEMORY_CHECK std::set<void *> m_alloced; #endif }; IMPLEMENT_STATIC_REQUEST_LOCAL(ImageMemoryAlloc, s_ima); #ifdef IM_MEMORY_CHECK #define IM_MALLOC(size) s_ima->imMalloc((size), __LINE__) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size), __LINE__) #define IM_FREE(ptr) s_ima->imFree((ptr), __LINE__) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size), __LINE__) #else #define IM_MALLOC(size) s_ima->imMalloc((size)) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size)) #define IM_FREE(ptr) s_ima->imFree((ptr)) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size)) #endif #define CHECK_BUFFER(begin, end, size) \ do { \ if (((char*)end) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d)", \ __FUNCTION__, __LINE__, begin, end, size); \ return; \ } \ } while (0) #define CHECK_BUFFER_R(begin, end, size, retcod) \ do { \ if (((char*)(end)) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d, %d)", \ __FUNCTION__, __LINE__, begin, end, size, retcod); \ return retcod; \ } \ } while (0) #define CHECK_ALLOC(ptr, size) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return; \ } \ } while (0) #define CHECK_ALLOC_R(ptr, size, retcod) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return retcod; \ } \ } while (0) // original Zend name is _estrndup static char *php_strndup_impl(const char* s, uint32_t length #ifdef IM_MEMORY_CHECK , int ln #endif ) { char *p; #ifdef IM_MEMORY_CHECK p = (char *)s_ima->imMalloc((length+1), ln); #else p = (char *)s_ima->imMalloc((length+1)); #endif CHECK_ALLOC_R(p, length+1, nullptr); memcpy(p, s, length); p[length] = 0; return p; } static char *php_strdup_impl(const char* s #ifdef IM_MEMORY_CHECK , int ln #endif ) { #ifdef IM_MEMORY_CHECK return php_strndup_impl(s, strlen(s), ln); #else return php_strndup_impl(s, strlen(s)); #endif } #ifdef IM_MEMORY_CHECK #define PHP_STRNDUP(var, s, length) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strndup_impl((s), (length), __LINE__); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strdup_impl(s, __LINE__); \ } while (0) #else #define PHP_STRNDUP(var, s, length) \ do { \ if (var) IM_FREE(var); \ (var) = php_strndup_impl((s), (length)); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) IM_FREE(var); \ (var) = php_strdup_impl(s); \ } while (0) #endif typedef enum { IMAGE_FILETYPE_UNKNOWN=0, IMAGE_FILETYPE_GIF=1, IMAGE_FILETYPE_JPEG, IMAGE_FILETYPE_PNG, IMAGE_FILETYPE_SWF, IMAGE_FILETYPE_PSD, IMAGE_FILETYPE_BMP, IMAGE_FILETYPE_TIFF_II, /* intel */ IMAGE_FILETYPE_TIFF_MM, /* motorola */ IMAGE_FILETYPE_JPC, IMAGE_FILETYPE_JP2, IMAGE_FILETYPE_JPX, IMAGE_FILETYPE_JB2, IMAGE_FILETYPE_SWC, IMAGE_FILETYPE_IFF, IMAGE_FILETYPE_WBMP, /* IMAGE_FILETYPE_JPEG2000 is a userland alias for IMAGE_FILETYPE_JPC */ IMAGE_FILETYPE_XBM, IMAGE_FILETYPE_ICO, IMAGE_FILETYPE_COUNT /* Must remain last */ } image_filetype; // PHP extension STANDARD: image.c /* file type markers */ static const char php_sig_gif[3] = {'G', 'I', 'F'}; static const char php_sig_psd[4] = {'8', 'B', 'P', 'S'}; static const char php_sig_bmp[2] = {'B', 'M'}; static const char php_sig_swf[3] = {'F', 'W', 'S'}; static const char php_sig_swc[3] = {'C', 'W', 'S'}; static const char php_sig_jpg[3] = {(char) 0xff, (char) 0xd8, (char) 0xff}; static const char php_sig_png[8] = {(char) 0x89, (char) 0x50, (char) 0x4e, (char) 0x47, (char) 0x0d, (char) 0x0a, (char) 0x1a, (char) 0x0a}; static const char php_sig_tif_ii[4] = {'I','I', (char)0x2A, (char)0x00}; static const char php_sig_tif_mm[4] = {'M','M', (char)0x00, (char)0x2A}; static const char php_sig_jpc[3] = {(char)0xff, (char)0x4f, (char)0xff}; static const char php_sig_jp2[12] = {(char)0x00, (char)0x00, (char)0x00, (char)0x0c, (char)0x6a, (char)0x50, (char)0x20, (char)0x20, (char)0x0d, (char)0x0a, (char)0x87, (char)0x0a}; static const char php_sig_iff[4] = {'F','O','R','M'}; static const char php_sig_ico[4] = {(char)0x00, (char)0x00, (char)0x01, (char)0x00}; static struct gfxinfo *php_handle_gif(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(3, SEEK_CUR)) return nullptr; String dim = stream->read(5); if (dim.length() != 5) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->width = (unsigned int)s[0] | (((unsigned int)s[1])<<8); result->height = (unsigned int)s[2] | (((unsigned int)s[3])<<8); result->bits = s[4]&0x80 ? ((((unsigned int)s[4])&0x07) + 1) : 0; result->channels = 3; /* always */ return result; } static struct gfxinfo *php_handle_psd(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(8); if (dim.length() != 8) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->height = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->width = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); return result; } static struct gfxinfo *php_handle_bmp(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int size; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(16); if (dim.length() != 16) return nullptr; s = (unsigned char *)dim.c_str(); size = (((unsigned int)s[3]) << 24) + (((unsigned int)s[2]) << 16) + (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (size == 12) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); result->bits = ((unsigned int)s[11]); } else if (size > 12 && (size <= 64 || size == 108 || size == 124)) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[7]) << 24) + (((unsigned int)s[6]) << 16) + (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[11]) << 24) + (((unsigned int)s[10]) << 16) + (((unsigned int)s[9]) << 8) + ((unsigned int)s[8]); result->height = abs((int32_t)result->height); result->bits = (((unsigned int)s[15]) << 8) + ((unsigned int)s[14]); } else { return nullptr; } return result; } static unsigned long int php_swf_get_bits(unsigned char* buffer, unsigned int pos, unsigned int count) { unsigned int loop; unsigned long int result = 0; for (loop = pos; loop < pos + count; loop++) { result = result + ((((buffer[loop / 8]) >> (7 - (loop % 8))) & 0x01) << (count - (loop - pos) - 1)); } return result; } static struct gfxinfo *php_handle_swc(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned long len=64, szlength; int factor=1,maxfactor=16; int slength, status=0; unsigned char *b, *buf=nullptr; String bufz; String tmp; b = (unsigned char *)IM_CALLOC(1, len + 1); CHECK_ALLOC_R(b, (len + 1), nullptr); if (!stream->seek(5, SEEK_CUR)) { IM_FREE(b); return nullptr; } String a = stream->read(64); if (a.length() != 64) { IM_FREE(b); return nullptr; } if (uncompress((Bytef*)b, &len, (const Bytef*)a.c_str(), 64) != Z_OK) { /* failed to decompress the file, will try reading the rest of the file */ if (!stream->seek(8, SEEK_SET)) { IM_FREE(b); return nullptr; } while (!(tmp = stream->read(8192)).empty()) { bufz += tmp; } slength = bufz.length(); /* * zlib::uncompress() wants to know the output data length * if none was given as a parameter * we try from input length * 2 up to input length * 2^8 * doubling it whenever it wasn't big enough * that should be eneugh for all real life cases */ do { szlength=slength*(1<<factor++); buf = (unsigned char *) IM_REALLOC(buf,szlength); if (!buf) IM_FREE(b); CHECK_ALLOC_R(buf, szlength, nullptr); status = uncompress((Bytef*)buf, &szlength, (const Bytef*)bufz.c_str(), slength); } while ((status==Z_BUF_ERROR)&&(factor<maxfactor)); if (status == Z_OK) { memcpy(b, buf, len); } if (buf) { IM_FREE(buf); } } if (!status) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); if (!result) IM_FREE(b); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (b, 0, 5); result->width = (php_swf_get_bits (b, 5 + bits, bits) - php_swf_get_bits (b, 5, bits)) / 20; result->height = (php_swf_get_bits (b, 5 + (3 * bits), bits) - php_swf_get_bits (b, 5 + (2 * bits), bits)) / 20; } else { result = nullptr; } IM_FREE(b); return result; } static struct gfxinfo *php_handle_swf(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned char *a; if (!stream->seek(5, SEEK_CUR)) return nullptr; String str = stream->read(32); if (str.length() != 32) return nullptr; a = (unsigned char *)str.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (a, 0, 5); result->width = (php_swf_get_bits (a, 5 + bits, bits) - php_swf_get_bits (a, 5, bits)) / 20; result->height = (php_swf_get_bits (a, 5 + (3 * bits), bits) - php_swf_get_bits (a, 5 + (2 * bits), bits)) / 20; result->bits = 0; result->channels = 0; return result; } static struct gfxinfo *php_handle_png(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; /* Width: 4 bytes * Height: 4 bytes * Bit depth: 1 byte * Color type: 1 byte * Compression method: 1 byte * Filter method: 1 byte * Interlace method: 1 byte */ if (!stream->seek(8, SEEK_CUR)) return nullptr; String dim = stream->read(9); if (dim.length() < 9) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->height = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); result->bits = (unsigned int)s[8]; return result; } /* routines to handle JPEG data */ /* some defines for the different JPEG block types */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_APP0 0xe0 #define M_APP1 0xe1 #define M_APP2 0xe2 #define M_APP3 0xe3 #define M_APP4 0xe4 #define M_APP5 0xe5 #define M_APP6 0xe6 #define M_APP7 0xe7 #define M_APP8 0xe8 #define M_APP9 0xe9 #define M_APP10 0xea #define M_APP11 0xeb #define M_APP12 0xec #define M_APP13 0xed #define M_APP14 0xee #define M_APP15 0xef #define M_COM 0xFE /* COMment */ #define M_PSEUDO 0xFFD8 /* pseudo marker for start of image(byte 0) */ #define M_EXIF 0xE1 /* Exif Attribute Information */ static unsigned short php_read2(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(2); /* just return 0 if we hit the end-of-file */ if (str.length() != 2) return 0; a = (unsigned char *)str.c_str(); return (((unsigned short)a[0]) << 8) + ((unsigned short)a[1]); } static unsigned int php_next_marker(const req::ptr<File>& file, int /*last_marker*/, int ff_read) { int a=0, marker; // get marker byte, swallowing possible padding if (!ff_read) { size_t extraneous = 0; while ((marker = file->getc()) != 0xff) { if (marker == EOF) { return M_EOI;/* we hit EOF */ } extraneous++; } if (extraneous) { raise_warning("corrupt JPEG data: %zu extraneous bytes before marker", extraneous); } } a = 1; do { if ((marker = file->getc()) == EOF) { return M_EOI;/* we hit EOF */ } ++a; } while (marker == 0xff); if (a < 2) { return M_EOI; /* at least one 0xff is needed before marker code */ } return (unsigned int)marker; } static int php_skip_variable(const req::ptr<File>& stream) { off_t length = (unsigned int)php_read2(stream); if (length < 2) { return 0; } length = length - 2; stream->seek(length, SEEK_CUR); return 1; } static int php_read_APP(const req::ptr<File>& stream, unsigned int marker, Array& info) { unsigned short length; unsigned char markername[16]; length = php_read2(stream); if (length < 2) { return 0; } length -= 2; /* length includes itself */ String buffer = stream->read(length); if (buffer.empty()) { return 0; } snprintf((char*)markername, sizeof(markername), "APP%d", marker - M_APP0); if (!info.exists(String((const char *)markername))) { /* XXX we only catch the 1st tag of it's kind! */ info.set(String((char*)markername, CopyString), buffer); } return 1; } static struct gfxinfo *php_handle_jpeg(const req::ptr<File>& file, Array& info) { struct gfxinfo *result = nullptr; unsigned int marker = M_PSEUDO; unsigned short length, ff_read=1; for (;;) { marker = php_next_marker(file, marker, ff_read); ff_read = 0; switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if (result == nullptr) { /* handle SOFn block */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); length = php_read2(file); result->bits = file->getc(); result->height = php_read2(file); result->width = php_read2(file); result->channels = file->getc(); if (info.isNull() || length < 8) { /* if we don't want an extanded info -> return */ return result; } if (!file->seek(length - 8, SEEK_CUR)) { /* file error after info */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_APP0: case M_APP1: case M_APP2: case M_APP3: case M_APP4: case M_APP5: case M_APP6: case M_APP7: case M_APP8: case M_APP9: case M_APP10: case M_APP11: case M_APP12: case M_APP13: case M_APP14: case M_APP15: if (!info.isNull()) { if (!php_read_APP(file, marker, info)) { /* read all the app markes... */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_SOS: case M_EOI: /* we're about to hit image data, or are at EOF. stop processing. */ return result; default: if (!php_skip_variable(file)) { /* anything else isn't interesting */ return result; } break; } } return result; /* perhaps image broken -> no info but size */ } static unsigned short php_read4(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(4); /* just return 0 if we hit the end-of-file */ if (str.length() != 4) return 0; a = (unsigned char *)str.c_str(); return (((unsigned int)a[0]) << 24) + (((unsigned int)a[1]) << 16) + (((unsigned int)a[2]) << 8) + (((unsigned int)a[3])); } /* JPEG 2000 Marker Codes */ #define JPEG2000_MARKER_PREFIX 0xFF /* All marker codes start with this */ #define JPEG2000_MARKER_SOC 0x4F /* Start of Codestream */ #define JPEG2000_MARKER_SOT 0x90 /* Start of Tile part */ #define JPEG2000_MARKER_SOD 0x93 /* Start of Data */ #define JPEG2000_MARKER_EOC 0xD9 /* End of Codestream */ #define JPEG2000_MARKER_SIZ 0x51 /* Image and tile size */ #define JPEG2000_MARKER_COD 0x52 /* Coding style default */ #define JPEG2000_MARKER_COC 0x53 /* Coding style component */ #define JPEG2000_MARKER_RGN 0x5E /* Region of interest */ #define JPEG2000_MARKER_QCD 0x5C /* Quantization default */ #define JPEG2000_MARKER_QCC 0x5D /* Quantization component */ #define JPEG2000_MARKER_POC 0x5F /* Progression order change */ #define JPEG2000_MARKER_TLM 0x55 /* Tile-part lengths */ #define JPEG2000_MARKER_PLM 0x57 /* Packet length, main header */ #define JPEG2000_MARKER_PLT 0x58 /* Packet length, tile-part header */ #define JPEG2000_MARKER_PPM 0x60 /* Packed packet headers, main header */ #define JPEG2000_MARKER_PPT 0x61 /* Packed packet headers, tile part header */ #define JPEG2000_MARKER_SOP 0x91 /* Start of packet */ #define JPEG2000_MARKER_EPH 0x92 /* End of packet header */ #define JPEG2000_MARKER_CRG 0x63 /* Component registration */ #define JPEG2000_MARKER_COM 0x64 /* Comment */ /* Main loop to parse JPEG2000 raw codestream structure */ static struct gfxinfo *php_handle_jpc(const req::ptr<File>& file) { struct gfxinfo *result = nullptr; int highest_bit_depth, bit_depth; unsigned char first_marker_id; unsigned int i; /* JPEG 2000 components can be vastly different from one another. Each component can be sampled at a different resolution, use a different colour space, have a separate colour depth, and be compressed totally differently! This makes giving a single "bit depth" answer somewhat problematic. For this implementation we'll use the highest depth encountered. */ /* Get the single byte that remains after the file type indentification */ first_marker_id = file->getc(); /* Ensure that this marker is SIZ (as is mandated by the standard) */ if (first_marker_id != JPEG2000_MARKER_SIZ) { raise_warning("JPEG2000 codestream corrupt(Expected SIZ marker " "not found after SOC)"); return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); php_read2(file); /* Lsiz */ php_read2(file); /* Rsiz */ result->width = php_read4(file); /* Xsiz */ result->height = php_read4(file); /* Ysiz */ #if MBO_0 php_read4(file); /* XOsiz */ php_read4(file); /* YOsiz */ php_read4(file); /* XTsiz */ php_read4(file); /* YTsiz */ php_read4(file); /* XTOsiz */ php_read4(file); /* YTOsiz */ #else if (!file->seek(24, SEEK_CUR)) { IM_FREE(result); return nullptr; } #endif result->channels = php_read2(file); /* Csiz */ if (result->channels > 256) { IM_FREE(result); return nullptr; } /* Collect bit depth info */ highest_bit_depth = bit_depth = 0; for (i = 0; i < result->channels; i++) { bit_depth = file->getc(); /* Ssiz[i] */ bit_depth++; if (bit_depth > highest_bit_depth) { highest_bit_depth = bit_depth; } file->getc(); /* XRsiz[i] */ file->getc(); /* YRsiz[i] */ } result->bits = highest_bit_depth; return result; } /* main loop to parse JPEG 2000 JP2 wrapper format structure */ static struct gfxinfo *php_handle_jp2(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; unsigned int box_length; unsigned int box_type; char jp2c_box_id[] = {(char)0x6a, (char)0x70, (char)0x32, (char)0x63}; /* JP2 is a wrapper format for JPEG 2000. Data is contained within "boxes". Boxes themselves can be contained within "super-boxes". Super-Boxes can contain super-boxes which provides us with a hierarchical storage system. It is valid for a JP2 file to contain multiple individual codestreams. We'll just look for the first codestream at the root of the box structure and handle that. */ for (;;) { box_length = php_read4(stream); /* LBox */ /* TBox */ String str = stream->read(sizeof(box_type)); if (str.length() != sizeof(box_type)) { /* Use this as a general "out of stream" error */ break; } memcpy(&box_type, str.c_str(), sizeof(box_type)); if (box_length == 1) { /* We won't handle XLBoxes */ return nullptr; } if (!memcmp(&box_type, jp2c_box_id, 4)) { /* Skip the first 3 bytes to emulate the file type examination */ stream->seek(3, SEEK_CUR); result = php_handle_jpc(stream); break; } /* Stop if this was the last box */ if ((int)box_length <= 0) { break; } /* Skip over LBox (Which includes both TBox and LBox itself */ if (!stream->seek(box_length - 8, SEEK_CUR)) { break; } } if (result == nullptr) { raise_warning("JP2 file has no codestreams at root level"); } return result; } /* tiff constants */ static const int php_tiff_bytes_per_format[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1}; static int get_php_tiff_bytes_per_format(int format) { int size = sizeof(php_tiff_bytes_per_format)/sizeof(int); if (format >= size) { raise_warning("Invalid format %d", format); format = 0; } return php_tiff_bytes_per_format[format]; } /* uncompressed only */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 /* compressed images only */ #define TAG_COMP_IMAGEWIDTH 0xA002 #define TAG_COMP_IMAGEHEIGHT 0xA003 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 static int php_vspprintf(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, ...) ATTRIBUTE_PRINTF(3,4); static int php_vspprintf(char **pbuf, size_t max_len, const char *fmt, ...) { va_list arglist; char *buf; va_start(arglist, fmt); int len = vspprintf_ap(&buf, max_len, fmt, arglist); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } va_end(arglist); return len; } static int php_vspprintf_ap(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, va_list ap) ATTRIBUTE_PRINTF(3,0); static int php_vspprintf_ap(char **pbuf, size_t max_len, const char *fmt, va_list ap) { char *buf; int len = vspprintf_ap(&buf, max_len, fmt, ap); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } return len; } /* Convert a 16 bit unsigned value from file's native byte order */ static int php_ifd_get16u(void *Short, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Short)[0] << 8) | ((unsigned char *)Short)[1]; } else { return (((unsigned char *)Short)[1] << 8) | ((unsigned char *)Short)[0]; } } /* Convert a 16 bit signed value from file's native byte order */ static signed short php_ifd_get16s(void *Short, int motorola_intel) { return (signed short)php_ifd_get16u(Short, motorola_intel); } /* Convert a 32 bit signed value from file's native byte order */ static int php_ifd_get32s(void *Long, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Long)[0] << 24) | (((unsigned char *)Long)[1] << 16) | (((unsigned char *)Long)[2] << 8) | (((unsigned char *)Long)[3] << 0); } else { return (((unsigned char *)Long)[3] << 24) | (((unsigned char *)Long)[2] << 16) | (((unsigned char *)Long)[1] << 8) | (((unsigned char *)Long)[0] << 0); } } /* Convert a 32 bit unsigned value from file's native byte order */ static unsigned php_ifd_get32u(void *Long, int motorola_intel) { return (unsigned)php_ifd_get32s(Long, motorola_intel) & 0xffffffff; } /* main loop to parse TIFF structure */ static struct gfxinfo *php_handle_tiff(const req::ptr<File>& stream, int motorola_intel) { struct gfxinfo *result = nullptr; int i, num_entries; unsigned char *dir_entry; size_t dir_size, entry_value, width=0, height=0, ifd_addr; int entry_tag , entry_type; String ifd_ptr = stream->read(4); if (ifd_ptr.length() != 4) return nullptr; ifd_addr = php_ifd_get32u((void*)ifd_ptr.c_str(), motorola_intel); if (!stream->seek(ifd_addr-8, SEEK_CUR)) return nullptr; String ifd_data = stream->read(2); if (ifd_data.length() != 2) return nullptr; num_entries = php_ifd_get16u((void*)ifd_data.c_str(), motorola_intel); dir_size = 2/*num dir entries*/ +12/*length of entry*/* num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; String ifd_data2 = stream->read(dir_size-2); if ((size_t)ifd_data2.length() != dir_size-2) return nullptr; ifd_data += ifd_data2; /* now we have the directory we can look how long it should be */ for(i=0;i<num_entries;i++) { dir_entry = (unsigned char*)ifd_data.c_str()+2+i*12; entry_tag = php_ifd_get16u(dir_entry+0, motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, motorola_intel); switch(entry_type) { case TAG_FMT_BYTE: case TAG_FMT_SBYTE: entry_value = (size_t)(dir_entry[8]); break; case TAG_FMT_USHORT: entry_value = php_ifd_get16u(dir_entry+8, motorola_intel); break; case TAG_FMT_SSHORT: entry_value = php_ifd_get16s(dir_entry+8, motorola_intel); break; case TAG_FMT_ULONG: entry_value = php_ifd_get32u(dir_entry+8, motorola_intel); break; case TAG_FMT_SLONG: entry_value = php_ifd_get32s(dir_entry+8, motorola_intel); break; default: continue; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGEWIDTH: width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGEHEIGHT: height = entry_value; break; } } if ( width && height) { /* not the same when in for-loop */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->height = height; result->width = width; result->bits = 0; result->channels = 0; return result; } return nullptr; } static struct gfxinfo *php_handle_iff(const req::ptr<File>& stream) { struct gfxinfo * result; char *a; int chunkId; int size; short width, height, bits; String str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); if (strncmp(a+4, "ILBM", 4) && strncmp(a+4, "PBM ", 4)) { return nullptr; } /* loop chunks to find BMHD chunk */ do { str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); chunkId = php_ifd_get32s(a+0, 1); size = php_ifd_get32s(a+4, 1); if (size < 0) return nullptr; if ((size & 1) == 1) { size++; } if (chunkId == 0x424d4844) { /* BMHD chunk */ if (size < 9) return nullptr; str = stream->read(9); if (str.length() != 9) return nullptr; a = (char *)str.c_str(); width = php_ifd_get16s(a+0, 1); height = php_ifd_get16s(a+2, 1); bits = a[8] & 0xff; if (width > 0 && height > 0 && bits > 0 && bits < 33) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = width; result->height = height; result->bits = bits; result->channels = 0; return result; } } else { if (!stream->seek(size, SEEK_CUR)) return nullptr; } } while (1); } /* * int WBMP file format type * byte Header Type * byte Extended Header * byte Header Data (type 00 = multibyte) * byte Header Data (type 11 = name/pairs) * int Number of columns * int Number of rows */ static int php_get_wbmp(const req::ptr<File>& file, struct gfxinfo **result, int check) { int i, width = 0, height = 0; if (!file->rewind()) { return 0; } /* get type */ if (file->getc() != 0) { return 0; } /* skip header */ do { i = file->getc(); if (i < 0) { return 0; } } while (i & 0x80); /* get width */ do { i = file->getc(); if (i < 0) { return 0; } width = (width << 7) | (i & 0x7f); } while (i & 0x80); /* get height */ do { i = file->getc(); if (i < 0) { return 0; } height = (height << 7) | (i & 0x7f); } while (i & 0x80); // maximum valid sizes for wbmp (although 127x127 may be a // more accurate one) if (!height || !width || height > 2048 || width > 2048) { return 0; } if (!check) { (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_WBMP; } static struct gfxinfo *php_handle_wbmp(const req::ptr<File>& stream) { struct gfxinfo *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); if (!php_get_wbmp(stream, &result, 0)) { IM_FREE(result); return nullptr; } return result; } static int php_get_xbm(const req::ptr<File>& stream, struct gfxinfo **result) { String fline; char *iname; char *type; int value; unsigned int width = 0, height = 0; if (result) { *result = nullptr; } if (!stream->rewind()) { return 0; } while (!(fline = HHVM_FN(fgets)(Resource(stream), 0).toString()).empty()) { iname = (char *)IM_MALLOC(fline.size() + 1); CHECK_ALLOC_R(iname, (fline.size() + 1), 0); if (sscanf(fline.c_str(), "#define %s %d", iname, &value) == 2) { if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("width", type)) { width = (unsigned int)value; if (height) { IM_FREE(iname); break; } } if (!strcmp("height", type)) { height = (unsigned int)value; if (width) { IM_FREE(iname); break; } } } IM_FREE(iname); } if (width && height) { if (result) { *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(*result, sizeof(struct gfxinfo), 0); (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_XBM; } return 0; } static struct gfxinfo *php_handle_xbm(const req::ptr<File>& stream) { struct gfxinfo *result; php_get_xbm(stream, &result); return result; } static struct gfxinfo *php_handle_ico(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int num_icons = 0; String dim = stream->read(2); if (dim.length() != 2) { return nullptr; } s = (unsigned char *)dim.c_str(); num_icons = (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (num_icons < 1 || num_icons > 255) { return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); while (num_icons > 0) { dim = stream->read(16); if (dim.length() != 16) { break; } s = (unsigned char *)dim.c_str(); if ((((unsigned int)s[7]) << 8) + ((unsigned int)s[6]) >= result->bits) { result->width = (unsigned int)s[0]; result->height = (unsigned int)s[1]; result->bits = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); } num_icons--; } return result; } /* Convert internal image_type to mime type */ static char *php_image_type_to_mime_type(int image_type) { switch( image_type) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } /* detect filetype from first bytes */ static int php_getimagetype(const req::ptr<File>& file) { String fileType = file->read(3); if (fileType.length() != 3) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 3 */ if (!memcmp(fileType.c_str(), php_sig_gif, 3)) { return IMAGE_FILETYPE_GIF; } else if (!memcmp(fileType.c_str(), php_sig_jpg, 3)) { return IMAGE_FILETYPE_JPEG; } else if (!memcmp(fileType.c_str(), php_sig_png, 3)) { String data = file->read(5); if (data.length() != 5) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } if (!memcmp((fileType + data).c_str(), php_sig_png, 8)) { return IMAGE_FILETYPE_PNG; } else { raise_warning("PNG file corrupted by ASCII conversion"); return IMAGE_FILETYPE_UNKNOWN; } } else if (!memcmp(fileType.c_str(), php_sig_swf, 3)) { return IMAGE_FILETYPE_SWF; } else if (!memcmp(fileType.c_str(), php_sig_swc, 3)) { return IMAGE_FILETYPE_SWC; } else if (!memcmp(fileType.c_str(), php_sig_psd, 3)) { return IMAGE_FILETYPE_PSD; } else if (!memcmp(fileType.c_str(), php_sig_bmp, 2)) { return IMAGE_FILETYPE_BMP; } else if (!memcmp(fileType.c_str(), php_sig_jpc, 3)) { return IMAGE_FILETYPE_JPC; } String data = file->read(1); if (data.length() != 1) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 4 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_tif_ii, 4)) { return IMAGE_FILETYPE_TIFF_II; } else if (!memcmp(fileType.c_str(), php_sig_tif_mm, 4)) { return IMAGE_FILETYPE_TIFF_MM; } else if (!memcmp(fileType.c_str(), php_sig_iff, 4)) { return IMAGE_FILETYPE_IFF; } else if (!memcmp(fileType.c_str(), php_sig_ico, 4)) { return IMAGE_FILETYPE_ICO; } data = file->read(8); if (data.length() != 8) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 12 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_jp2, 12)) { return IMAGE_FILETYPE_JP2; } /* AFTER ALL ABOVE FAILED */ if (php_get_wbmp(file, nullptr, 1)) { return IMAGE_FILETYPE_WBMP; } if (php_get_xbm(file, nullptr)) { return IMAGE_FILETYPE_XBM; } return IMAGE_FILETYPE_UNKNOWN; } String HHVM_FUNCTION(image_type_to_mime_type, int64_t imagetype) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } Variant HHVM_FUNCTION(image_type_to_extension, int64_t imagetype, bool include_dot /*=true */) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return include_dot ? String(".gif") : String("gif"); case IMAGE_FILETYPE_JPEG: return include_dot ? String(".jpeg") : String("jpeg"); case IMAGE_FILETYPE_PNG: return include_dot ? String(".png") : String("png"); case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return include_dot ? String(".swf") : String("swf"); case IMAGE_FILETYPE_PSD: return include_dot ? String(".psd") : String("psd"); case IMAGE_FILETYPE_BMP: case IMAGE_FILETYPE_WBMP: return include_dot ? String(".bmp") : String("bmp"); case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return include_dot ? String(".tiff") : String("tiff"); case IMAGE_FILETYPE_IFF: return include_dot ? String(".iff") : String("iff"); case IMAGE_FILETYPE_JPC: return include_dot ? String(".jpc") : String("jpc"); case IMAGE_FILETYPE_JP2: return include_dot ? String(".jp2") : String("jp2"); case IMAGE_FILETYPE_JPX: return include_dot ? String(".jpx") : String("jpx"); case IMAGE_FILETYPE_JB2: return include_dot ? String(".jb2") : String("jb2"); case IMAGE_FILETYPE_XBM: return include_dot ? String(".xbm") : String("xbm"); case IMAGE_FILETYPE_ICO: return include_dot ? String(".ico") : String("ico"); default: return false; } } const StaticString s_bits("bits"), s_channels("channels"), s_mime("mime"), s_linespacing("linespacing"); gdImagePtr get_valid_image_resource(const Resource& image) { auto img_res = dyn_cast_or_null<Image>(image); if (!img_res || !img_res->get()) { raise_warning("supplied resource is not a valid Image resource"); return nullptr; } return img_res->get(); } Variant getImageSize(const req::ptr<File>& stream, VRefParam imageinfo) { int itype = 0; struct gfxinfo *result = nullptr; auto imageInfoPtr = imageinfo.getVariantOrNull(); if (imageInfoPtr) { *imageInfoPtr = Array::Create(); } itype = php_getimagetype(stream); switch( itype) { case IMAGE_FILETYPE_GIF: result = php_handle_gif(stream); break; case IMAGE_FILETYPE_JPEG: { Array infoArr; if (imageInfoPtr) { infoArr = Array::Create(); } result = php_handle_jpeg(stream, infoArr); if (imageInfoPtr) { *imageInfoPtr = infoArr; } } break; case IMAGE_FILETYPE_PNG: result = php_handle_png(stream); break; case IMAGE_FILETYPE_SWF: result = php_handle_swf(stream); break; case IMAGE_FILETYPE_SWC: result = php_handle_swc(stream); break; case IMAGE_FILETYPE_PSD: result = php_handle_psd(stream); break; case IMAGE_FILETYPE_BMP: result = php_handle_bmp(stream); break; case IMAGE_FILETYPE_TIFF_II: result = php_handle_tiff(stream, 0); break; case IMAGE_FILETYPE_TIFF_MM: result = php_handle_tiff(stream, 1); break; case IMAGE_FILETYPE_JPC: result = php_handle_jpc(stream); break; case IMAGE_FILETYPE_JP2: result = php_handle_jp2(stream); break; case IMAGE_FILETYPE_IFF: result = php_handle_iff(stream); break; case IMAGE_FILETYPE_WBMP: result = php_handle_wbmp(stream); break; case IMAGE_FILETYPE_XBM: result = php_handle_xbm(stream); break; case IMAGE_FILETYPE_ICO: result = php_handle_ico(stream); break; default: case IMAGE_FILETYPE_UNKNOWN: break; } if (result) { DArrayInit ret(7); ret.set(0, (int64_t)result->width); ret.set(1, (int64_t)result->height); ret.set(2, itype); char *temp; php_vspprintf(&temp, 0, "width=\"%d\" height=\"%d\"", result->width, result->height); ret.set(3, String(temp, CopyString)); if (temp) IM_FREE(temp); if (result->bits != 0) { ret.set(s_bits, (int64_t)result->bits); } if (result->channels != 0) { ret.set(s_channels, (int64_t)result->channels); } ret.set(s_mime, (char*)php_image_type_to_mime_type(itype)); IM_FREE(result); return ret.toVariant(); } else { return false; } } Variant HHVM_FUNCTION(getimagesize, const String& filename, VRefParam imageinfo /*=null */) { if (auto stream = File::Open(filename, "rb")) { return getImageSize(stream, imageinfo); } return false; } Variant HHVM_FUNCTION(getimagesizefromstring, const String& imagedata, VRefParam imageinfo /*=null */) { String data = "data://text/plain;base64,"; data += StringUtil::Base64Encode(imagedata); if (auto stream = File::Open(data, "r")) { return getImageSize(stream, imageinfo); } return false; } // PHP extension gd.c #define HAVE_GDIMAGECREATEFROMPNG 1 #if HAVE_LIBTTF|HAVE_LIBFREETYPE #ifndef ENABLE_GD_TTF #define ENABLE_GD_TTF #endif #endif #define PHP_GDIMG_TYPE_GIF 1 #define PHP_GDIMG_TYPE_PNG 2 #define PHP_GDIMG_TYPE_JPG 3 #define PHP_GDIMG_TYPE_WBM 4 #define PHP_GDIMG_TYPE_XBM 5 #define PHP_GDIMG_TYPE_XPM 6 #define PHP_GDIMG_CONVERT_WBM 7 #define PHP_GDIMG_TYPE_GD 8 #define PHP_GDIMG_TYPE_GD2 9 #define PHP_GDIMG_TYPE_GD2PART 10 #define PHP_GDIMG_TYPE_WEBP 11 #define PHP_GD_VERSION_STRING "bundled (2.0.34 compatible)" #define USE_GD_IOCTX 1 #define CTX_PUTC(c,ctx) ctx->putC(ctx, c) #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static req::ptr<File> php_open_plain_file(const String& filename, const char *mode, FILE **fpp) { auto file = File::Open(filename, mode); auto plain_file = dyn_cast_or_null<PlainFile>(file); if (!plain_file) return nullptr; if (FILE* fp = plain_file->getStream()) { if (fpp) *fpp = fp; return file; } file->close(); return nullptr; } static int php_write(void *buf, uint32_t size) { g_context->write((const char *)buf, size); return size; } static void _php_image_output_putc(struct gdIOCtx* /*ctx*/, int c) { /* without the following downcast, the write will fail * (i.e., will write a zero byte) for all * big endian architectures: */ unsigned char ch = (unsigned char) c; php_write(&ch, 1); } static int _php_image_output_putbuf(struct gdIOCtx* /*ctx*/, const void* buf, int len) { return php_write((void *)buf, len); } static void _php_image_output_ctxfree(struct gdIOCtx *ctx) { if (ctx) { IM_FREE(ctx); } } static bool _php_image_output_ctx(const Resource& image, const String& filename, int quality, int basefilter, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp = nullptr; int q = quality, i; int f = basefilter; gdIOCtx *ctx; /* The third (quality) parameter for Wbmp stands for the threshold when called from image2wbmp(). The third (quality) parameter for Wbmp and Xbm stands for the foreground color index when called from imagey<type>(). */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } ctx = gdNewFileCtx(fp); } else { ctx = (gdIOCtx *)IM_MALLOC(sizeof(gdIOCtx)); CHECK_ALLOC_R(ctx, sizeof(gdIOCtx), false); ctx->putC = _php_image_output_putc; ctx->putBuf = _php_image_output_putbuf; ctx->gd_free = _php_image_output_ctxfree; } switch(image_type) { case PHP_GDIMG_CONVERT_WBM: if (q<0||q>255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); } case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, gdIOCtx *, int))(func_p))(im, ctx, q); break; case PHP_GDIMG_TYPE_PNG: ((void(*)(gdImagePtr, gdIOCtx *, int, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_WEBP: ((void(*)(gdImagePtr, gdIOCtx *, int64_t, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_XBM: case PHP_GDIMG_TYPE_WBM: if (q == -1) { // argc < 3 for(i=0; i < gdImageColorsTotal(im); i++) { if (!gdImageRed(im, i) && !gdImageGreen(im, i) && !gdImageBlue(im, i)) break; } q = i; } if (image_type == PHP_GDIMG_TYPE_XBM) { ((void(*)(gdImagePtr, char *, int, gdIOCtx *))(func_p)) (im, (char*)filename.c_str(), q, ctx); } else { ((void(*)(gdImagePtr, int, gdIOCtx *))(func_p))(im, q, ctx); } break; default: ((void(*)(gdImagePtr, gdIOCtx *))(func_p))(im, ctx); break; } ctx->gd_free(ctx); if (fp) { fflush(fp); file->close(); } return true; } /* It converts a gd Image to bw using a threshold value */ static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold) { gdImagePtr im_dest; int white, black; int color, color_org, median; int dest_height = gdImageSY(im_org); int dest_width = gdImageSX(im_org); int x, y; im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate temporary buffer"); return; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } if (im_org->trueColor) { gdImageTrueColorToPalette(im_org, 1, 256); } for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel(im_org, x, y); median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageWBMPCtx (im_dest, black, out); } /* * converts jpeg/png images to wbmp and resizes them as needed */ static bool _php_image_convert(const String& f_org, const String& f_dest, int dest_height, int dest_width, int threshold, int image_type) { gdImagePtr im_org, im_dest, im_tmp; req::ptr<File> org_file, dest_file; FILE *org, *dest; int org_height, org_width; int white, black; int color, color_org, median; int x, y; float x_ratio, y_ratio; #ifdef HAVE_GD_JPG // long ignore_warning; #endif /* Check threshold value */ if (threshold < 0 || threshold > 8) { raise_warning("Invalid threshold value '%d'", threshold); return false; } /* Open origin file */ org_file = php_open_plain_file(f_org, "rb", &org); if (!org_file) { return false; } /* Open destination file */ dest_file = php_open_plain_file(f_dest, "wb", &dest); if (!dest_file) { return false; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid GIF file", f_org.c_str()); return false; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im_org = gdImageCreateFromJpeg(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid JPEG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid PNG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_PNG */ #ifdef HAVE_LIBVPX case PHP_GDIMG_TYPE_WEBP: im_org = gdImageCreateFromWebp(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid webp file", f_org.c_str()); return false; } break; #endif /* HAVE_LIBVPX */ default: raise_warning("Format not supported"); return false; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == nullptr) { raise_warning("Unable to allocate temporary buffer"); return false; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); org_file->close(); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate destination buffer"); return false; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } threshold = threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel(im_dest, x, y, color); } } gdImageDestroy(im_tmp); gdImageWBMP(im_dest, black , dest); fflush(dest); dest_file->close(); gdImageDestroy(im_dest); return true; } // For quality and type, -1 means that the argument does not exist static bool _php_image_output(const Resource& image, const String& filename, int quality, int type, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp; int q = quality, i, t = type; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ /* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */ /* The quality parameter for gd2 stands for chunk size */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, fp); break; case PHP_GDIMG_TYPE_JPG: { // gdImageJpeg ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, fp, q); break; } case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) break; } // gdImageWBMP ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, i, fp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } // gdImageGd ((void(*)(gdImagePtr, FILE *))(func_p))(im, fp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } // gdImageGd2 ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; default: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; } fflush(fp); file->close(); } else { int b; FILE *tmp; char buf[4096]; char path[PATH_MAX]; // open a temporary file snprintf(path, sizeof(path), "/tmp/XXXXXX"); int fd = mkstemp(path); if (fd == -1 || (tmp = fdopen(fd, "r+b")) == nullptr) { if (fd != -1) close(fd); raise_warning("Unable to open temporary file"); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, tmp); break; case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, tmp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) { break; } } ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, q, tmp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, tmp, q, t); break; default: ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; } fseek(tmp, 0, SEEK_SET); while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) { g_context->write(buf, b); } fclose(tmp); /* make sure that the temporary file is removed */ unlink((const char *)path); } return true; } static gdImagePtr _php_image_create_from(const String& filename, int srcX, int srcY, int width, int height, int image_type, char *tn, gdImagePtr(*func_p)(), gdImagePtr(*ioctx_func_p)()) { VMRegAnchor _; gdImagePtr im = nullptr; #ifdef HAVE_GD_JPG // long ignore_warning; #endif if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (width < 1 || height < 1) { raise_warning("Zero width or height not allowed"); return nullptr; } } auto file = File::Open(filename, "rb"); if (!file) { raise_warning("failed to open stream: %s", filename.c_str()); return nullptr; } FILE *fp = nullptr; auto plain_file = dyn_cast<PlainFile>(file); if (plain_file) { fp = plain_file->getStream(); } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; // copy all String buff = file->read(8192); String str; do { str = file->read(8192); buff += str; } while (!str.empty()); if (buff.empty()) { raise_warning("Cannot read image data"); return nullptr; } io_ctx = gdNewDynamicCtxEx(buff.length(), (char *)buff.c_str(), 0); if (!io_ctx) { raise_warning("Cannot allocate GD IO context"); return nullptr; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = ((gdImagePtr(*)(gdIOCtx *, int, int, int, int))(ioctx_func_p)) (io_ctx, srcX, srcY, width, height); } else { im = ((gdImagePtr(*)(gdIOCtx *))(ioctx_func_p))(io_ctx); } io_ctx->gd_free(io_ctx); } else { /* TODO: try and force the stream to be FILE* */ assertx(false); } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = ((gdImagePtr(*)(FILE *, int, int, int, int))(func_p)) (fp, srcX, srcY, width, height); break; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(filename); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im = gdImageCreateFromJpeg(fp); break; #endif default: im = ((gdImagePtr(*)(FILE*))(func_p))(fp); break; } fflush(fp); } if (im) { file->close(); return im; } raise_warning("'%s' is not a valid %s file", filename.c_str(), tn); file->close(); return nullptr; } static const char php_sig_gd2[3] = {'g', 'd', '2'}; /* getmbi ** ------ ** Get a multibyte integer from a generic getin function ** 'getin' can be getc, with in = NULL ** you can find getin as a function just above the main function ** This way you gain a lot of flexibilty about how this package ** reads a wbmp file. */ static int getmbi(gdIOCtx *ctx) { int i, mbi = 0; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); mbi = (mbi << 7) | (i & 0x7f); } while (i & 0x80); return (mbi); } /* skipheader ** ---------- ** Skips the ExtHeader. Not needed for the moment ** */ int skipheader (gdIOCtx *ctx) { int i; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); } while (i & 0x80); return (0); } static int _php_image_type (char data[8]) { if (data == nullptr) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (getmbi(io_ctx) == 0 && skipheader(io_ctx) == 0 ) { io_ctx->gd_free(io_ctx); return PHP_GDIMG_TYPE_WBM; } else { io_ctx->gd_free(io_ctx); } } } return -1; } gdImagePtr _php_image_create_from_string(const String& image, char *tn, gdImagePtr (*ioctx_func_p)()) { VMRegAnchor _; gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(image.length(), (char *)image.c_str(), 0); if (!io_ctx) { return nullptr; } gdImagePtr im = (*(gdImagePtr (*)(gdIOCtx *))ioctx_func_p)(io_ctx); if (!im) { raise_warning("Passed data is not in '%s' format", tn); io_ctx->gd_free(io_ctx); return nullptr; } io_ctx->gd_free(io_ctx); return im; } static gdFontPtr php_find_gd_font(int size) { gdFontPtr font; switch (size) { case 1: font = gdFontTiny; break; case 2: font = gdFontSmall; break; case 3: font = gdFontMediumBold; break; case 4: font = gdFontLarge; break; case 5: font = gdFontGiant; break; default: raise_warning("Unsupported font: %d", size); // font = zend_list_find(size - 5, &ind_type); // if (!font || ind_type != le_gd_font) { if (size < 1) { font = gdFontTiny; } else { font = gdFontGiant; } break; } return font; } /* workaround for a bug in gd 1.2 */ static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy, px, py, fline; cx = 0; cy = 0; if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } /* * arg = 0 ImageChar * arg = 1 ImageCharUp * arg = 2 ImageString * arg = 3 ImageStringUp */ static bool php_imagechar(const Resource& image, int size, int x, int y, const String& c, int color, int mode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ch = 0; gdFontPtr font; if (mode < 2) { ch = (int)((unsigned char)(c.charAt(0))); } font = php_find_gd_font(size); switch (mode) { case 0: gdImageChar(im, font, x, y, ch, color); break; case 1: php_gdimagecharup(im, font, x, y, ch, color); break; case 2: for (int i = 0; (i < c.length()); i++) { gdImageChar(im, font, x, y, (int)((unsigned char)c.charAt(i)), color); x += font->w; } break; case 3: for (int i = 0; (i < c.length()); i++) { gdImageCharUp(im, font, x, y, (int)c.charAt(i), color); y -= font->w; } break; } return true; } /* arg = 0 normal polygon arg = 1 filled polygon */ static bool php_imagepolygon(const Resource& image, const Array& points, int num_points, int color, int filled) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdPointPtr pts; int nelem, i; nelem = points.size(); if (nelem < 6) { raise_warning("You must have at least 3 points in your array"); return false; } if (nelem < num_points * 2) { raise_warning("Trying to use %d points in array with only %d points", num_points, nelem/2); return false; } pts = (gdPointPtr)IM_MALLOC(num_points * sizeof(gdPoint)); CHECK_ALLOC_R(pts, (num_points * sizeof(gdPoint)), false); for (i = 0; i < num_points; i++) { if (points.exists(i * 2)) { pts[i].x = points[i * 2].toInt32(); } if (points.exists(i * 2 + 1)) { pts[i].y = points[i * 2 + 1].toInt32(); } } if (filled) { gdImageFilledPolygon(im, pts, num_points, color); } else { color = SetupAntiAliasedColor(im, color); gdImagePolygon(im, pts, num_points, color); } IM_FREE(pts); return true; } static bool php_image_filter_negate(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageNegate(im) == 1; } static bool php_image_filter_grayscale(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGrayScale(im) == 1; } static bool php_image_filter_brightness(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int brightness = arg1; return gdImageBrightness(im, brightness) == 1; } static bool php_image_filter_contrast(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int contrast = arg1; return gdImageContrast(im, contrast) == 1; } static bool php_image_filter_colorize(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int arg3 /* = 0 */, int /*arg4*/ /* = 0 */) { int r = arg1; int g = arg2; int b = arg3; int a = arg1; return gdImageColor(im, r, g, b, a) == 1; } static bool php_image_filter_edgedetect(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEdgeDetectQuick(im) == 1; } static bool php_image_filter_emboss(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEmboss(im) == 1; } static bool php_image_filter_gaussian_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGaussianBlur(im) == 1; } static bool php_image_filter_selective_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageSelectiveBlur(im) == 1; } static bool php_image_filter_mean_removal(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageMeanRemoval(im) == 1; } static bool php_image_filter_smooth(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int weight = arg1; return gdImageSmooth(im, weight) == 1; } static bool php_image_filter_pixelate(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int blocksize = arg1; unsigned mode = arg2; return gdImagePixelate(im, blocksize, mode) == 1; } /* * arg = 0 ImageFontWidth * arg = 1 ImageFontHeight */ static int php_imagefontsize(int size, int arg) { gdFontPtr font = php_find_gd_font(size); return (arg ? font->h : font->w); } #ifdef ENABLE_GD_TTF #define TTFTEXT_DRAW 0 #define TTFTEXT_BBOX 1 #endif #ifdef ENABLE_GD_TTF static Variant php_imagettftext_common(int mode, int extended, const Variant& arg1, const Variant& arg2, const Variant& arg3, const Variant& arg4, const Variant& arg5 = uninit_variant, const Variant& arg6 = uninit_variant, const Variant& arg7 = uninit_variant, const Variant& arg8 = uninit_variant, const Variant& arg9 = uninit_variant) { gdImagePtr im=nullptr; long col = -1, x = -1, y = -1; int brect[8]; double ptsize, angle; String str; String fontname; Array extrainfo; char *error = nullptr; gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { ptsize = arg1.toDouble(); angle = arg2.toDouble(); fontname = arg3.toString(); str = arg4.toString(); extrainfo = arg5; } else { Resource image = arg1.toResource(); ptsize = arg2.toDouble(); angle = arg3.toDouble(); x = arg4.toInt64(); y = arg5.toInt64(); col = arg6.toInt64(); fontname = arg7.toString(); str = arg8.toString(); extrainfo = arg9; im = get_valid_image_resource(image); if (!im) return false; } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && !extrainfo.empty()) { /* parse extended info */ /* walk the assoc array */ for (ArrayIter iter(extrainfo); iter; ++iter) { Variant key = iter.first(); if (!key.isString()) continue; Variant item = iter.second(); if (equal(key, s_linespacing)) { strex.flags |= gdFTEX_LINESPACE; strex.linespacing = item.toDouble(); } } } FILE *fp = nullptr; if (!RuntimeOption::FontPath.empty()) { fontname = String(RuntimeOption::FontPath.c_str()) + HHVM_FN(basename)(fontname); } auto stream = php_open_plain_file(fontname, "rb", &fp); if (!stream) { raise_warning("Invalid font filename %s", fontname.c_str()); return false; } stream->close(); #ifdef USE_GD_IMGSTRTTF if (extended) { error = gdImageStringFTEx(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str(), &strex); } else { error = gdImageStringFT(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str()); } #else /* !USE_GD_IMGSTRTTF */ error = gdttf(im, brect, col, fontname.c_str(), ptsize, angle, x, y, str.c_str()); #endif if (error) { raise_warning("%s", error); return false; } /* return array with the text's bounding box */ Array ret = Array::CreateDArray(); for (int i = 0; i < 8; i++) { ret.set(i, brect[i]); } return ret; } #endif /* ENABLE_GD_TTF */ const StaticString s_GD_Version("GD Version"), s_FreeType_Support("FreeType Support"), s_FreeType_Linkage("FreeType Linkage"), s_with_freetype("with freetype"), s_with_TTF_library("with TTF library"), s_with_unknown_library("with unknown library"), s_T1Lib_Support("T1Lib_Support"), s_GIF_Read_Support("GIF Read Support"), s_GIF_Create_Support("GIF Create Support"), s_JPG_Support("JPEG Support"), s_PNG_Support("PNG Support"), s_WBMP_Support("WBMP Support"), s_XPM_Support("XPM Support"), s_XBM_Support("XBM Support"), s_JIS_mapped_Japanese_Font_Support("JIS-mapped Japanese Font Support"); Array HHVM_FUNCTION(gd_info) { Array ret = Array::CreateDArray(); ret.set(s_GD_Version, PHP_GD_VERSION_STRING); #ifdef ENABLE_GD_TTF ret.set(s_FreeType_Support, true); #if HAVE_LIBFREETYPE ret.set(s_FreeType_Linkage, s_with_freetype); #elif HAVE_LIBTTF ret.set(s_FreeType_Linkage, s_with_TTF_library); #else ret.set(s_FreeType_Linkage, s_with_unknown_library); #endif #else ret.set(s_FreeType_Support, false); #endif #ifdef HAVE_LIBT1 ret.set(s_T1Lib_Support, true); #else ret.set(s_T1Lib_Support, false); #endif ret.set(s_GIF_Read_Support, true); ret.set(s_GIF_Create_Support, true); #ifdef HAVE_GD_JPG ret.set(s_JPG_Support, true); #else ret.set(s_JPG_Support, false); #endif #ifdef HAVE_GD_PNG ret.set(s_PNG_Support, true); #else ret.set(s_PNG_Support, false); #endif ret.set(s_WBMP_Support, true); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret.set(s_XPM_Support, true); #else ret.set(s_XPM_Support, false); #endif ret.set(s_XBM_Support, true); #if defined(USE_GD_JISX0208) && defined(HAVE_GD_BUNDLED) ret.set(s_JIS_mapped_Japanese_Font_Support, true); #else ret.set(s_JIS_mapped_Japanese_Font_Support, false); #endif return ret; } #define FLIPWORD(a) (((a & 0xff000000) >> 24) | \ ((a & 0x00ff0000) >> 8) | \ ((a & 0x0000ff00) << 8) | \ ((a & 0x000000ff) << 24)) Variant HHVM_FUNCTION(imageloadfont, const String& /*file*/) { // TODO: ind = 5 + zend_list_insert(font, le_gd_font); throw_not_supported(__func__, "NYI"); #ifdef NEVER Variant stream; zval **file; int hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; stream = File::Open(file, "rb"); if (!stream) { raise_warning("failed to open file: %s", file.c_str()); return false; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) IM_MALLOC(sizeof(gdFont)); CHECK_ALLOC_R(font, sizeof(gdFont), false); b = 0; String hdr = stream->read(hdr_size); if (hdr.length() < hdr_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading header"); } else { raise_warning("Error while reading header"); } stream->close(); return false; } memcpy((void*)font, hdr.c_str(), hdr.length()); i = int64_t(f_tell(stream)); stream->seek(0, SEEK_END); body_size_check = int64_t(f_tell(stream)) - hdr_size; stream->seek(i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (font->nchars <= 0 || font->h <= 0 || font->nchars >= INT_MAX || font->h >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if ((font->nchars * font->h) <= 0 || font->w <= 0 || (font->nchars * font->h) >= INT_MAX || font->w >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if (body_size != body_size_check) { raise_warning("Error reading font"); IM_FREE(font); stream->close(); return false; } String body = stream->read(body_size); if (body.length() < body_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading body"); } else { raise_warning("Error while reading body"); } stream->close(); return false; } font->data = IM_MALLOC(body_size); CHECK_ALLOC_R(font->data, body_size, false); memcpy((void*)font->data, body.c_str(), body.length()); stream->close(); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ // ind = 5 + zend_list_insert(font, le_gd_font); return ind; #endif } bool HHVM_FUNCTION(imagesetstyle, const Resource& image, const Array& style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int *stylearr; int index; size_t malloc_size = sizeof(int) * style.size(); stylearr = (int *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(stylearr, malloc_size, false); index = 0; for (ArrayIter iter(style); iter; ++iter) { stylearr[index++] = cellToInt(tvToCell(iter.secondVal())); } gdImageSetStyle(im, stylearr, index); IM_FREE(stylearr); return true; } const StaticString s_x("x"), s_y("y"), s_width("width"), s_height("height"); Variant HHVM_FUNCTION(imagecrop, const Resource& image, const Array& rect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; gdRect gdrect; if (rect.exists(s_x)) { gdrect.x = rect[s_x].toInt64(); } else { raise_warning("imagecrop(): Missing x position"); return false; } if (rect.exists(s_y)) { gdrect.y = rect[s_y].toInt64(); } else { raise_warning("imagecrop(): Missing y position"); return false; } if (rect.exists(s_width)) { gdrect.width = rect[s_width].toInt64(); } else { raise_warning("imagecrop(): Missing width position"); return false; } if (rect.exists(s_height)) { gdrect.height = rect[s_height].toInt64(); } else { raise_warning("imagecrop(): Missing height position"); return false; } imcropped = gdImageCrop(im, &gdrect); if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecropauto, const Resource& image, int64_t mode /* = -1 */, double threshold /* = 0.5f */, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; switch (mode) { case -1: mode = GD_CROP_DEFAULT; case GD_CROP_DEFAULT: case GD_CROP_TRANSPARENT: case GD_CROP_BLACK: case GD_CROP_WHITE: case GD_CROP_SIDES: imcropped = gdImageCropAuto(im, mode); break; case GD_CROP_THRESHOLD: if (color < 0) { raise_warning("imagecropauto(): Color argument missing " "with threshold mode"); return false; } imcropped = gdImageCropThreshold(im, color, (float) threshold); break; default: raise_warning("imagecropauto(): Unknown crop mode"); return false; } if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecreatetruecolor, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreateTrueColor(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } bool f_imageistruecolor(const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return im->trueColor; } Variant HHVM_FUNCTION(imagetruecolortopalette, const Resource& image, bool dither, int64_t ncolors) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (ncolors <= 0 || ncolors >= INT_MAX) { raise_warning("Number of colors has to be greater than zero"); return false; } gdImageTrueColorToPalette(im, dither, ncolors); return true; } Variant HHVM_FUNCTION(imagecolormatch, const Resource& image1, const Resource& image2) { gdImagePtr im1 = get_valid_image_resource(image1); if (!im1) return false; gdImagePtr im2 = get_valid_image_resource(image2); if (!im2) return false; int result; result = gdImageColorMatch(im1, im2); switch (result) { case -1: raise_warning("Image1 must be TrueColor"); return false; case -2: raise_warning("Image2 must be Palette"); return false; case -3: raise_warning("Image1 and Image2 must be the same size"); return false; case -4: raise_warning("Image2 must have at least one color"); return false; } return true; } bool HHVM_FUNCTION(imagesetthickness, const Resource& image, int64_t thickness) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetThickness(im, thickness); return true; } bool HHVM_FUNCTION(imagefilledellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledEllipse(im, cx, cy, width, height, color); return true; } bool HHVM_FUNCTION(imagefilledarc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color, int64_t style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; gdImageFilledArc(im, cx, cy, width, height, start, end, color, style); return true; } Variant HHVM_FUNCTION(imageaffine, const Resource& image, const Array& affine /* = Array() */, const Array& clip /* = Array() */) { gdImagePtr src = get_valid_image_resource(image); if (!src) return false; gdImagePtr dst = nullptr; gdRect rect; gdRectPtr pRect = nullptr; int nelem = affine.size(); int i; double daffine[6]; if (nelem != 6) { raise_warning("imageaffine(): Affine array must have six elements"); return false; } for (i = 0; i < nelem; i++) { if (affine[i].isInteger()) { daffine[i] = affine[i].toInt64(); } else if (affine[i].isDouble() || affine[i].isString()) { daffine[i] = affine[i].toDouble(); } else { raise_warning("imageaffine(): Invalid type for element %i", i); return false; } } if (!clip.empty()) { if (clip.exists(s_x)) { rect.x = clip[s_x].toInt64(); } else { raise_warning("imageaffine(): Missing x position"); return false; } if (clip.exists(s_y)) { rect.y = clip[s_y].toInt64(); } else { raise_warning("imageaffine(): Missing y position"); return false; } if (clip.exists(s_width)) { rect.width = clip[s_width].toInt64(); } else { raise_warning("imageaffine(): Missing width position"); return false; } if (clip.exists(s_height)) { rect.height = clip[s_height].toInt64(); } else { raise_warning("imageaffine(): Missing height position"); return false; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = nullptr; } if (gdTransformAffineGetImage(&dst, src, pRect, daffine) != GD_TRUE) { return false; } return Variant(req::make<Image>(dst)); } Variant HHVM_FUNCTION(imageaffinematrixconcat, const Array& m1, const Array& m2) { int nelem1 = m1.size(); int nelem2 = m2.size(); int i; double dm1[6]; double dm2[6]; double dmr[6]; Array ret = Array::Create(); if (nelem1 != 6 || nelem2 != 6) { raise_warning("imageaffinematrixconcat(): Affine array must " "have six elements"); return false; } for (i = 0; i < 6; i++) { if (m1[i].isInteger()) { dm1[i] = m1[i].toInt64(); } else if (m1[i].isDouble() || m1[i].isString()) { dm1[i] = m1[i].toDouble(); } else { raise_warning("imageaffinematrixconcat(): Invalid type for " "element %i", i); return false; } if (m2[i].isInteger()) { dm2[i] = m2[i].toInt64(); } else if (m2[i].isDouble() || m2[i].isString()) { dm2[i] = m2[i].toDouble(); } else { raise_warning("imageaffinematrixconcat():Invalid type for" "element %i", i); return false; } } if (gdAffineConcat(dmr, dm1, dm2) != GD_TRUE) { return false; } for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), dmr[i]); } return ret; } Variant HHVM_FUNCTION(imageaffinematrixget, int64_t type, const Variant& options /* = Array() */) { Array ret = Array::Create(); double affine[6]; int res = GD_FALSE, i; switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; Array aoptions = options.toArray(); if (aoptions.empty()) { raise_warning("imageaffinematrixget(): Array expected as options"); return false; } if (aoptions.exists(s_x)) { x = aoptions[s_x].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (aoptions.exists(s_y)) { y = aoptions[s_y].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; double doptions = options.toDouble(); if (!doptions) { raise_warning("imageaffinematrixget(): Number is expected as option"); return false; } angle = doptions; if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: raise_warning("imageaffinematrixget():Invalid type for " "element %" PRId64, type); return false; } if (res == GD_FALSE) { return false; } else { for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), affine[i]); } } return ret; } bool HHVM_FUNCTION(imagealphablending, const Resource& image, bool blendmode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, blendmode); return true; } bool HHVM_FUNCTION(imagesavealpha, const Resource& image, bool saveflag) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSaveAlpha(im, saveflag); return true; } bool HHVM_FUNCTION(imagelayereffect, const Resource& image, int64_t effect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, effect); return true; } Variant HHVM_FUNCTION(imagecolorallocatealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagecolorresolvealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolveAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorclosestalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorexactalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExactAlpha(im, red, green, blue, alpha); } bool HHVM_FUNCTION(imagecopyresampled, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = get_valid_image_resource(src_im); if (!im_src) return false; gdImagePtr im_dst = get_valid_image_resource(dst_im); if (!im_dst) return false; gdImageCopyResampled(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagerotate, const Resource& source_image, double angle, int64_t bgd_color, int64_t /*ignore_transparent*/ /* = 0 */) { gdImagePtr im_src = get_valid_image_resource(source_image); if (!im_src) return false; gdImagePtr im_dst = gdImageRotateInterpolated(im_src, angle, bgd_color); if (!im_dst) return false; return Variant(req::make<Image>(im_dst)); } bool HHVM_FUNCTION(imagesettile, const Resource& image, const Resource& tile) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr til = get_valid_image_resource(tile); if (!til) return false; gdImageSetTile(im, til); return true; } bool HHVM_FUNCTION(imagesetbrush, const Resource& image, const Resource& brush) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr tile = get_valid_image_resource(brush); if (!tile) return false; gdImageSetBrush(im, tile); return true; } bool HHVM_FUNCTION(imagesetinterpolation, const Resource& image, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (method == -1) method = GD_BILINEAR_FIXED; return gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method); } Variant HHVM_FUNCTION(imagecreate, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreate(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } int64_t HHVM_FUNCTION(imagetypes) { int ret=0; ret = IMAGE_TYPE_GIF; #ifdef HAVE_GD_JPG ret |= IMAGE_TYPE_JPEG; #endif #ifdef HAVE_GD_PNG ret |= IMAGE_TYPE_PNG; #endif ret |= IMAGE_TYPE_WBMP; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret |= IMAGE_TYPE_XPM; #endif return ret; } Variant HHVM_FUNCTION(imagecreatefromstring, const String& data) { gdImagePtr im; int imtype; char sig[8]; if (data.length() < 8) { raise_warning("Empty string or invalid image"); return false; } memcpy(sig, data.c_str(), 8); imtype = _php_image_type(sig); switch (imtype) { case PHP_GDIMG_TYPE_JPG: #ifdef HAVE_GD_JPG im = _php_image_create_from_string(data, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpegCtx); #else raise_warning("No JPEG support"); return false; #endif break; case PHP_GDIMG_TYPE_PNG: #ifdef HAVE_GD_PNG im = _php_image_create_from_string(data, "PNG", (gdImagePtr(*)())gdImageCreateFromPngCtx); #else raise_warning("No PNG support"); return false; #endif break; case PHP_GDIMG_TYPE_WEBP: #ifdef HAVE_LIBVPX im = _php_image_create_from_string(data, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebpCtx); #else raise_warning("No webp support (libvpx is needed)"); return false; #endif break; case PHP_GDIMG_TYPE_GIF: im = _php_image_create_from_string(data, "GIF", (gdImagePtr(*)())gdImageCreateFromGifCtx); break; case PHP_GDIMG_TYPE_WBM: im = _php_image_create_from_string(data, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMPCtx); break; case PHP_GDIMG_TYPE_GD2: im = _php_image_create_from_string(data, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Ctx); break; default: raise_warning("Data is not in a recognized format"); return false; } if (!im) { raise_warning("Couldn't create GD Image Stream out of Data"); return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgif, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (gdImagePtr(*)())gdImageCreateFromGif, (gdImagePtr(*)())gdImageCreateFromGifCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #ifdef HAVE_GD_JPG Variant HHVM_FUNCTION(imagecreatefromjpeg, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpeg, (gdImagePtr(*)())gdImageCreateFromJpegCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_GD_PNG Variant HHVM_FUNCTION(imagecreatefrompng, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_PNG, "PNG", (gdImagePtr(*)())gdImageCreateFromPng, (gdImagePtr(*)())gdImageCreateFromPngCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_LIBVPX Variant HHVM_FUNCTION(imagecreatefromwebp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebp, (gdImagePtr(*)())gdImageCreateFromWebpCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromxbm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XBM, "XBM", (gdImagePtr(*)())gdImageCreateFromXbm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) Variant HHVM_FUNCTION(imagecreatefromxpm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XPM, "XPM", (gdImagePtr(*)())gdImageCreateFromXpm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromwbmp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMP, (gdImagePtr(*)())gdImageCreateFromWBMPCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (gdImagePtr(*)())gdImageCreateFromGd, (gdImagePtr(*)())gdImageCreateFromGdCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD2, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2, (gdImagePtr(*)())gdImageCreateFromGd2Ctx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2part, const String& filename, int64_t srcx, int64_t srcy, int64_t width, int64_t height) { gdImagePtr im = _php_image_create_from(filename, srcx, srcy, width, height, PHP_GDIMG_TYPE_GD2PART, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Part, (gdImagePtr(*)())gdImageCreateFromGd2PartCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } bool HHVM_FUNCTION(imagegif, const Resource& image, const String& filename /* = null_string */) { return _php_image_output_ctx(image, filename, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (void (*)())gdImageGifCtx); } #ifdef HAVE_GD_PNG bool HHVM_FUNCTION(imagepng, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */, int64_t filters /* = -1 */) { return _php_image_output_ctx(image, filename, quality, filters, PHP_GDIMG_TYPE_PNG, "PNG", (void (*)())gdImagePngCtxEx); } #endif #ifdef HAVE_LIBVPX bool HHVM_FUNCTION(imagewebp, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = 80 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (void (*)())gdImageWebpCtx); } #endif #ifdef HAVE_GD_JPG bool HHVM_FUNCTION(imagejpeg, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (void (*)())gdImageJpegCtx); } #endif bool HHVM_FUNCTION(imagewbmp, const Resource& image, const String& filename /* = null_string */, int64_t foreground /* = -1 */) { return _php_image_output_ctx(image, filename, foreground, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (void (*)())gdImageWBMPCtx); } bool HHVM_FUNCTION(imagegd, const Resource& image, const String& filename /* = null_string */) { return _php_image_output(image, filename, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (void (*)())gdImageGd); } bool HHVM_FUNCTION(imagegd2, const Resource& image, const String& filename /* = null_string */, int64_t chunk_size /* = 0 */, int64_t type /* = 0 */) { return _php_image_output(image, filename, chunk_size, type, PHP_GDIMG_TYPE_GD2, "GD2", (void (*)())gdImageGd2); } bool HHVM_FUNCTION(imagedestroy, const Resource& image) { auto img_res = cast<Image>(image); gdImagePtr im = img_res->get(); if (!im) return false; img_res->reset(); return true; } Variant HHVM_FUNCTION(imagecolorallocate, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocate(im, red, green, blue); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagepalettecopy, const Resource& dst, const Resource& src) { gdImagePtr dstim = cast<Image>(dst)->get(); gdImagePtr srcim = cast<Image>(src)->get(); if (!dstim || !srcim) return false; gdImagePaletteCopy(dstim, srcim); return true; } Variant HHVM_FUNCTION(imagecolorat, const Resource& image, int64_t x, int64_t y) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (gdImageTrueColor(im)) { if (im->tpixels && gdImageBoundsSafe(im, x, y)) { return gdImageTrueColorPixel(im, x, y); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } else { if (im->pixels && gdImageBoundsSafe(im, x, y)) { return (im->pixels[y][x]); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } } Variant HHVM_FUNCTION(imagecolorclosest, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosest(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorclosesthwb, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestHWB(im, red, green, blue); } bool HHVM_FUNCTION(imagecolordeallocate, const Resource& image, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; /* We can return right away for a truecolor image as deallocating colours is meaningless here */ if (gdImageTrueColor(im)) return true; if (color >= 0 && color < gdImageColorsTotal(im)) { gdImageColorDeallocate(im, color); return true; } else { raise_warning("Color index %" PRId64 " out of range", color); return false; } } Variant HHVM_FUNCTION(imagecolorresolve, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolve(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorexact, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExact(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorset, const Resource& image, int64_t index, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && index < gdImageColorsTotal(im)) { im->red[index] = red; im->green[index] = green; im->blue[index] = blue; return true; } else { return false; } } const StaticString s_red("red"), s_green("green"), s_blue("blue"), s_alpha("alpha"); Variant HHVM_FUNCTION(imagecolorsforindex, const Resource& image, int64_t index) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && (gdImageTrueColor(im) || index < gdImageColorsTotal(im))) { return make_map_array( s_red, gdImageRed(im,index), s_green, gdImageGreen(im,index), s_blue, gdImageBlue(im,index), s_alpha, gdImageAlpha(im,index) ); } raise_warning("Color index %" PRId64 " out of range", index); return false; } bool HHVM_FUNCTION(imagegammacorrect, const Resource& image, double inputgamma, double outputgamma) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (inputgamma <= 0.0 || outputgamma <= 0.0) { raise_warning("Gamma values should be positive"); return false; } if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColor((int)((pow((pow((gdTrueColorGetRed(c)/255.0), inputgamma)),1.0/outputgamma)*255) + .5), (int)((pow((pow((gdTrueColorGetGreen(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5), (int)((pow((pow((gdTrueColorGetBlue(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5))); } } return true; } for (int i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->green[i] = (int)((pow((pow((im->green[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); } return true; } bool HHVM_FUNCTION(imagesetpixel, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetPixel(im, x, y, color); return true; } bool HHVM_FUNCTION(imageline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagedashedline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageDashedLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagerectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagefilledrectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagearc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, start, end, color); return true; } bool HHVM_FUNCTION(imageellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, 0, 360, color); return true; } bool HHVM_FUNCTION(imagefilltoborder, const Resource& image, int64_t x, int64_t y, int64_t border, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFillToBorder(im, x, y, border, color); return true; } bool HHVM_FUNCTION(imagefill, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFill(im, x, y, color); return true; } Variant HHVM_FUNCTION(imagecolorstotal, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return (gdImageColorsTotal(im)); } Variant HHVM_FUNCTION(imagecolortransparent, const Resource& image, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (color != -1) { // has color argument gdImageColorTransparent(im, color); } return gdImageGetTransparent(im); } TypedValue HHVM_FUNCTION(imageinterlace, const Resource& image, TypedValue interlace /* = 0 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return make_tv<KindOfBoolean>(false); if (!tvIsNull(interlace)) { // has interlace argument gdImageInterlace(im, tvAssertInt(interlace)); } return make_tv<KindOfInt64>(gdImageGetInterlaced(im)); } bool HHVM_FUNCTION(imagepolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 0); } bool HHVM_FUNCTION(imagefilledpolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 1); } int64_t HHVM_FUNCTION(imagefontwidth, int64_t font) { return php_imagefontsize(font, 0); } int64_t HHVM_FUNCTION(imagefontheight, int64_t font) { return php_imagefontsize(font, 1); } bool HHVM_FUNCTION(imagechar, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 0); } bool HHVM_FUNCTION(imagecharup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 1); } bool HHVM_FUNCTION(imagestring, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 2); } bool HHVM_FUNCTION(imagestringup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 3); } bool HHVM_FUNCTION(imagecopy, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopy(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h); return true; } bool HHVM_FUNCTION(imagecopymerge, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMerge(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopymergegray, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMergeGray(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopyresized, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; if (dst_w <= 0 || dst_h <= 0 || src_w <= 0 || src_h <= 0) { raise_warning("Invalid image dimensions"); return false; } gdImageCopyResized(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagesx, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSX(im); } Variant HHVM_FUNCTION(imagesy, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSY(im); } #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE Variant HHVM_FUNCTION(imageftbbox, double size, double angle, const String& font_file, const String& text, const Array& extrainfo /*=[] */) { return php_imagettftext_common(TTFTEXT_BBOX, 1, size, angle, font_file, text, extrainfo); } Variant HHVM_FUNCTION(imagefttext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t col, const String& font_file, const String& text, const Array& extrainfo) { return php_imagettftext_common(TTFTEXT_DRAW, 1, image, size, angle, x, y, col, font_file, text, extrainfo); } #endif #ifdef ENABLE_GD_TTF Variant HHVM_FUNCTION(imagettfbbox, double size, double angle, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_BBOX, 0, size, angle, fontfile, text); } Variant HHVM_FUNCTION(imagettftext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t color, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_DRAW, 0, image, size.toDouble(), angle.toDouble(), x, y, color, fontfile, text); } #endif bool HHVM_FUNCTION(image2wbmp, const Resource& image, const String& filename /* = null_string */, int64_t threshold /* = -1 */) { return _php_image_output(image, filename, threshold, -1, PHP_GDIMG_CONVERT_WBM, "WBMP", (void (*)())_php_image_bw_convert); } bool HHVM_FUNCTION(jpeg2wbmp, const String& jpegname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(jpegname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_JPG); } bool HHVM_FUNCTION(png2wbmp, const String& pngname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(pngname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_PNG); } bool HHVM_FUNCTION(imagefilter, const Resource& res, int64_t filtertype, const Variant& arg1 /*=0*/, const Variant& arg2 /*=0*/, const Variant& arg3 /*=0*/, const Variant& arg4 /*=0*/) { gdImagePtr im = get_valid_image_resource(res); if (!im) return false; /* Exists purely to mirror PHP5's invalid arg logic for this function */ #define IMFILT_TYPECHK(n) \ if (!arg##n.isBoolean() && !arg##n.isNumeric(true)) { \ raise_warning("imagefilter() expected boolean/numeric for argument %d", \ (n+2)); \ return false; \ } IMFILT_TYPECHK(1) IMFILT_TYPECHK(2) IMFILT_TYPECHK(3) IMFILT_TYPECHK(4) #undef IMFILT_TYPECHECK using image_filter = bool (*)(gdImagePtr, int, int, int, int); image_filter filters[] = { php_image_filter_negate, php_image_filter_grayscale, php_image_filter_brightness, php_image_filter_contrast, php_image_filter_colorize, php_image_filter_edgedetect, php_image_filter_emboss, php_image_filter_gaussian_blur, php_image_filter_selective_blur, php_image_filter_mean_removal, php_image_filter_smooth, php_image_filter_pixelate, }; auto const num_filters = sizeof(filters) / sizeof(image_filter); if (filtertype >= 0 && filtertype < num_filters) { return filters[filtertype](im, arg1.toInt64(), arg2.toInt64(), arg3.toInt64(), arg4.toInt64()); } return false; } bool HHVM_FUNCTION(imageflip, const Resource& image, int64_t mode /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (mode == -1) mode = GD_FLIP_HORINZONTAL; switch (mode) { case GD_FLIP_VERTICAL: gdImageFlipVertical(im); break; case GD_FLIP_HORINZONTAL: gdImageFlipHorizontal(im); break; case GD_FLIP_BOTH: gdImageFlipBoth(im); break; default: raise_warning("imageflip(): Unknown flip mode"); return false; } return true; } // gdImageConvolution does not exist in our libgd.a, copied from // php's libgd/gd.c /* Filters function added on 2003/12 * by Pierre-Alain Joye (pajoye@pearfr.org) **/ static int hphp_gdImageConvolution(gdImagePtr src, float filter[3][3], float filter_div, float offset) { int x, y, i, j, new_a; float new_r, new_g, new_b; int new_pxl, pxl=0; gdImagePtr srcback; if (src==nullptr) { return 0; } /* We need the orinal image with each safe neoghb. pixel */ srcback = gdImageCreateTrueColor (src->sx, src->sy); gdImageCopy(srcback, src,0,0,0,0,src->sx,src->sy); if (srcback==nullptr) { return 0; } for ( y=0; y<src->sy; y++) { for(x=0; x<src->sx; x++) { new_r = new_g = new_b = 0; new_a = gdImageAlpha(srcback, pxl); for (j=0; j<3; j++) { int yv = std::min(std::max(y - 1 + j, 0), src->sy - 1); for (i=0; i<3; i++) { pxl = gdImageGetPixel(srcback, std::min(std::max(x - 1 + i, 0), src->sx - 1), yv); new_r += (float)gdImageRed(srcback, pxl) * filter[j][i]; new_g += (float)gdImageGreen(srcback, pxl) * filter[j][i]; new_b += (float)gdImageBlue(srcback, pxl) * filter[j][i]; } } new_r = (new_r/filter_div)+offset; new_g = (new_g/filter_div)+offset; new_b = (new_b/filter_div)+offset; new_r = (new_r > 255.0f)? 255.0f : ((new_r < 0.0f)? 0.0f:new_r); new_g = (new_g > 255.0f)? 255.0f : ((new_g < 0.0f)? 0.0f:new_g); new_b = (new_b > 255.0f)? 255.0f : ((new_b < 0.0f)? 0.0f:new_b); new_pxl = gdImageColorAllocateAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); if (new_pxl == -1) { new_pxl = gdImageColorClosestAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); } gdImageSetPixel (src, x, y, new_pxl); } } gdImageDestroy(srcback); return 1; } bool HHVM_FUNCTION(imageconvolution, const Resource& image, const Array& matrix, double div, double offset) { gdImagePtr im_src = cast<Image>(image)->get(); if (!im_src) return false; int nelem = matrix.size(); int i, j; float mtx[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; Variant v; Array row; if (nelem != 3) { raise_warning("You must have 3x3 array"); return false; } for (i=0; i<3; i++) { if (matrix.exists(i) && (v = matrix[i]).isArray()) { if ((row = v.toArray()).size() != 3) { raise_warning("You must have 3x3 array"); return false; } for (j=0; j<3; j++) { if (row.exists(j)) { mtx[i][j] = row[j].toDouble(); } else { raise_warning("You must have a 3x3 matrix"); return false; } } } } if (hphp_gdImageConvolution(im_src, mtx, div, offset)) { return true; } else { return false; } } bool HHVM_FUNCTION(imageantialias, const Resource& image, bool on) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; SetAntiAliased(im, on); return true; } Variant HHVM_FUNCTION(imagescale, const Resource& image, int64_t newwidth, int64_t newheight /* =-1 */, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imscaled = nullptr; gdInterpolationMethod old_method; if (method == -1) method = GD_BILINEAR_FIXED; if (newheight < 0) { /* preserve ratio */ long src_x, src_y; src_x = gdImageSX(im); src_y = gdImageSY(im); if (src_x) { newheight = newwidth * src_y / src_x; } } if (newheight <= 0 || newheight > INT_MAX || newwidth <= 0 || newwidth > INT_MAX) { return false; } old_method = im->interpolation_id; if (gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method)) { imscaled = gdImageScale(im, newwidth, newheight); } gdImageSetInterpolationMethod(im, old_method); if (imscaled == nullptr) { return false; } return Variant(req::make<Image>(imscaled)); } namespace { // PHP extension STANDARD: iptc.c inline int php_iptc_put1(req::ptr<File> /*file*/, int spool, unsigned char c, unsigned char** spoolbuf) { if (spool > 0) { g_context->write((const char *)&c, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_get1(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; char cc; c = file->getc(); if (c == EOF) return EOF; if (spool > 0) { cc = c; g_context->write((const char *)&cc, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_read_remaining(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { while (php_iptc_get1(file, spool, spoolbuf) != EOF) continue; return M_EOI; } int php_iptc_skip_variable(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { unsigned int length; int c1, c2; if ((c1 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; if ((c2 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) { if (php_iptc_get1(file, spool, spoolbuf) == EOF) return M_EOI; } return 0; } int php_iptc_next_marker(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; /* skip unimportant stuff */ c = php_iptc_get1(file, spool, spoolbuf); if (c == EOF) return M_EOI; while (c != 0xff) { if ((c = php_iptc_get1(file, spool, spoolbuf)) == EOF) { return M_EOI; /* we hit EOF */ } } /* get marker byte, swallowing possible padding */ do { c = php_iptc_get1(file, 0, 0); if (c == EOF) return M_EOI; /* we hit EOF */ else if (c == 0xff) php_iptc_put1(file, spool, (unsigned char)c, spoolbuf); } while (c == 0xff); return (unsigned int) c; } } const StaticString s_size("size"); Variant HHVM_FUNCTION(iptcembed, const String& iptcdata, const String& jpeg_file_name, int64_t spool /* = 0 */) { char psheader[] = "\xFF\xED\0\0Photoshop 3.0\08BIM\x04\x04\0\0\0"; static_assert(sizeof(psheader) == 28, "psheader must be 28 bytes"); unsigned int iptcdata_len = iptcdata.length(); unsigned int marker, inx; unsigned char *spoolbuf = nullptr, *poi = nullptr; bool done = false; bool written = false; auto file = File::Open(jpeg_file_name, "rb"); if (!file) { raise_warning("failed to open file: %s", jpeg_file_name.c_str()); return false; } if (spool < 2) { auto stat = HHVM_FN(fstat)(Resource(file)); // TODO(t7561579) until we can properly handle non-file streams here, don't // pretend we can and crash. if (!stat.isArray()) { raise_warning("unable to stat input"); return false; } auto& stat_arr = stat.toCArrRef(); auto st_size = stat_arr[s_size].toInt64(); if (st_size < 0) { raise_warning("unsupported stream type"); return false; } if (iptcdata_len >= (INT64_MAX - sizeof(psheader) - st_size - 1024 - 1)) { raise_warning("iptcdata too long"); return false; } auto malloc_size = iptcdata_len + sizeof(psheader) + st_size + 1024 + 1; poi = spoolbuf = (unsigned char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(poi, malloc_size, false); memset(poi, 0, malloc_size); } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xFF) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xD8) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } while (!done) { marker = php_iptc_next_marker(file, spool, poi?&poi:0); if (marker == M_EOI) { /* EOF */ break; } else if (marker != M_APP13) { php_iptc_put1(file, spool, (unsigned char)marker, poi?&poi:0); } switch (marker) { case M_APP13: /* we are going to write a new APP13 marker, so don't output the old one */ php_iptc_skip_variable(file, 0, 0); php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; case M_APP0: /* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */ case M_APP1: if (written) { /* don't try to write the data twice */ break; } written = true; php_iptc_skip_variable(file, spool, poi?&poi:0); if (iptcdata_len & 1) { iptcdata_len++; /* make the length even */ } psheader[2] = (iptcdata_len + sizeof(psheader)) >> 8; psheader[3] = (iptcdata_len + sizeof(psheader)) & 0xff; for (inx = 0; inx < sizeof(psheader); inx++) { php_iptc_put1(file, spool, psheader[inx], poi ? &poi : 0); } php_iptc_put1(file, spool, (unsigned char)(iptcdata_len>>8), poi?&poi:0); php_iptc_put1(file, spool, (unsigned char)(iptcdata_len&0xff), poi?&poi:0); for (inx = 0; inx < iptcdata_len; inx++) { php_iptc_put1(file, spool, iptcdata.c_str()[inx], poi?&poi:0); } break; case M_SOS: /* we hit data, no more marker-inserting can be done! */ php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; default: php_iptc_skip_variable(file, spool, poi?&poi:0); break; } } file->close(); if (spool < 2) { return String((char *)spoolbuf, poi - spoolbuf, AttachString); } return true; } Variant HHVM_FUNCTION(iptcparse, const String& iptcblock) { unsigned int inx = 0, len, tagsfound = 0; unsigned char *buffer, recnum, dataset, key[16]; unsigned int str_len = iptcblock.length(); Array ret; buffer = (unsigned char *)iptcblock.c_str(); while (inx < str_len) { /* find 1st tag */ if ((buffer[inx] == 0x1c) && ((buffer[inx+1] == 0x01) || (buffer[inx+1] == 0x02))) { break; } else { inx++; } } while (inx < str_len) { if (buffer[ inx++ ] != 0x1c) { /* we ran against some data which does not conform to IPTC - stop parsing! */ break; } if ((inx + 4) >= str_len) break; dataset = buffer[inx++]; recnum = buffer[inx++]; if (buffer[inx] & (unsigned char) 0x80) { /* long tag */ if (inx + 6 >= str_len) break; len = (((long)buffer[inx + 2]) << 24) + (((long)buffer[inx + 3]) << 16) + (((long)buffer[inx + 4]) << 8) + (((long)buffer[inx + 5])); inx += 6; } else { /* short tag */ len = (((unsigned short)buffer[inx])<<8) | (unsigned short)buffer[inx+1]; inx += 2; } snprintf((char *)key, sizeof(key), "%d#%03d", (unsigned int)dataset, (unsigned int)recnum); if ((len > str_len) || (inx + len) > str_len) { break; } String skey((const char *)key, CopyString); if (!ret.exists(skey)) { ret.set(skey, Array::CreateVArray()); } auto const lval = ret.lvalAt(skey); forceToArray(lval).append( String((const char *)(buffer+inx), len, CopyString)); inx += len; tagsfound++; } if (!tagsfound) { return false; } return ret; } // PHP extension exif.c #define NUM_FORMATS 13 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 #define TAG_FMT_IFD 13 /* Describes tag values */ #define TAG_GPS_VERSION_ID 0x0000 #define TAG_GPS_LATITUDE_REF 0x0001 #define TAG_GPS_LATITUDE 0x0002 #define TAG_GPS_LONGITUDE_REF 0x0003 #define TAG_GPS_LONGITUDE 0x0004 #define TAG_GPS_ALTITUDE_REF 0x0005 #define TAG_GPS_ALTITUDE 0x0006 #define TAG_GPS_TIME_STAMP 0x0007 #define TAG_GPS_SATELLITES 0x0008 #define TAG_GPS_STATUS 0x0009 #define TAG_GPS_MEASURE_MODE 0x000A #define TAG_GPS_DOP 0x000B #define TAG_GPS_SPEED_REF 0x000C #define TAG_GPS_SPEED 0x000D #define TAG_GPS_TRACK_REF 0x000E #define TAG_GPS_TRACK 0x000F #define TAG_GPS_IMG_DIRECTION_REF 0x0010 #define TAG_GPS_IMG_DIRECTION 0x0011 #define TAG_GPS_MAP_DATUM 0x0012 #define TAG_GPS_DEST_LATITUDE_REF 0x0013 #define TAG_GPS_DEST_LATITUDE 0x0014 #define TAG_GPS_DEST_LONGITUDE_REF 0x0015 #define TAG_GPS_DEST_LONGITUDE 0x0016 #define TAG_GPS_DEST_BEARING_REF 0x0017 #define TAG_GPS_DEST_BEARING 0x0018 #define TAG_GPS_DEST_DISTANCE_REF 0x0019 #define TAG_GPS_DEST_DISTANCE 0x001A #define TAG_GPS_PROCESSING_METHOD 0x001B #define TAG_GPS_AREA_INFORMATION 0x001C #define TAG_GPS_DATE_STAMP 0x001D #define TAG_GPS_DIFFERENTIAL 0x001E #define TAG_TIFF_COMMENT 0x00FE /* SHOUDLNT HAPPEN */ #define TAG_NEW_SUBFILE 0x00FE /* New version of subfile tag */ #define TAG_SUBFILE_TYPE 0x00FF /* Old version of subfile tag */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 #define TAG_BITS_PER_SAMPLE 0x0102 #define TAG_COMPRESSION 0x0103 #define TAG_PHOTOMETRIC_INTERPRETATION 0x0106 #define TAG_TRESHHOLDING 0x0107 #define TAG_CELL_WIDTH 0x0108 #define TAG_CELL_HEIGHT 0x0109 #define TAG_FILL_ORDER 0x010A #define TAG_DOCUMENT_NAME 0x010D #define TAG_IMAGE_DESCRIPTION 0x010E #define TAG_MAKE 0x010F #define TAG_MODEL 0x0110 #define TAG_STRIP_OFFSETS 0x0111 #define TAG_ORIENTATION 0x0112 #define TAG_SAMPLES_PER_PIXEL 0x0115 #define TAG_ROWS_PER_STRIP 0x0116 #define TAG_STRIP_BYTE_COUNTS 0x0117 #define TAG_MIN_SAMPPLE_VALUE 0x0118 #define TAG_MAX_SAMPLE_VALUE 0x0119 #define TAG_X_RESOLUTION 0x011A #define TAG_Y_RESOLUTION 0x011B #define TAG_PLANAR_CONFIGURATION 0x011C #define TAG_PAGE_NAME 0x011D #define TAG_X_POSITION 0x011E #define TAG_Y_POSITION 0x011F #define TAG_FREE_OFFSETS 0x0120 #define TAG_FREE_BYTE_COUNTS 0x0121 #define TAG_GRAY_RESPONSE_UNIT 0x0122 #define TAG_GRAY_RESPONSE_CURVE 0x0123 #define TAG_RESOLUTION_UNIT 0x0128 #define TAG_PAGE_NUMBER 0x0129 #define TAG_TRANSFER_FUNCTION 0x012D #define TAG_SOFTWARE 0x0131 #define TAG_DATETIME 0x0132 #define TAG_ARTIST 0x013B #define TAG_HOST_COMPUTER 0x013C #define TAG_PREDICTOR 0x013D #define TAG_WHITE_POINT 0x013E #define TAG_PRIMARY_CHROMATICITIES 0x013F #define TAG_COLOR_MAP 0x0140 #define TAG_HALFTONE_HINTS 0x0141 #define TAG_TILE_WIDTH 0x0142 #define TAG_TILE_LENGTH 0x0143 #define TAG_TILE_OFFSETS 0x0144 #define TAG_TILE_BYTE_COUNTS 0x0145 #define TAG_SUB_IFD 0x014A #define TAG_INK_SETMPUTER 0x014C #define TAG_INK_NAMES 0x014D #define TAG_NUMBER_OF_INKS 0x014E #define TAG_DOT_RANGE 0x0150 #define TAG_TARGET_PRINTER 0x0151 #define TAG_EXTRA_SAMPLE 0x0152 #define TAG_SAMPLE_FORMAT 0x0153 #define TAG_S_MIN_SAMPLE_VALUE 0x0154 #define TAG_S_MAX_SAMPLE_VALUE 0x0155 #define TAG_TRANSFER_RANGE 0x0156 #define TAG_JPEG_TABLES 0x015B #define TAG_JPEG_PROC 0x0200 #define TAG_JPEG_INTERCHANGE_FORMAT 0x0201 #define TAG_JPEG_INTERCHANGE_FORMAT_LEN 0x0202 #define TAG_JPEG_RESTART_INTERVAL 0x0203 #define TAG_JPEG_LOSSLESS_PREDICTOR 0x0205 #define TAG_JPEG_POINT_TRANSFORMS 0x0206 #define TAG_JPEG_Q_TABLES 0x0207 #define TAG_JPEG_DC_TABLES 0x0208 #define TAG_JPEG_AC_TABLES 0x0209 #define TAG_YCC_COEFFICIENTS 0x0211 #define TAG_YCC_SUB_SAMPLING 0x0212 #define TAG_YCC_POSITIONING 0x0213 #define TAG_REFERENCE_BLACK_WHITE 0x0214 /* 0x0301 - 0x0302 */ /* 0x0320 */ /* 0x0343 */ /* 0x5001 - 0x501B */ /* 0x5021 - 0x503B */ /* 0x5090 - 0x5091 */ /* 0x5100 - 0x5101 */ /* 0x5110 - 0x5113 */ /* 0x80E3 - 0x80E6 */ /* 0x828d - 0x828F */ #define TAG_COPYRIGHT 0x8298 #define TAG_EXPOSURETIME 0x829A #define TAG_FNUMBER 0x829D #define TAG_EXIF_IFD_POINTER 0x8769 #define TAG_ICC_PROFILE 0x8773 #define TAG_EXPOSURE_PROGRAM 0x8822 #define TAG_SPECTRAL_SENSITY 0x8824 #define TAG_GPS_IFD_POINTER 0x8825 #define TAG_ISOSPEED 0x8827 #define TAG_OPTOELECTRIC_CONVERSION_F 0x8828 /* 0x8829 - 0x882b */ #define TAG_EXIFVERSION 0x9000 #define TAG_DATE_TIME_ORIGINAL 0x9003 #define TAG_DATE_TIME_DIGITIZED 0x9004 #define TAG_COMPONENT_CONFIG 0x9101 #define TAG_COMPRESSED_BITS_PER_PIXEL 0x9102 #define TAG_SHUTTERSPEED 0x9201 #define TAG_APERTURE 0x9202 #define TAG_BRIGHTNESS_VALUE 0x9203 #define TAG_EXPOSURE_BIAS_VALUE 0x9204 #define TAG_MAX_APERTURE 0x9205 #define TAG_SUBJECT_DISTANCE 0x9206 #define TAG_METRIC_MODULE 0x9207 #define TAG_LIGHT_SOURCE 0x9208 #define TAG_FLASH 0x9209 #define TAG_FOCAL_LENGTH 0x920A /* 0x920B - 0x920D */ /* 0x9211 - 0x9216 */ #define TAG_SUBJECT_AREA 0x9214 #define TAG_MAKER_NOTE 0x927C #define TAG_USERCOMMENT 0x9286 #define TAG_SUB_SEC_TIME 0x9290 #define TAG_SUB_SEC_TIME_ORIGINAL 0x9291 #define TAG_SUB_SEC_TIME_DIGITIZED 0x9292 /* 0x923F */ /* 0x935C */ #define TAG_XP_TITLE 0x9C9B #define TAG_XP_COMMENTS 0x9C9C #define TAG_XP_AUTHOR 0x9C9D #define TAG_XP_KEYWORDS 0x9C9E #define TAG_XP_SUBJECT 0x9C9F #define TAG_FLASH_PIX_VERSION 0xA000 #define TAG_COLOR_SPACE 0xA001 #define TAG_COMP_IMAGE_WIDTH 0xA002 /* compressed images only */ #define TAG_COMP_IMAGE_HEIGHT 0xA003 #define TAG_RELATED_SOUND_FILE 0xA004 #define TAG_INTEROP_IFD_POINTER 0xA005 /* IFD pointer */ #define TAG_FLASH_ENERGY 0xA20B #define TAG_SPATIAL_FREQUENCY_RESPONSE 0xA20C #define TAG_FOCALPLANE_X_RES 0xA20E #define TAG_FOCALPLANE_Y_RES 0xA20F #define TAG_FOCALPLANE_RESOLUTION_UNIT 0xA210 #define TAG_SUBJECT_LOCATION 0xA214 #define TAG_EXPOSURE_INDEX 0xA215 #define TAG_SENSING_METHOD 0xA217 #define TAG_FILE_SOURCE 0xA300 #define TAG_SCENE_TYPE 0xA301 #define TAG_CFA_PATTERN 0xA302 #define TAG_CUSTOM_RENDERED 0xA401 #define TAG_EXPOSURE_MODE 0xA402 #define TAG_WHITE_BALANCE 0xA403 #define TAG_DIGITAL_ZOOM_RATIO 0xA404 #define TAG_FOCAL_LENGTH_IN_35_MM_FILM 0xA405 #define TAG_SCENE_CAPTURE_TYPE 0xA406 #define TAG_GAIN_CONTROL 0xA407 #define TAG_CONTRAST 0xA408 #define TAG_SATURATION 0xA409 #define TAG_SHARPNESS 0xA40A #define TAG_DEVICE_SETTING_DESCRIPTION 0xA40B #define TAG_SUBJECT_DISTANCE_RANGE 0xA40C #define TAG_IMAGE_UNIQUE_ID 0xA420 /* Olympus specific tags */ #define TAG_OLYMPUS_SPECIALMODE 0x0200 #define TAG_OLYMPUS_JPEGQUAL 0x0201 #define TAG_OLYMPUS_MACRO 0x0202 #define TAG_OLYMPUS_DIGIZOOM 0x0204 #define TAG_OLYMPUS_SOFTWARERELEASE 0x0207 #define TAG_OLYMPUS_PICTINFO 0x0208 #define TAG_OLYMPUS_CAMERAID 0x0209 /* end Olympus specific tags */ /* Internal */ #define TAG_NONE -1 /* note that -1 <> 0xFFFF */ #define TAG_COMPUTED_VALUE -2 #define TAG_END_OF_LIST 0xFFFD /* Values for TAG_PHOTOMETRIC_INTERPRETATION */ #define PMI_BLACK_IS_ZERO 0 #define PMI_WHITE_IS_ZERO 1 #define PMI_RGB 2 #define PMI_PALETTE_COLOR 3 #define PMI_TRANSPARENCY_MASK 4 #define PMI_SEPARATED 5 #define PMI_YCBCR 6 #define PMI_CIELAB 8 typedef const struct { unsigned short Tag; char *Desc; } tag_info_type; typedef tag_info_type tag_info_array[]; typedef tag_info_type *tag_table_type; #define TAG_TABLE_END \ {((unsigned short)TAG_NONE), "No tag value"},\ {((unsigned short)TAG_COMPUTED_VALUE), "Computed value"},\ {TAG_END_OF_LIST, ""} /* Important for exif_get_tagname() IF value != "" function result is != false */ static const tag_info_array tag_table_IFD = { { 0x000B, "ACDComment"}, { 0x00FE, "NewSubFile"}, /* better name it 'ImageType' ? */ { 0x00FF, "SubFile"}, { 0x0100, "ImageWidth"}, { 0x0101, "ImageLength"}, { 0x0102, "BitsPerSample"}, { 0x0103, "Compression"}, { 0x0106, "PhotometricInterpretation"}, { 0x010A, "FillOrder"}, { 0x010D, "DocumentName"}, { 0x010E, "ImageDescription"}, { 0x010F, "Make"}, { 0x0110, "Model"}, { 0x0111, "StripOffsets"}, { 0x0112, "Orientation"}, { 0x0115, "SamplesPerPixel"}, { 0x0116, "RowsPerStrip"}, { 0x0117, "StripByteCounts"}, { 0x0118, "MinSampleValue"}, { 0x0119, "MaxSampleValue"}, { 0x011A, "XResolution"}, { 0x011B, "YResolution"}, { 0x011C, "PlanarConfiguration"}, { 0x011D, "PageName"}, { 0x011E, "XPosition"}, { 0x011F, "YPosition"}, { 0x0120, "FreeOffsets"}, { 0x0121, "FreeByteCounts"}, { 0x0122, "GrayResponseUnit"}, { 0x0123, "GrayResponseCurve"}, { 0x0124, "T4Options"}, { 0x0125, "T6Options"}, { 0x0128, "ResolutionUnit"}, { 0x0129, "PageNumber"}, { 0x012D, "TransferFunction"}, { 0x0131, "Software"}, { 0x0132, "DateTime"}, { 0x013B, "Artist"}, { 0x013C, "HostComputer"}, { 0x013D, "Predictor"}, { 0x013E, "WhitePoint"}, { 0x013F, "PrimaryChromaticities"}, { 0x0140, "ColorMap"}, { 0x0141, "HalfToneHints"}, { 0x0142, "TileWidth"}, { 0x0143, "TileLength"}, { 0x0144, "TileOffsets"}, { 0x0145, "TileByteCounts"}, { 0x014A, "SubIFD"}, { 0x014C, "InkSet"}, { 0x014D, "InkNames"}, { 0x014E, "NumberOfInks"}, { 0x0150, "DotRange"}, { 0x0151, "TargetPrinter"}, { 0x0152, "ExtraSample"}, { 0x0153, "SampleFormat"}, { 0x0154, "SMinSampleValue"}, { 0x0155, "SMaxSampleValue"}, { 0x0156, "TransferRange"}, { 0x0157, "ClipPath"}, { 0x0158, "XClipPathUnits"}, { 0x0159, "YClipPathUnits"}, { 0x015A, "Indexed"}, { 0x015B, "JPEGTables"}, { 0x015F, "OPIProxy"}, { 0x0200, "JPEGProc"}, { 0x0201, "JPEGInterchangeFormat"}, { 0x0202, "JPEGInterchangeFormatLength"}, { 0x0203, "JPEGRestartInterval"}, { 0x0205, "JPEGLosslessPredictors"}, { 0x0206, "JPEGPointTransforms"}, { 0x0207, "JPEGQTables"}, { 0x0208, "JPEGDCTables"}, { 0x0209, "JPEGACTables"}, { 0x0211, "YCbCrCoefficients"}, { 0x0212, "YCbCrSubSampling"}, { 0x0213, "YCbCrPositioning"}, { 0x0214, "ReferenceBlackWhite"}, { 0x02BC, "ExtensibleMetadataPlatform"}, /* XAP: Extensible Authoring Publishing, obsoleted by XMP: Extensible Metadata Platform */ { 0x0301, "Gamma"}, { 0x0302, "ICCProfileDescriptor"}, { 0x0303, "SRGBRenderingIntent"}, { 0x0320, "ImageTitle"}, { 0x5001, "ResolutionXUnit"}, { 0x5002, "ResolutionYUnit"}, { 0x5003, "ResolutionXLengthUnit"}, { 0x5004, "ResolutionYLengthUnit"}, { 0x5005, "PrintFlags"}, { 0x5006, "PrintFlagsVersion"}, { 0x5007, "PrintFlagsCrop"}, { 0x5008, "PrintFlagsBleedWidth"}, { 0x5009, "PrintFlagsBleedWidthScale"}, { 0x500A, "HalftoneLPI"}, { 0x500B, "HalftoneLPIUnit"}, { 0x500C, "HalftoneDegree"}, { 0x500D, "HalftoneShape"}, { 0x500E, "HalftoneMisc"}, { 0x500F, "HalftoneScreen"}, { 0x5010, "JPEGQuality"}, { 0x5011, "GridSize"}, { 0x5012, "ThumbnailFormat"}, { 0x5013, "ThumbnailWidth"}, { 0x5014, "ThumbnailHeight"}, { 0x5015, "ThumbnailColorDepth"}, { 0x5016, "ThumbnailPlanes"}, { 0x5017, "ThumbnailRawBytes"}, { 0x5018, "ThumbnailSize"}, { 0x5019, "ThumbnailCompressedSize"}, { 0x501A, "ColorTransferFunction"}, { 0x501B, "ThumbnailData"}, { 0x5020, "ThumbnailImageWidth"}, { 0x5021, "ThumbnailImageHeight"}, { 0x5022, "ThumbnailBitsPerSample"}, { 0x5023, "ThumbnailCompression"}, { 0x5024, "ThumbnailPhotometricInterp"}, { 0x5025, "ThumbnailImageDescription"}, { 0x5026, "ThumbnailEquipMake"}, { 0x5027, "ThumbnailEquipModel"}, { 0x5028, "ThumbnailStripOffsets"}, { 0x5029, "ThumbnailOrientation"}, { 0x502A, "ThumbnailSamplesPerPixel"}, { 0x502B, "ThumbnailRowsPerStrip"}, { 0x502C, "ThumbnailStripBytesCount"}, { 0x502D, "ThumbnailResolutionX"}, { 0x502E, "ThumbnailResolutionY"}, { 0x502F, "ThumbnailPlanarConfig"}, { 0x5030, "ThumbnailResolutionUnit"}, { 0x5031, "ThumbnailTransferFunction"}, { 0x5032, "ThumbnailSoftwareUsed"}, { 0x5033, "ThumbnailDateTime"}, { 0x5034, "ThumbnailArtist"}, { 0x5035, "ThumbnailWhitePoint"}, { 0x5036, "ThumbnailPrimaryChromaticities"}, { 0x5037, "ThumbnailYCbCrCoefficients"}, { 0x5038, "ThumbnailYCbCrSubsampling"}, { 0x5039, "ThumbnailYCbCrPositioning"}, { 0x503A, "ThumbnailRefBlackWhite"}, { 0x503B, "ThumbnailCopyRight"}, { 0x5090, "LuminanceTable"}, { 0x5091, "ChrominanceTable"}, { 0x5100, "FrameDelay"}, { 0x5101, "LoopCount"}, { 0x5110, "PixelUnit"}, { 0x5111, "PixelPerUnitX"}, { 0x5112, "PixelPerUnitY"}, { 0x5113, "PaletteHistogram"}, { 0x1000, "RelatedImageFileFormat"}, { 0x800D, "ImageID"}, { 0x80E3, "Matteing"}, /* obsoleted by ExtraSamples */ { 0x80E4, "DataType"}, /* obsoleted by SampleFormat */ { 0x80E5, "ImageDepth"}, { 0x80E6, "TileDepth"}, { 0x828D, "CFARepeatPatternDim"}, { 0x828E, "CFAPattern"}, { 0x828F, "BatteryLevel"}, { 0x8298, "Copyright"}, { 0x829A, "ExposureTime"}, { 0x829D, "FNumber"}, { 0x83BB, "IPTC/NAA"}, { 0x84E3, "IT8RasterPadding"}, { 0x84E5, "IT8ColorTable"}, { 0x8649, "ImageResourceInformation"}, /* PhotoShop */ { 0x8769, "Exif_IFD_Pointer"}, { 0x8773, "ICC_Profile"}, { 0x8822, "ExposureProgram"}, { 0x8824, "SpectralSensity"}, { 0x8828, "OECF"}, { 0x8825, "GPS_IFD_Pointer"}, { 0x8827, "ISOSpeedRatings"}, { 0x8828, "OECF"}, { 0x9000, "ExifVersion"}, { 0x9003, "DateTimeOriginal"}, { 0x9004, "DateTimeDigitized"}, { 0x9101, "ComponentsConfiguration"}, { 0x9102, "CompressedBitsPerPixel"}, { 0x9201, "ShutterSpeedValue"}, { 0x9202, "ApertureValue"}, { 0x9203, "BrightnessValue"}, { 0x9204, "ExposureBiasValue"}, { 0x9205, "MaxApertureValue"}, { 0x9206, "SubjectDistance"}, { 0x9207, "MeteringMode"}, { 0x9208, "LightSource"}, { 0x9209, "Flash"}, { 0x920A, "FocalLength"}, { 0x920B, "FlashEnergy"}, /* 0xA20B in JPEG */ { 0x920C, "SpatialFrequencyResponse"}, /* 0xA20C - - */ { 0x920D, "Noise"}, { 0x920E, "FocalPlaneXResolution"}, /* 0xA20E - - */ { 0x920F, "FocalPlaneYResolution"}, /* 0xA20F - - */ { 0x9210, "FocalPlaneResolutionUnit"}, /* 0xA210 - - */ { 0x9211, "ImageNumber"}, { 0x9212, "SecurityClassification"}, { 0x9213, "ImageHistory"}, { 0x9214, "SubjectLocation"}, /* 0xA214 - - */ { 0x9215, "ExposureIndex"}, /* 0xA215 - - */ { 0x9216, "TIFF/EPStandardID"}, { 0x9217, "SensingMethod"}, /* 0xA217 - - */ { 0x923F, "StoNits"}, { 0x927C, "MakerNote"}, { 0x9286, "UserComment"}, { 0x9290, "SubSecTime"}, { 0x9291, "SubSecTimeOriginal"}, { 0x9292, "SubSecTimeDigitized"}, { 0x935C, "ImageSourceData"}, /* "Adobe Photoshop Document Data Block": 8BIM... */ { 0x9c9b, "Title" }, /* Win XP specific, Unicode */ { 0x9c9c, "Comments" }, /* Win XP specific, Unicode */ { 0x9c9d, "Author" }, /* Win XP specific, Unicode */ { 0x9c9e, "Keywords" }, /* Win XP specific, Unicode */ { 0x9c9f, "Subject" }, /* Win XP specific, Unicode, not to be confused with SubjectDistance and SubjectLocation */ { 0xA000, "FlashPixVersion"}, { 0xA001, "ColorSpace"}, { 0xA002, "ExifImageWidth"}, { 0xA003, "ExifImageLength"}, { 0xA004, "RelatedSoundFile"}, { 0xA005, "InteroperabilityOffset"}, { 0xA20B, "FlashEnergy"}, /* 0x920B in TIFF/EP */ { 0xA20C, "SpatialFrequencyResponse"}, /* 0x920C - - */ { 0xA20D, "Noise"}, { 0xA20E, "FocalPlaneXResolution"}, /* 0x920E - - */ { 0xA20F, "FocalPlaneYResolution"}, /* 0x920F - - */ { 0xA210, "FocalPlaneResolutionUnit"}, /* 0x9210 - - */ { 0xA211, "ImageNumber"}, { 0xA212, "SecurityClassification"}, { 0xA213, "ImageHistory"}, { 0xA214, "SubjectLocation"}, /* 0x9214 - - */ { 0xA215, "ExposureIndex"}, /* 0x9215 - - */ { 0xA216, "TIFF/EPStandardID"}, { 0xA217, "SensingMethod"}, /* 0x9217 - - */ { 0xA300, "FileSource"}, { 0xA301, "SceneType"}, { 0xA302, "CFAPattern"}, { 0xA401, "CustomRendered"}, { 0xA402, "ExposureMode"}, { 0xA403, "WhiteBalance"}, { 0xA404, "DigitalZoomRatio"}, { 0xA405, "FocalLengthIn35mmFilm"}, { 0xA406, "SceneCaptureType"}, { 0xA407, "GainControl"}, { 0xA408, "Contrast"}, { 0xA409, "Saturation"}, { 0xA40A, "Sharpness"}, { 0xA40B, "DeviceSettingDescription"}, { 0xA40C, "SubjectDistanceRange"}, { 0xA420, "ImageUniqueID"}, TAG_TABLE_END }; static const tag_info_array tag_table_GPS = { { 0x0000, "GPSVersion"}, { 0x0001, "GPSLatitudeRef"}, { 0x0002, "GPSLatitude"}, { 0x0003, "GPSLongitudeRef"}, { 0x0004, "GPSLongitude"}, { 0x0005, "GPSAltitudeRef"}, { 0x0006, "GPSAltitude"}, { 0x0007, "GPSTimeStamp"}, { 0x0008, "GPSSatellites"}, { 0x0009, "GPSStatus"}, { 0x000A, "GPSMeasureMode"}, { 0x000B, "GPSDOP"}, { 0x000C, "GPSSpeedRef"}, { 0x000D, "GPSSpeed"}, { 0x000E, "GPSTrackRef"}, { 0x000F, "GPSTrack"}, { 0x0010, "GPSImgDirectionRef"}, { 0x0011, "GPSImgDirection"}, { 0x0012, "GPSMapDatum"}, { 0x0013, "GPSDestLatitudeRef"}, { 0x0014, "GPSDestLatitude"}, { 0x0015, "GPSDestLongitudeRef"}, { 0x0016, "GPSDestLongitude"}, { 0x0017, "GPSDestBearingRef"}, { 0x0018, "GPSDestBearing"}, { 0x0019, "GPSDestDistanceRef"}, { 0x001A, "GPSDestDistance"}, { 0x001B, "GPSProcessingMode"}, { 0x001C, "GPSAreaInformation"}, { 0x001D, "GPSDateStamp"}, { 0x001E, "GPSDifferential"}, TAG_TABLE_END }; static const tag_info_array tag_table_IOP = { { 0x0001, "InterOperabilityIndex"}, /* should be 'R98' or 'THM' */ { 0x0002, "InterOperabilityVersion"}, { 0x1000, "RelatedFileFormat"}, { 0x1001, "RelatedImageWidth"}, { 0x1002, "RelatedImageHeight"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CANON = { { 0x0001, "ModeArray"}, /* guess */ { 0x0004, "ImageInfo"}, /* guess */ { 0x0006, "ImageType"}, { 0x0007, "FirmwareVersion"}, { 0x0008, "ImageNumber"}, { 0x0009, "OwnerName"}, { 0x000C, "Camera"}, { 0x000F, "CustomFunctions"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CASIO = { { 0x0001, "RecordingMode"}, { 0x0002, "Quality"}, { 0x0003, "FocusingMode"}, { 0x0004, "FlashMode"}, { 0x0005, "FlashIntensity"}, { 0x0006, "ObjectDistance"}, { 0x0007, "WhiteBalance"}, { 0x000A, "DigitalZoom"}, { 0x000B, "Sharpness"}, { 0x000C, "Contrast"}, { 0x000D, "Saturation"}, { 0x0014, "CCDSensitivity"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_FUJI = { { 0x0000, "Version"}, { 0x1000, "Quality"}, { 0x1001, "Sharpness"}, { 0x1002, "WhiteBalance"}, { 0x1003, "Color"}, { 0x1004, "Tone"}, { 0x1010, "FlashMode"}, { 0x1011, "FlashStrength"}, { 0x1020, "Macro"}, { 0x1021, "FocusMode"}, { 0x1030, "SlowSync"}, { 0x1031, "PictureMode"}, { 0x1100, "ContTake"}, { 0x1300, "BlurWarning"}, { 0x1301, "FocusWarning"}, { 0x1302, "AEWarning "}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON = { { 0x0003, "Quality"}, { 0x0004, "ColorMode"}, { 0x0005, "ImageAdjustment"}, { 0x0006, "CCDSensitivity"}, { 0x0007, "WhiteBalance"}, { 0x0008, "Focus"}, { 0x000a, "DigitalZoom"}, { 0x000b, "Converter"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON_990 = { { 0x0001, "Version"}, { 0x0002, "ISOSetting"}, { 0x0003, "ColorMode"}, { 0x0004, "Quality"}, { 0x0005, "WhiteBalance"}, { 0x0006, "ImageSharpening"}, { 0x0007, "FocusMode"}, { 0x0008, "FlashSetting"}, { 0x000F, "ISOSelection"}, { 0x0080, "ImageAdjustment"}, { 0x0082, "AuxiliaryLens"}, { 0x0085, "ManualFocusDistance"}, { 0x0086, "DigitalZoom"}, { 0x0088, "AFFocusPosition"}, { 0x0010, "DataDump"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_OLYMPUS = { { 0x0200, "SpecialMode"}, { 0x0201, "JPEGQuality"}, { 0x0202, "Macro"}, { 0x0204, "DigitalZoom"}, { 0x0207, "SoftwareRelease"}, { 0x0208, "PictureInfo"}, { 0x0209, "CameraId"}, { 0x0F00, "DataDump"}, TAG_TABLE_END }; typedef enum mn_byte_order_t { MN_ORDER_INTEL = 0, MN_ORDER_MOTOROLA = 1, MN_ORDER_NORMAL } mn_byte_order_t; typedef enum mn_offset_mode_t { MN_OFFSET_NORMAL, MN_OFFSET_MAKER, MN_OFFSET_GUESS } mn_offset_mode_t; typedef struct { tag_table_type tag_table; char *make; char *model; char *id_string; int id_string_len; int offset; mn_byte_order_t byte_order; mn_offset_mode_t offset_mode; } maker_note_type; static const maker_note_type maker_note_array[] = { { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_INTEL, MN_OFFSET_NORMAL}, /* { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL},*/ { tag_table_VND_CASIO, "CASIO", nullptr, nullptr, 0, 0, MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL}, { tag_table_VND_FUJI, "FUJIFILM", nullptr, "FUJIFILM\x0C\x00\x00\x00", 12, 12, MN_ORDER_INTEL, MN_OFFSET_MAKER}, { tag_table_VND_NIKON, "NIKON", nullptr, "Nikon\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_NIKON_990, "NIKON", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_OLYMPUS, "OLYMPUS OPTICAL CO.,LTD", nullptr, "OLYMP\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, }; /* Get headername for tag_num or nullptr if not defined */ static char * exif_get_tagname(int tag_num, char *ret, int len, tag_table_type tag_table) { int i, t; char tmp[32]; for (i = 0; (t = tag_table[i].Tag) != TAG_END_OF_LIST; i++) { if (t == tag_num) { if (ret && len) { string_copy(ret, tag_table[i].Desc, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return tag_table[i].Desc; } } if (ret && len) { snprintf(tmp, sizeof(tmp), "UndefinedTag:0x%04X", tag_num); string_copy(ret, tmp, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return ""; } #define MAX_IFD_NESTING_LEVEL 100 #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif typedef struct { int num; int den; } signed_rational; typedef struct { unsigned int num; unsigned int den; } unsigned_rational; typedef union _image_info_value { char *s; unsigned u; int i; float f; double d; signed_rational sr; unsigned_rational ur; union _image_info_value *list; } image_info_value; typedef struct { WORD tag; WORD format; DWORD length; DWORD dummy; /* value ptr of tiff directory entry */ char *name; image_info_value value; } image_info_data; typedef struct { int count; image_info_data *list; } image_info_list; #define SECTION_FILE 0 #define SECTION_COMPUTED 1 #define SECTION_ANY_TAG 2 #define SECTION_IFD0 3 #define SECTION_THUMBNAIL 4 #define SECTION_COMMENT 5 #define SECTION_APP0 6 #define SECTION_EXIF 7 #define SECTION_FPIX 8 #define SECTION_GPS 9 #define SECTION_INTEROP 10 #define SECTION_APP12 11 #define SECTION_WINXP 12 #define SECTION_MAKERNOTE 13 #define SECTION_COUNT 14 #define FOUND_FILE (1<<SECTION_FILE) #define FOUND_COMPUTED (1<<SECTION_COMPUTED) #define FOUND_ANY_TAG (1<<SECTION_ANY_TAG) #define FOUND_IFD0 (1<<SECTION_IFD0) #define FOUND_THUMBNAIL (1<<SECTION_THUMBNAIL) #define FOUND_COMMENT (1<<SECTION_COMMENT) #define FOUND_APP0 (1<<SECTION_APP0) #define FOUND_EXIF (1<<SECTION_EXIF) #define FOUND_FPIX (1<<SECTION_FPIX) #define FOUND_GPS (1<<SECTION_GPS) #define FOUND_INTEROP (1<<SECTION_INTEROP) #define FOUND_APP12 (1<<SECTION_APP12) #define FOUND_WINXP (1<<SECTION_WINXP) #define FOUND_MAKERNOTE (1<<SECTION_MAKERNOTE) const StaticString s_FILE("FILE"), s_COMPUTED("COMPUTED"), s_ANY_TAG("ANY_TAG"), s_IFD0("IFD0"), s_THUMBNAIL("THUMBNAIL"), s_COMMENT("COMMENT"), s_APP0("APP0"), s_EXIF("EXIF"), s_FPIX("FPIX"), s_GPS("GPS"), s_INTEROP("INTEROP"), s_APP12("APP12"), s_WINXP("WINXP"), s_MAKERNOTE("MAKERNOTE"); static String exif_get_sectionname(int section) { switch(section) { case SECTION_FILE: return s_FILE; case SECTION_COMPUTED: return s_COMPUTED; case SECTION_ANY_TAG: return s_ANY_TAG; case SECTION_IFD0: return s_IFD0; case SECTION_THUMBNAIL: return s_THUMBNAIL; case SECTION_COMMENT: return s_COMMENT; case SECTION_APP0: return s_APP0; case SECTION_EXIF: return s_EXIF; case SECTION_FPIX: return s_FPIX; case SECTION_GPS: return s_GPS; case SECTION_INTEROP: return s_INTEROP; case SECTION_APP12: return s_APP12; case SECTION_WINXP: return s_WINXP; case SECTION_MAKERNOTE: return s_MAKERNOTE; } return empty_string(); } static tag_table_type exif_get_tag_table(int section) { switch(section) { case SECTION_FILE: return &tag_table_IFD[0]; case SECTION_COMPUTED: return &tag_table_IFD[0]; case SECTION_ANY_TAG: return &tag_table_IFD[0]; case SECTION_IFD0: return &tag_table_IFD[0]; case SECTION_THUMBNAIL: return &tag_table_IFD[0]; case SECTION_COMMENT: return &tag_table_IFD[0]; case SECTION_APP0: return &tag_table_IFD[0]; case SECTION_EXIF: return &tag_table_IFD[0]; case SECTION_FPIX: return &tag_table_IFD[0]; case SECTION_GPS: return &tag_table_GPS[0]; case SECTION_INTEROP: return &tag_table_IOP[0]; case SECTION_APP12: return &tag_table_IFD[0]; case SECTION_WINXP: return &tag_table_IFD[0]; } return &tag_table_IFD[0]; } /* Return list of sectionnames specified by sectionlist. Return value must be freed */ static char *exif_get_sectionlist(int sectionlist) { int i, len, ml = 0; char *sections; for(i=0; i<SECTION_COUNT; i++) { ml += exif_get_sectionname(i).size() + 2; } sections = (char *)IM_MALLOC(ml + 1); CHECK_ALLOC_R(sections, ml + 1, nullptr); sections[0] = '\0'; len = 0; for(i=0; i<SECTION_COUNT; i++) { if (sectionlist&(1<<i)) { snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i).c_str()); len = strlen(sections); } } if (len>2) { sections[len-2] = '\0'; } return sections; } /* This structure stores Exif header image elements in a simple manner Used to store camera data as extracted from the various ways that it can be stored in a nexif header */ typedef struct { int type; size_t size; unsigned char *data; } file_section; typedef struct { int count; file_section *list; } file_section_list; typedef struct { image_filetype filetype; size_t width, height; size_t size; size_t offset; char *data; } thumbnail_data; typedef struct { char *value; size_t size; int tag; } xp_field_type; typedef struct { int count; xp_field_type *list; } xp_field_list; /* This structure is used to store a section of a Jpeg file. */ typedef struct { req::ptr<File> infile; String FileName; time_t FileDateTime; size_t FileSize; image_filetype FileType; int Height, Width; int IsColor; char *make; char *model; float ApertureFNumber; float ExposureTime; double FocalplaneUnits; float CCDWidth; double FocalplaneXRes; size_t ExifImageWidth; float FocalLength; float Distance; int motorola_intel; /* 1 Motorola; 0 Intel */ char *UserComment; int UserCommentLength; char *UserCommentEncoding; char *encode_unicode; char *decode_unicode_be; char *decode_unicode_le; char *encode_jis; char *decode_jis_be; char *decode_jis_le; /* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */ char *Copyright; char *CopyrightPhotographer; char *CopyrightEditor; xp_field_list xp_fields; thumbnail_data Thumbnail; /* other */ int sections_found; /* FOUND_<marker> */ image_info_list info_list[SECTION_COUNT]; /* for parsing */ bool read_thumbnail; bool read_all; int ifd_nesting_level; /* internal */ file_section_list file; } image_info_type; typedef struct { int bits_per_sample; size_t width; size_t height; int num_components; } jpeg_sof_info; /* forward declarations */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index); static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table); /* Add a file_section to image_info returns the used block or -1. if size>0 and data == nullptr buffer of size is allocated */ static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, unsigned char *data) { file_section *tmp; int count = ImageInfo->file.count; size_t realloc_size = (count+1) * sizeof(file_section); tmp = (file_section *)IM_REALLOC(ImageInfo->file.list, realloc_size); CHECK_ALLOC_R(tmp, realloc_size, -1); ImageInfo->file.list = tmp; ImageInfo->file.list[count].type = 0xFFFF; ImageInfo->file.list[count].data = nullptr; ImageInfo->file.list[count].size = 0; ImageInfo->file.count = count+1; if (!size) { data = nullptr; } else if (data == nullptr) { data = (unsigned char *)IM_MALLOC(size); if (data == nullptr) IM_FREE(tmp); CHECK_ALLOC_R(data, size, -1); } ImageInfo->file.list[count].type = type; ImageInfo->file.list[count].data = data; ImageInfo->file.list[count].size = size; return count; } /* get length of string if buffer if less than buffer size or buffer size */ static size_t php_strnlen(char* str, size_t maxlen) { size_t len = 0; if (str && maxlen && *str) { do { len++; } while (--maxlen && *(++str)); } return len; } /* Add a value to image_info */ static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data*) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; PHP_STRDUP(info_data->name, name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen((char*)value, length); // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { /* do not recompute length here */ // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = (image_info_value*)IM_CALLOC(length, sizeof(image_info_value)); CHECK_ALLOC(info_value->list, sizeof(image_info_value)); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + get_php_tiff_bytes_per_format(format)) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: info_value->f = *(float *)value; case TAG_FMT_DOUBLE: info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a tag from IFD to image_info */ static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value) { exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel); } /* Evaluate number, be it int, rational, or float from directory. */ static double exif_convert_any_format(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return (double)php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (double)php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return (signed short)php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (double)*(float *)value; case TAG_FMT_DOUBLE: return *(double *)value; } return 0; } /* Evaluate number, be it int, rational, or float from directory. */ static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den); } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (size_t)*(float *)value; case TAG_FMT_DOUBLE: return (size_t)*(double *)value; } return 0; } /* Get 16 bits motorola order (always) for jpeg header stuff. */ static int php_jpg_get16(void *value) { return (((unsigned char *)value)[0] << 8) | ((unsigned char *)value)[1]; } /* Write 16 bit unsigned value to data */ static void php_ifd_set16u(char *data, unsigned int value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF00) >> 8; data[1] = (value & 0x00FF); } else { data[1] = (value & 0xFF00) >> 8; data[0] = (value & 0x00FF); } } /* Convert a 32 bit unsigned value from file's native byte order */ static void php_ifd_set32u(char *data, size_t value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF000000) >> 24; data[1] = (value & 0x00FF0000) >> 16; data[2] = (value & 0x0000FF00) >> 8; data[3] = (value & 0x000000FF); } else { data[3] = (value & 0xFF000000) >> 24; data[2] = (value & 0x00FF0000) >> 16; data[1] = (value & 0x0000FF00) >> 8; data[0] = (value & 0x000000FF); } } /* Create a value for an ifd from an info_data pointer */ static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel) { size_t byte_count; char *value_ptr, *data_ptr; size_t i; image_info_value *info_value; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; size_t malloc_size = byte_count > 4 ? byte_count : 4; value_ptr = (char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(value_ptr, malloc_size, nullptr); memset(value_ptr, 0, 4); if (!info_data->length) { return value_ptr; } if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE))) { memmove(value_ptr, info_data->value.s, byte_count); return value_ptr; } else if (info_data->format == TAG_FMT_BYTE) { *value_ptr = info_data->value.u; return value_ptr; } else if (info_data->format == TAG_FMT_SBYTE) { *value_ptr = info_data->value.i; return value_ptr; } else { data_ptr = value_ptr; for(i=0; i<info_data->length; i++) { if (info_data->length==1) { info_value = &info_data->value; } else { info_value = &info_data->value.list[i]; } switch(info_data->format) { case TAG_FMT_USHORT: php_ifd_set16u(data_ptr, info_value->u, motorola_intel); data_ptr += 2; break; case TAG_FMT_ULONG: php_ifd_set32u(data_ptr, info_value->u, motorola_intel); data_ptr += 4; break; case TAG_FMT_SSHORT: php_ifd_set16u(data_ptr, info_value->i, motorola_intel); data_ptr += 2; break; case TAG_FMT_SLONG: php_ifd_set32u(data_ptr, info_value->i, motorola_intel); data_ptr += 4; break; case TAG_FMT_URATIONAL: php_ifd_set32u(data_ptr, info_value->sr.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SRATIONAL: php_ifd_set32u(data_ptr, info_value->ur.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SINGLE: memmove(data_ptr, &info_value->f, 4); data_ptr += 4; break; case TAG_FMT_DOUBLE: memmove(data_ptr, &info_value->d, 8); data_ptr += 8; break; } } } return value_ptr; } /* Process a COM marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ static void exif_process_COM(image_info_type *image_info, char *value, size_t length) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2); } /* Check and build thumbnail */ static void exif_thumbnail_build(image_info_type *ImageInfo) { size_t new_size, new_move, new_value; char *new_data; void *value_ptr; int i, byte_count; image_info_list *info_list; image_info_data *info_data; if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) { return; /* ignore this call */ } switch(ImageInfo->Thumbnail.filetype) { default: case IMAGE_FILETYPE_JPEG: /* done */ break; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: info_list = &ImageInfo->info_list[SECTION_THUMBNAIL]; new_size = 8 + 2 + info_list->count * 12 + 4; new_value= new_size; /* offset for ifd values outside ifd directory */ for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (byte_count > 4) { new_size += byte_count; } } new_move = new_size; new_data = (char *)IM_REALLOC(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size + new_size); CHECK_ALLOC(new_data, ImageInfo->Thumbnail.size + new_size); ImageInfo->Thumbnail.data = new_data; memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size); ImageInfo->Thumbnail.size += new_size; /* fill in data */ if (ImageInfo->motorola_intel) { memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8); } else { memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8); } new_data += 8; php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel); new_data += 2; for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, TAG_FMT_ULONG, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, 1, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 8, new_move, ImageInfo->motorola_intel); } else { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel); value_ptr = exif_ifd_make_value(info_data, ImageInfo->motorola_intel); if (byte_count <= 4) { memmove(new_data+8, value_ptr, 4); } else { php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel); memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count); new_value += byte_count; } if (value_ptr) IM_FREE(value_ptr); } new_data += 12; } memset(new_data, 0, 4); /* next ifd pointer */ break; } } /* Grab the thumbnail, corrected */ static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length) { if (ImageInfo->Thumbnail.data) { raise_warning("Multiple possible thumbnails"); return; /* Should not happen */ } if (!ImageInfo->read_thumbnail) { return; /* ignore this call */ } /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */ if (ImageInfo->Thumbnail.size >= 65536 || ImageInfo->Thumbnail.size <= 0 || ImageInfo->Thumbnail.offset <= 0) { raise_warning("Illegal thumbnail size/offset"); return; } /* Check to make sure we are not going to go past the ExifLength */ if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) { raise_warning("Thumbnail goes IFD boundary or end of file reached"); return; } PHP_STRNDUP(ImageInfo->Thumbnail.data, offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size); exif_thumbnail_build(ImageInfo); } /* Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */ static int exif_process_undefined(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ if (byte_count) { PHP_STRNDUP((*result), value, byte_count); /* NULL @ byte_count!!! */ if (*result) return byte_count+1; } return 0; } /* Copy a string in Exif header to a character string returns length of allocated buffer if any. */ #if !EXIF_USE_MBSTRING static int exif_process_string_raw(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ *result = 0; if (byte_count) { (*result) = (char*)IM_MALLOC(byte_count + 1); CHECK_ALLOC_R((*result), byte_count + 1, 0); memcpy(*result, value, byte_count); (*result)[byte_count] = '\0'; return byte_count+1; } return 0; } #endif /* * Copy a string in Exif header to a character string and return length of allocated buffer if any. In contrast to exif_process_string this function does always return a string buffer */ static int exif_process_string(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we cannot use strlen to * determin length of string and we cannot use strlcpy with len=byte_count+1 * because then we might get into an EXCEPTION if we exceed an allocated * memory page...so we use php_strnlen in conjunction with memcpy and add * the NUL char. */ if ((byte_count=php_strnlen(value, byte_count)) > 0) { return exif_process_undefined(result, value, byte_count); } PHP_STRNDUP((*result), "", 1); /* force empty string */ if (*result) return byte_count+1; return 0; } /* Process UserComment in IFD. */ static int exif_process_user_comment(image_info_type* /*ImageInfo*/, char** pszInfoPtr, char** pszEncoding, char* szValuePtr, int ByteCount) { int a; #if EXIF_USE_MBSTRING char *decode; size_t len; #endif *pszEncoding = nullptr; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, decode, &len); return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user */ PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING if (ImageInfo->motorola_intel) { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_be, &len); } else { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_le, &len); } return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ PHP_STRDUP(*pszEncoding, "UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount); return strlen(*pszInfoPtr); } /* Process unicode field in IFD. */ static int exif_process_unicode(image_info_type* /*ImageInfo*/, xp_field_type* xp_field, int tag, char* szValuePtr, int ByteCount) { xp_field->tag = tag; xp_field->value = nullptr; /* Copy the comment */ #if EXIF_USE_MBSTRING xp_field->value = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, ImageInfo->decode_unicode_le, &xp_field->size); return xp_field->size; #else xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount); return xp_field->size; #endif } /* Process nested IFDs directories in Maker Note. */ static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; char *value_end = value_ptr + value_len; for (unsigned int i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) return 0; maker_note = maker_note_array+i; if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) { continue; } if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) { continue; } if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, (maker_note->id_string_len < value_len ? maker_note->id_string_len : value_len))) { continue; } break; } if (maker_note->offset >= value_len) return 0; dir_start = value_ptr + maker_note->offset; ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } if (value_end - dir_start < 2) return 0; NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: if (value_end - (dir_start+10) < 4) return 0; offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); if (offset_diff < 0 || offset_diff >= value_len) return 0; offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { raise_warning("Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, value_end, IFDlength, displacement, section_index, 0, maker_note->tag_table)) { return 0; } } ImageInfo->motorola_intel = old_motorola_intel; return 0; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=nullptr; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { raise_warning("corrupt EXIF header: maximum directory " "nesting level reached"); return 0; } ImageInfo->ifd_nesting_level++; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ raise_warning("Process tag(x%04X=%s): Illegal format code 0x%04X, " "suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { raise_warning("Process tag(x%04X=%s): Illegal components(%d)", tag, exif_get_tagname(tag, tagname, -12, tag_table), components); return 1; } byte_count_signed = (int64_t)components * get_php_tiff_bytes_per_format(format); if (byte_count_signed < 0 || (byte_count_signed > 2147483648)) { raise_warning("Process tag(x%04X=%s): Illegal byte_count(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table), byte_count_signed); return 1; // ignore that field, but don't abort parsing } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* // It is important to check for IMAGE_FILETYPE_TIFF // JPEG does not use absolute pointers instead // its pointers are relative to the start // of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX < %04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, dir_entry-offset_base); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX + x%04lX = x%04lX > x%04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, byte_count, offset_val+byte_count, IFDlength); } return 0; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = (char *)IM_MALLOC(byte_count); CHECK_ALLOC_R(value_ptr, byte_count, 0); outside = value_ptr; } else { /* // in most cases we only access a small range so // it is faster to use a static buffer there // BUT it offers also the possibility to have // pointers read without the need to free them // explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = ImageInfo->infile->tell(); ImageInfo->infile->seek(displacement+offset_val, SEEK_SET); fgot = ImageInfo->infile->tell(); if (fgot!=displacement+offset_val) { if (outside) IM_FREE(outside); raise_warning("Wrong file pointer: 0x%08lX != 0x%08lX", fgot, displacement+offset_val); return 0; } String str = ImageInfo->infile->read(byte_count); fgot = str.length(); memcpy(value_ptr, str.c_str(), fgot); ImageInfo->infile->seek(fpos, SEEK_SET); if (fgot<byte_count) { if (outside) IM_FREE(outside); raise_warning("Unexpected end of file reached"); return 0; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ PHP_STRDUP(ImageInfo->CopyrightPhotographer, value_ptr); PHP_STRNDUP( ImageInfo->CopyrightEditor, value_ptr + length + 1, byte_count - length - 1 ); if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); php_vspprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, ImageInfo->CopyrightEditor); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { PHP_STRNDUP(ImageInfo->Copyright, value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: { size_t realloc_size = (ImageInfo->xp_fields.count+1) * sizeof(xp_field_type); tmp_xp = (xp_field_type*) IM_REALLOC(ImageInfo->xp_fields.list, realloc_size); if (!tmp_xp) { if (outside) IM_FREE(outside); } CHECK_ALLOC_R(tmp_xp, realloc_size, 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count); break; } case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ raise_notice("Skip SUB IFD"); } break; case TAG_MAKE: PHP_STRNDUP(ImageInfo->make, value_ptr, byte_count); break; case TAG_MODEL: PHP_STRNDUP(ImageInfo->model, value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } CHECK_BUFFER_R(value_ptr, end, 4, 0); Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { raise_warning("Illegal IFD Pointer"); return 0; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, end, IFDlength, displacement, sub_section_index)) { return 0; } } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table), tag, format, components, value_ptr); if (outside) IM_FREE(outside); return 1; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index) { int de; int NumDirEntries; int NextDirOffset; ImageInfo->sections_found |= FOUND_IFD0; CHECK_BUFFER_R(dir_start, end, 2, 0); NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { raise_warning("Illegal IFD size: x%04X + 2 + x%04X*12 = x%04X > x%04lX", (int)((size_t)dir_start+2-(size_t)offset_base), NumDirEntries, (int)((size_t)dir_start+2+ NumDirEntries*12-(size_t)offset_base), IFDlength); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, end, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index))) { return 0; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return true; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) * to the thumbnail */ CHECK_BUFFER_R(dir_start+2+12*de, end, 4, 0); NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ if (offset_base + NextDirOffset < offset_base || offset_base + NextDirOffset > offset_base+IFDlength) { raise_warning("Illegal IFD offset"); return 0; } /* That is the IFD for the first thumbnail */ if (exif_process_IFD_in_JPEG(ImageInfo, offset_base + NextDirOffset, offset_base, end, IFDlength, displacement, SECTION_THUMBNAIL)) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength); } return 1; } else { return 0; } } return 1; } /* Process a TIFF header in a JPEG file */ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { char *end = CharBuf + length; unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ CHECK_BUFFER(CharBuf, end, 2); if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { raise_warning("Invalid TIFF a lignment marker"); return; } /* Check the next two values for correctness. */ CHECK_BUFFER(CharBuf+4, end, 4); exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { raise_warning("Invalid TIFF start (1)"); return; } if (offset_of_ifd > length) { raise_warning("Invalid IFD start"); return; } ImageInfo->sections_found |= FOUND_IFD0; /* First directory starts at offset 8. Offsets starts at 0. */ exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, end, length/* -14*/, displacement, SECTION_IFD0); /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } /* Process an JPEG APP1 block marker Describes all the drivel that most digital cameras include... */ static void exif_process_APP1(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { /* Check the APP1 for Exif Identifier Code */ char *end = CharBuf + length; static const unsigned char ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00}; CHECK_BUFFER(CharBuf+2, end, 6); if (length <= 8 || memcmp(CharBuf+2, ExifHeader, 6)) { raise_warning("Incorrect APP1 Exif Identifier Code"); return; } exif_process_TIFF_in_JPEG(ImageInfo, CharBuf + 8, length - 8, displacement+8); } /* Process an JPEG APP12 block marker used by OLYMPUS */ static void exif_process_APP12(image_info_type *ImageInfo, char *buffer, size_t length) { size_t l1, l2=0; if ((l1 = php_strnlen(buffer+2, length-2)) > 0) { exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company", TAG_NONE, TAG_FMT_STRING, l1, buffer+2); if (length > 2+l1+1) { l2 = php_strnlen(buffer+2+l1+1, length-2-l1-1); exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info", TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1); } } } /* Process a SOFn marker. This is useful for the image dimensions */ static void exif_process_SOFn(unsigned char* Data, int /*marker*/, jpeg_sof_info* result) { result->bits_per_sample = Data[2]; result->height = php_jpg_get16(Data+3); result->width = php_jpg_get16(Data+5); result->num_components = Data[7]; } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_JPEG_header(image_info_type *ImageInfo) { int section, sn; int marker = 0, last_marker = M_PSEUDO, comment_correction=1; int ll, lh; unsigned char *Data; size_t fpos, size, got, itemlen; jpeg_sof_info sof_info; for(section=0;;section++) { // get marker byte, swallowing possible padding // some software does not count the length bytes of COM section // one company doing so is very much envolved in JPEG... // so we accept too if (last_marker==M_COM && comment_correction) { comment_correction = 2; } do { if ((marker = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if (last_marker==M_COM && comment_correction>0) { if (marker!=0xFF) { marker = 0xff; comment_correction--; } else { last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */ } } } while (marker == 0xff); if (last_marker==M_COM && !comment_correction) { raise_notice("Image has corrupt COM section: some software set " "wrong length information"); } if (last_marker==M_COM && comment_correction) return M_EOI; /* ah illegal: char after COM section not 0xFF */ fpos = ImageInfo->infile->tell(); if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. raise_warning("To many padding bytes"); return 0; } /* Read the length of the section. */ if ((lh = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if ((ll = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } itemlen = (lh << 8) | ll; if (itemlen < 2) { raise_warning("File structure corrupted"); return 0; } sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; /* Store first two pre-read bytes. */ Data[0] = (unsigned char)lh; Data[1] = (unsigned char)ll; String str = ImageInfo->infile->read(itemlen-2); got = str.length(); if (got != itemlen-2) { raise_warning("Error reading from file: " "got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)", got, got, itemlen-2, itemlen-2); return 0; } memcpy(Data+2, str.c_str(), got); switch(marker) { case M_SOS: /* stop before hitting compressed data */ // If reading entire image is requested, read the rest of the data. if (ImageInfo->read_all) { /* Determine how much file is left. */ fpos = ImageInfo->infile->tell(); size = ImageInfo->FileSize - fpos; sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; str = ImageInfo->infile->read(size); got = str.length(); if (got != size) { raise_warning("Unexpected end of file reached"); return 0; } memcpy(Data, str.c_str(), got); } return 1; case M_EOI: /* in case it's a tables-only JPEG stream */ raise_warning("No image in jpeg!"); return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0; case M_COM: /* Comment section */ exif_process_COM(ImageInfo, (char *)Data, itemlen); break; case M_EXIF: if (!(ImageInfo->sections_found&FOUND_IFD0)) { /*ImageInfo->sections_found |= FOUND_EXIF;*/ /* Seen files from some 'U-lead' software with Vivitar scanner that uses marker 31 later in the file (no clue what for!) */ exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos); } break; case M_APP12: exif_process_APP12(ImageInfo, (char *)Data, itemlen); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if ((itemlen - 2) < 6) { return 0; } exif_process_SOFn(Data, marker, &sof_info); ImageInfo->Width = sof_info.width; ImageInfo->Height = sof_info.height; if (sof_info.num_components == 3) { ImageInfo->IsColor = 1; } else { ImageInfo->IsColor = 0; } break; default: /* skip any other marker silently. */ break; } /* keep track of last marker */ last_marker = marker; } return 1; } /* Reallocate a file section returns 0 on success and -1 on failure */ static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size) { void *tmp; /* This is not a malloc/realloc check. It is a plausibility check for the * function parameters (requirements engineering). */ if (section_index >= ImageInfo->file.count) { raise_warning("Illegal reallocating of undefined file section"); return -1; } tmp = IM_REALLOC(ImageInfo->file.list[section_index].data, size); CHECK_ALLOC_R(tmp, size, -1); ImageInfo->file.list[section_index].data = (unsigned char *)tmp; ImageInfo->file.list[section_index].size = size; return 0; } /* Parse the TIFF header; */ static int exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index) { int i, sn, num_entries, sub_section_index = 0; unsigned char *dir_entry; char tagname[64]; size_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot; int entry_tag , entry_type; tag_table_type tag_table = exif_get_tag_table(section_index); if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { return 0; } if (ImageInfo->FileSize >= dir_offset+2) { sn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, nullptr); if (sn == -1) return 0; /* we do not know the order of sections */ ImageInfo->infile->seek(dir_offset, SEEK_SET); String snData = ImageInfo->infile->read(2); memcpy(ImageInfo->file.list[sn].data, snData.c_str(), 2); num_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel); dir_size = 2/*num dir entries*/ + 12/*length of entry*/*num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; if (ImageInfo->FileSize >= dir_offset+dir_size) { if (exif_file_sections_realloc(ImageInfo, sn, dir_size)) { return 0; } snData = ImageInfo->infile->read(dir_size-2); memcpy(ImageInfo->file.list[sn].data+2, snData.c_str(), dir_size-2); next_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel); /* now we have the directory we can look how long it should be */ ifd_size = dir_size; char *end = (char*)ImageInfo->file.list[sn].data + dir_size; for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_type > NUM_FORMATS) { raise_notice("Read from TIFF: tag(0x%04X,%12s): " "Illegal format code 0x%04X, switching to BYTE", entry_tag, exif_get_tagname(entry_tag, tagname, -12, tag_table), entry_type); /* Since this is repeated in exif_process_IFD_TAG make it a notice here and make it a warning in the exif_process_IFD_TAG which is called elsewhere. */ entry_type = TAG_FMT_BYTE; } entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * get_php_tiff_bytes_per_format(entry_type); if (entry_length <= 4) { switch(entry_type) { case TAG_FMT_USHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SSHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_ULONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SLONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel); break; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Height = entry_value; break; case TAG_PHOTOMETRIC_INTERPRETATION: switch (entry_value) { case PMI_BLACK_IS_ZERO: case PMI_WHITE_IS_ZERO: case PMI_TRANSPARENCY_MASK: ImageInfo->IsColor = 0; break; case PMI_RGB: case PMI_PALETTE_COLOR: case PMI_SEPARATED: case PMI_YCBCR: case PMI_CIELAB: ImageInfo->IsColor = 1; break; } break; } } else { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* if entry needs expading ifd cache and entry is at end of current ifd cache. */ /* otherwise there may be huge holes between two entries */ if (entry_offset + entry_length > dir_offset + ifd_size && entry_offset == dir_offset + ifd_size) { ifd_size = entry_offset + entry_length - dir_offset; } } } if (ImageInfo->FileSize >= dir_offset + ImageInfo->file.list[sn].size) { if (ifd_size > dir_size) { if (dir_offset + ifd_size > ImageInfo->FileSize) { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX + x%04lX)", ImageInfo->FileSize, dir_offset, ifd_size); return 0; } if (exif_file_sections_realloc(ImageInfo, sn, ifd_size)) { return 0; } else { end = (char*)ImageInfo->file.list[sn].data + dir_size; } /* read values not stored in directory itself */ snData = ImageInfo->infile->read(ifd_size-dir_size); memcpy(ImageInfo->file.list[sn].data+dir_size, snData.c_str(), ifd_size-dir_size); } /* now process the tags */ for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+2, end, 2, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_tag == TAG_EXIF_IFD_POINTER || entry_tag == TAG_INTEROP_IFD_POINTER || entry_tag == TAG_GPS_IFD_POINTER || entry_tag == TAG_SUB_IFD) { switch(entry_tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; case TAG_SUB_IFD: ImageInfo->sections_found |= FOUND_THUMBNAIL; sub_section_index = SECTION_THUMBNAIL; break; } CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index); if (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { if (!ImageInfo->Thumbnail.data) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } } } else { if (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry, (char*)(ImageInfo->file.list[sn].data-dir_offset), (char*)(ImageInfo->file.list[sn].data + ifd_size), ifd_size, 0, section_index, 0, tag_table)) { return 0; } } } /* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */ if (next_offset && section_index != SECTION_THUMBNAIL) { /* this should be a thumbnail IFD */ /* the thumbnail itself is stored at Tag=StripOffsets */ ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL); if (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); CHECK_ALLOC_R(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size, 0); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } return 1; } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX)", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than size " "of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+dir_size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "start of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+2); return 0; } } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_FILE_header(image_info_type *ImageInfo) { unsigned char *file_header; int ret = 0; ImageInfo->FileType = IMAGE_FILETYPE_UNKNOWN; if (ImageInfo->FileSize >= 2) { ImageInfo->infile->seek(0, SEEK_SET); String fileHeader = ImageInfo->infile->read(2); if (fileHeader.length() != 2) { return 0; } file_header = (unsigned char *)fileHeader.c_str(); if ((file_header[0]==0xff) && (file_header[1]==M_SOI)) { ImageInfo->FileType = IMAGE_FILETYPE_JPEG; if (exif_scan_JPEG_header(ImageInfo)) { ret = 1; } else { raise_warning("Invalid JPEG file"); } } else if (ImageInfo->FileSize >= 8) { String str = ImageInfo->infile->read(6); if (str.length() != 6) { return 0; } fileHeader += str; file_header = (unsigned char *)fileHeader.c_str(); if (!memcmp(file_header, "II\x2A\x00", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_II; ImageInfo->motorola_intel = 0; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else if (!memcmp(file_header, "MM\x00\x2a", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_MM; ImageInfo->motorola_intel = 1; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else { raise_warning("File not supported"); return 0; } } } else { raise_warning("File too small (%lu)", ImageInfo->FileSize); } return ret; } static int exif_read_file(image_info_type *ImageInfo, String FileName, bool read_thumbnail, bool read_all) { struct stat st; /* Start with an empty image information structure. */ memset(ImageInfo, 0, sizeof(*ImageInfo)); ImageInfo->motorola_intel = -1; /* flag as unknown */ ImageInfo->infile = File::Open(FileName, "rb"); if (!ImageInfo->infile) { raise_warning("Unable to open file %s", FileName.c_str()); return 0; } auto plain_file = dyn_cast<PlainFile>(ImageInfo->infile); if (plain_file) { if (stat(FileName.c_str(), &st) >= 0) { if ((st.st_mode & S_IFMT) != S_IFREG) { raise_warning("Not a file"); return 0; } } /* Store file date/time. */ ImageInfo->FileDateTime = st.st_mtime; ImageInfo->FileSize = st.st_size; } else { if (!ImageInfo->FileSize) { ImageInfo->infile->seek(0, SEEK_END); ImageInfo->FileSize = ImageInfo->infile->tell(); ImageInfo->infile->seek(0, SEEK_SET); } } ImageInfo->FileName = HHVM_FN(basename)(FileName); ImageInfo->read_thumbnail = read_thumbnail; ImageInfo->read_all = read_all; ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_UNKNOWN; PHP_STRDUP(ImageInfo->encode_unicode, "ISO-8859-15"); PHP_STRDUP(ImageInfo->decode_unicode_be, "UCS-2BE"); PHP_STRDUP(ImageInfo->decode_unicode_le, "UCS-2LE"); PHP_STRDUP(ImageInfo->encode_jis, ""); PHP_STRDUP(ImageInfo->decode_jis_be, "JIS"); PHP_STRDUP(ImageInfo->decode_jis_le, "JIS"); ImageInfo->ifd_nesting_level = 0; /* Scan the JPEG headers. */ auto ret = exif_scan_FILE_header(ImageInfo); ImageInfo->infile->close(); return ret; } /* Free memory allocated for image_info */ static void exif_iif_free(image_info_type *image_info, int section_index) { int i; void *f; /* faster */ if (image_info->info_list[section_index].count) { for (i=0; i < image_info->info_list[section_index].count; i++) { if ((f=image_info->info_list[section_index].list[i].name) != nullptr) { IM_FREE(f); } switch(image_info->info_list[section_index].list[i].format) { case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (image_info->info_list[section_index].list[i].length<1) break; default: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: if ((f=image_info->info_list[section_index].list[i].value.s) != nullptr) { IM_FREE(f); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: /* nothing to do here */ if (image_info->info_list[section_index].list[i].length > 1) { if ((f=image_info->info_list[section_index].list[i].value.list) != nullptr) { IM_FREE(f); } } break; } } } if (image_info->info_list[section_index].list) { IM_FREE(image_info->info_list[section_index].list); } } /* Discard all file_sections in ImageInfo */ static int exif_file_sections_free(image_info_type *ImageInfo) { int i; if (ImageInfo->file.count) { for (i=0; i<ImageInfo->file.count; i++) { if (ImageInfo->file.list[i].data) { IM_FREE(ImageInfo->file.list[i].data); } } } if (ImageInfo->file.list) IM_FREE(ImageInfo->file.list); ImageInfo->file.count = 0; return 1; } /* Discard data scanned by exif_read_file. */ static int exif_discard_imageinfo(image_info_type *ImageInfo) { int i; if (ImageInfo->UserComment) IM_FREE(ImageInfo->UserComment); if (ImageInfo->UserCommentEncoding) { IM_FREE(ImageInfo->UserCommentEncoding); } if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); if (ImageInfo->CopyrightPhotographer) { IM_FREE(ImageInfo->CopyrightPhotographer); } if (ImageInfo->CopyrightEditor) IM_FREE(ImageInfo->CopyrightEditor); if (ImageInfo->Thumbnail.data) IM_FREE(ImageInfo->Thumbnail.data); if (ImageInfo->encode_unicode) IM_FREE(ImageInfo->encode_unicode); if (ImageInfo->decode_unicode_be) { IM_FREE(ImageInfo->decode_unicode_be); } if (ImageInfo->decode_unicode_le) { IM_FREE(ImageInfo->decode_unicode_le); } if (ImageInfo->encode_jis) IM_FREE(ImageInfo->encode_jis); if (ImageInfo->decode_jis_be) IM_FREE(ImageInfo->decode_jis_be); if (ImageInfo->decode_jis_le) IM_FREE(ImageInfo->decode_jis_le); if (ImageInfo->make) IM_FREE(ImageInfo->make); if (ImageInfo->model) IM_FREE(ImageInfo->model); for (i=0; i<ImageInfo->xp_fields.count; i++) { if (ImageInfo->xp_fields.list[i].value) { IM_FREE(ImageInfo->xp_fields.list[i].value); } } if (ImageInfo->xp_fields.list) IM_FREE(ImageInfo->xp_fields.list); for (i=0; i<SECTION_COUNT; i++) { exif_iif_free(ImageInfo, i); } exif_file_sections_free(ImageInfo); memset(ImageInfo, 0, sizeof(*ImageInfo)); return 1; } /* Add an int value to image_info */ static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value) { image_info_data *info_data; image_info_data *list; size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_SLONG; info_data->length = 1; PHP_STRDUP(info_data->name, name); info_data->value.i = value; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_STRING; info_data->length = 1; PHP_STRDUP(info_data->name, name); // TODO // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, strlen(value), nullptr, 0); // } else { PHP_STRDUP(info_data->value.s, value); image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* Add a format string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name, char *value, ...) { va_list arglist; va_start(arglist, value); if (value) { char *tmp = 0; php_vspprintf_ap(&tmp, 0, value, arglist); exif_iif_add_str(image_info, section_index, name, tmp); if (tmp) IM_FREE(tmp); } va_end(arglist); } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_UNDEFINED; info_data->length = length; PHP_STRDUP(info_data->name, name); // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, length, &length, 0); // info_data->length = length; // } else { info_data->value.s = (char *)IM_MALLOC(length + 1); if (!info_data->value.s) info_data->length = 0; CHECK_ALLOC(info_data->value.s, length + 1); memcpy(info_data->value.s, value, length); info_data->value.s[length] = 0; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* scan JPEG in thumbnail (memory) */ static int exif_scan_thumbnail(image_info_type *ImageInfo) { unsigned char c, *data = (unsigned char*)ImageInfo->Thumbnail.data; int n, marker; size_t length=2, pos=0; jpeg_sof_info sof_info; if (!data) { return 0; /* nothing to do here */ } if (memcmp(data, "\xFF\xD8\xFF", 3)) { if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) { raise_warning("Thumbnail is not a JPEG image"); } return 0; } for (;;) { pos += length; if (pos>=ImageInfo->Thumbnail.size) return 0; c = data[pos++]; if (pos>=ImageInfo->Thumbnail.size) return 0; if (c != 0xFF) { return 0; } n = 8; while ((c = data[pos++]) == 0xFF && n--) { if (pos+3>=ImageInfo->Thumbnail.size) return 0; /* +3 = pos++ of next check when reaching marker + 2 bytes for length */ } if (c == 0xFF) return 0; marker = c; length = php_jpg_get16(data+pos); if (pos+length>=ImageInfo->Thumbnail.size) { return 0; } switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: /* handle SOFn block */ exif_process_SOFn(data+pos, marker, &sof_info); ImageInfo->Thumbnail.height = sof_info.height; ImageInfo->Thumbnail.width = sof_info.width; return 1; case M_SOS: case M_EOI: raise_warning("Could not compute size of thumbnail"); return 0; break; default: /* just skip */ break; } } raise_warning("Could not compute size of thumbnail"); return 0; } /* Add image_info to associative array value. */ static void add_assoc_image_info(Array &value, bool sub_array, image_info_type *image_info, int section_index) { char buffer[64], *val, *name, uname[64]; int i, ap, l, b, idx=0, unknown=0; image_info_value *info_value; image_info_data *info_data; Array tmp; Array *tmpi = &tmp; Array array; if (image_info->info_list[section_index].count) { if (!sub_array) { tmpi = &value; } for(i=0; i<image_info->info_list[section_index].count; i++) { info_data = &image_info->info_list[section_index].list[i]; info_value = &info_data->value; if (!(name = info_data->name)) { snprintf(uname, sizeof(uname), "%d", unknown++); name = uname; } if (info_data->length==0) { tmpi->set(String(name, CopyString), uninit_null()); } else { switch (info_data->format) { default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ case TAG_FMT_BYTE: case TAG_FMT_SBYTE: case TAG_FMT_UNDEFINED: if (!info_value->s) { tmpi->set(String(name, CopyString), ""); } else { tmpi->set(String(name, CopyString), String(info_value->s, info_data->length, CopyString)); } break; case TAG_FMT_STRING: if (!(val = info_value->s)) { val = ""; } if (section_index==SECTION_COMMENT) { tmpi->set(idx++, String(val, CopyString)); } else { tmpi->set(String(name, CopyString), String(val, CopyString)); } break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: /*case TAG_FMT_BYTE: case TAG_FMT_SBYTE:*/ case TAG_FMT_USHORT: case TAG_FMT_SSHORT: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: case TAG_FMT_ULONG: case TAG_FMT_SLONG: /* now the rest, first see if it becomes an array */ if ((l = info_data->length) > 1) { array.clear(); } for(ap=0; ap<l; ap++) { if (l>1) { info_value = &info_data->value.list[ap]; } switch (info_data->format) { case TAG_FMT_BYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(b, (int)(info_value->s[b])); } break; } case TAG_FMT_USHORT: case TAG_FMT_ULONG: if (l==1) { tmpi->set(String(name, CopyString), (int)info_value->u); } else { array.set(ap, (int)info_value->u); } break; case TAG_FMT_URATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SBYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(ap, (int)info_value->s[b]); } break; } case TAG_FMT_SSHORT: case TAG_FMT_SLONG: if (l==1) { tmpi->set(String(name, CopyString), info_value->i); } else { array.set(ap, info_value->i); } break; case TAG_FMT_SRATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SINGLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->f); } else { array.set(ap, info_value->f); } break; case TAG_FMT_DOUBLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->d); } else { array.set(ap, info_value->d); } break; } info_value = &info_data->value.list[ap]; } if (l>1) { tmpi->set(String(name, CopyString), array); } break; } } } if (sub_array) { value.set(exif_get_sectionname(section_index), tmp); } } } Variant HHVM_FUNCTION(exif_tagname, int64_t index) { char *szTemp; szTemp = exif_get_tagname(index, nullptr, 0, tag_table_IFD); if (index <0 || !szTemp || !szTemp[0]) { return false; } else { return String(szTemp, CopyString); } } Variant HHVM_FUNCTION(exif_read_data, const String& filename, const String& sections /*="" */, bool arrays /*=false */, bool thumbnail /*=false */) { int i, ret, sections_needed=0; image_info_type ImageInfo; char tmp[64], *sections_str, *s; memset(&ImageInfo, 0, sizeof(ImageInfo)); if (!sections.empty()) { php_vspprintf(&sections_str, 0, ",%s,", sections.c_str()); /* sections_str DOES start with , and SPACES are NOT allowed in names */ s = sections_str; while(*++s) { if (*s==' ') { *s = ','; } } for (i=0; i<SECTION_COUNT; i++) { snprintf(tmp, sizeof(tmp), ",%s,", exif_get_sectionname(i).c_str()); if (strstr(sections_str, tmp)) { sections_needed |= 1<<i; } } if (sections_str) IM_FREE(sections_str); } ret = exif_read_file(&ImageInfo, filename, thumbnail, 0); sections_str = exif_get_sectionlist(ImageInfo.sections_found); /* do not inform about in debug*/ ImageInfo.sections_found |= FOUND_COMPUTED|FOUND_FILE; if (ret==0|| (sections_needed && !(sections_needed&ImageInfo.sections_found))) { exif_discard_imageinfo(&ImageInfo); if (sections_str) IM_FREE(sections_str); return false; } /* now we can add our information */ exif_iif_add_str(&ImageInfo, SECTION_FILE, "FileName", (char *)ImageInfo.FileName.c_str()); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileDateTime", ImageInfo.FileDateTime); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileSize", ImageInfo.FileSize); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileType", ImageInfo.FileType); exif_iif_add_str(&ImageInfo, SECTION_FILE, "MimeType", (char*)php_image_type_to_mime_type(ImageInfo.FileType)); exif_iif_add_str(&ImageInfo, SECTION_FILE, "SectionsFound", sections_str ? sections_str : (char *)"NONE"); if (ImageInfo.Width>0 && ImageInfo.Height>0) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "html", "width=\"%d\" height=\"%d\"", ImageInfo.Width, ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Height", ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Width", ImageInfo.Width); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "IsColor", ImageInfo.IsColor); if (ImageInfo.motorola_intel != -1) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "ByteOrderMotorola", ImageInfo.motorola_intel); } if (ImageInfo.FocalLength) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocalLength", "%4.1Fmm", ImageInfo.FocalLength); if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "35mmFocalLength", "%dmm", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5)); } } if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "CCDWidth", "%dmm", (int)ImageInfo.CCDWidth); } if (ImageInfo.ExposureTime>0) { if (ImageInfo.ExposureTime <= 0.5) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s (1/%d)", ImageInfo.ExposureTime, (int)(0.5 + 1/ImageInfo.ExposureTime)); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s", ImageInfo.ExposureTime); } } if (ImageInfo.ApertureFNumber) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ApertureFNumber", "f/%.1F", ImageInfo.ApertureFNumber); } if (ImageInfo.Distance) { if (ImageInfo.Distance<0) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "Infinite"); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "%0.2Fm", ImageInfo.Distance); } } if (ImageInfo.UserComment) { exif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, "UserComment", ImageInfo.UserCommentLength, ImageInfo.UserComment); if (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "UserCommentEncoding", ImageInfo.UserCommentEncoding); } } exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright", ImageInfo.Copyright); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Photographer", ImageInfo.CopyrightPhotographer); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Editor", ImageInfo.CopyrightEditor); for (i=0; i<ImageInfo.xp_fields.count; i++) { exif_iif_add_str(&ImageInfo, SECTION_WINXP, exif_get_tagname(ImageInfo.xp_fields.list[i].tag, nullptr, 0, exif_get_tag_table(SECTION_WINXP)), ImageInfo.xp_fields.list[i].value); } if (ImageInfo.Thumbnail.size) { if (thumbnail) { /* not exif_iif_add_str : this is a buffer */ exif_iif_add_tag(&ImageInfo, SECTION_THUMBNAIL, "THUMBNAIL", TAG_NONE, TAG_FMT_UNDEFINED, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.data); } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { /* try to evaluate if thumbnail data is present */ exif_scan_thumbnail(&ImageInfo); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.FileType", ImageInfo.Thumbnail.filetype); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Thumbnail.MimeType", (char*)php_image_type_to_mime_type(ImageInfo.Thumbnail.filetype)); } if (ImageInfo.Thumbnail.width && ImageInfo.Thumbnail.height) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Height", ImageInfo.Thumbnail.height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Width", ImageInfo.Thumbnail.width); } if (sections_str) IM_FREE(sections_str); Array retarr; add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FILE); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMPUTED); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_ANY_TAG); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_IFD0); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_THUMBNAIL); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMMENT); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_EXIF); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_GPS); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_INTEROP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FPIX); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_APP12); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_WINXP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_MAKERNOTE); exif_discard_imageinfo(&ImageInfo); return retarr; } Variant HHVM_FUNCTION(exif_thumbnail, const String& filename, VRefParam width /* = null */, VRefParam height /* = null */, VRefParam imagetype /* = null */) { image_info_type ImageInfo; memset(&ImageInfo, 0, sizeof(ImageInfo)); int ret = exif_read_file(&ImageInfo, filename.c_str(), 1, 0); if (ret==0) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.data || !ImageInfo.Thumbnail.size) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { exif_scan_thumbnail(&ImageInfo); } width.assignIfRef((int64_t)ImageInfo.Thumbnail.width); height.assignIfRef((int64_t)ImageInfo.Thumbnail.height); imagetype.assignIfRef(ImageInfo.Thumbnail.filetype); String str(ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, CopyString); exif_discard_imageinfo(&ImageInfo); return str; } Variant HHVM_FUNCTION(exif_imagetype, const String& filename) { auto stream = File::Open(filename, "rb"); if (!stream) { return false; } int itype = php_getimagetype(stream); stream->close(); if (itype == IMAGE_FILETYPE_UNKNOWN) return false; return itype; } /////////////////////////////////////////////////////////////////////////////// struct ExifExtension final : Extension { ExifExtension() : Extension("exif", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(exif_imagetype); HHVM_FE(exif_read_data); HHVM_FE(exif_tagname); HHVM_FE(exif_thumbnail); HHVM_RC_INT(EXIF_USE_MBSTRING, 0); loadSystemlib(); } } s_exif_extension; struct GdExtension final : Extension { GdExtension() : Extension("gd", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(gd_info); HHVM_FE(getimagesize); HHVM_FE(getimagesizefromstring); HHVM_FE(image_type_to_extension); HHVM_FE(image_type_to_mime_type); HHVM_FE(image2wbmp); HHVM_FE(imageaffine); HHVM_FE(imageaffinematrixconcat); HHVM_FE(imageaffinematrixget); HHVM_FE(imagealphablending); HHVM_FE(imageantialias); HHVM_FE(imagearc); HHVM_FE(imagechar); HHVM_FE(imagecharup); HHVM_FE(imagecolorallocate); HHVM_FE(imagecolorallocatealpha); HHVM_FE(imagecolorat); HHVM_FE(imagecolorclosest); HHVM_FE(imagecolorclosestalpha); HHVM_FE(imagecolorclosesthwb); HHVM_FE(imagecolordeallocate); HHVM_FE(imagecolorexact); HHVM_FE(imagecolorexactalpha); HHVM_FE(imagecolormatch); HHVM_FE(imagecolorresolve); HHVM_FE(imagecolorresolvealpha); HHVM_FE(imagecolorset); HHVM_FE(imagecolorsforindex); HHVM_FE(imagecolorstotal); HHVM_FE(imagecolortransparent); HHVM_FE(imageconvolution); HHVM_FE(imagecopy); HHVM_FE(imagecopymerge); HHVM_FE(imagecopymergegray); HHVM_FE(imagecopyresampled); HHVM_FE(imagecopyresized); HHVM_FE(imagecreate); HHVM_FE(imagecreatefromgd2part); HHVM_FE(imagecreatefromgd); HHVM_FE(imagecreatefromgd2); HHVM_FE(imagecreatefromgif); #ifdef HAVE_GD_JPG HHVM_FE(imagecreatefromjpeg); #endif #ifdef HAVE_GD_PNG HHVM_FE(imagecreatefrompng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagecreatefromwebp); #endif HHVM_FE(imagecreatefromstring); HHVM_FE(imagecreatefromwbmp); HHVM_FE(imagecreatefromxbm); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) HHVM_FE(imagecreatefromxpm); #endif HHVM_FE(imagecreatetruecolor); HHVM_FE(imagecrop); HHVM_FE(imagecropauto); HHVM_FE(imagedashedline); HHVM_FE(imagedestroy); HHVM_FE(imageellipse); HHVM_FE(imagefill); HHVM_FE(imagefilledarc); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilter); HHVM_FE(imageflip); HHVM_FE(imagefontheight); HHVM_FE(imagefontwidth); #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE HHVM_FE(imageftbbox); HHVM_FE(imagefttext); #endif HHVM_FE(imagegammacorrect); HHVM_FE(imagegd2); HHVM_FE(imagegd); HHVM_FE(imagegif); HHVM_FE(imageinterlace); HHVM_FE(imageistruecolor); #ifdef HAVE_GD_JPG HHVM_FE(imagejpeg); #endif HHVM_FE(imagelayereffect); HHVM_FE(imageline); HHVM_FE(imageloadfont); #ifdef HAVE_GD_PNG HHVM_FE(imagepng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagewebp); #endif HHVM_FE(imagepolygon); HHVM_FE(imagerectangle); HHVM_FE(imagerotate); HHVM_FE(imagesavealpha); HHVM_FE(imagescale); HHVM_FE(imagesetbrush); HHVM_FE(imagesetinterpolation); HHVM_FE(imagesetpixel); HHVM_FE(imagesetstyle); HHVM_FE(imagesetthickness); HHVM_FE(imagesettile); HHVM_FE(imagestring); HHVM_FE(imagestringup); HHVM_FE(imagesx); HHVM_FE(imagesy); HHVM_FE(imagetruecolortopalette); #ifdef ENABLE_GD_TTF HHVM_FE(imagettfbbox); HHVM_FE(imagettftext); #endif HHVM_FE(imagetypes); HHVM_FE(imagewbmp); HHVM_FE(iptcembed); HHVM_FE(iptcparse); HHVM_FE(jpeg2wbmp); HHVM_FE(png2wbmp); HHVM_FE(imagepalettecopy); HHVM_RC_INT(IMG_GIF, IMAGE_TYPE_GIF); HHVM_RC_INT(IMG_JPG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_JPEG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_PNG, IMAGE_TYPE_PNG); HHVM_RC_INT(IMG_WBMP, IMAGE_TYPE_WBMP); HHVM_RC_INT(IMG_XPM, IMAGE_TYPE_XPM); /* special colours for gd */ HHVM_RC_INT(IMG_COLOR_TILED, gdTiled); HHVM_RC_INT(IMG_COLOR_STYLED, gdStyled); HHVM_RC_INT(IMG_COLOR_BRUSHED, gdBrushed); HHVM_RC_INT(IMG_COLOR_STYLEDBRUSHED, gdStyledBrushed); HHVM_RC_INT(IMG_COLOR_TRANSPARENT, gdTransparent); /* for imagefilledarc */ HHVM_RC_INT(IMG_ARC_ROUNDED, gdArc); HHVM_RC_INT(IMG_ARC_PIE, gdPie); HHVM_RC_INT(IMG_ARC_CHORD, gdChord); HHVM_RC_INT(IMG_ARC_NOFILL, gdNoFill); HHVM_RC_INT(IMG_ARC_EDGED, gdEdged); /* GD2 image format types */ HHVM_RC_INT(IMG_GD2_RAW, GD2_FMT_RAW); HHVM_RC_INT(IMG_GD2_COMPRESSED, GD2_FMT_COMPRESSED); HHVM_RC_INT(IMG_FLIP_HORIZONTAL, GD_FLIP_HORINZONTAL); HHVM_RC_INT(IMG_FLIP_VERTICAL, GD_FLIP_VERTICAL); HHVM_RC_INT(IMG_FLIP_BOTH, GD_FLIP_BOTH); HHVM_RC_INT(IMG_EFFECT_REPLACE, gdEffectReplace); HHVM_RC_INT(IMG_EFFECT_ALPHABLEND, gdEffectAlphaBlend); HHVM_RC_INT(IMG_EFFECT_NORMAL, gdEffectNormal); HHVM_RC_INT(IMG_EFFECT_OVERLAY, gdEffectOverlay); HHVM_RC_INT(IMG_CROP_DEFAULT, GD_CROP_DEFAULT); HHVM_RC_INT(IMG_CROP_TRANSPARENT, GD_CROP_TRANSPARENT); HHVM_RC_INT(IMG_CROP_BLACK, GD_CROP_BLACK); HHVM_RC_INT(IMG_CROP_WHITE, GD_CROP_WHITE); HHVM_RC_INT(IMG_CROP_SIDES, GD_CROP_SIDES); HHVM_RC_INT(IMG_CROP_THRESHOLD, GD_CROP_THRESHOLD); HHVM_RC_INT(IMG_BELL, GD_BELL); HHVM_RC_INT(IMG_BESSEL, GD_BESSEL); HHVM_RC_INT(IMG_BILINEAR_FIXED, GD_BILINEAR_FIXED); HHVM_RC_INT(IMG_BICUBIC, GD_BICUBIC); HHVM_RC_INT(IMG_BICUBIC_FIXED, GD_BICUBIC_FIXED); HHVM_RC_INT(IMG_BLACKMAN, GD_BLACKMAN); HHVM_RC_INT(IMG_BOX, GD_BOX); HHVM_RC_INT(IMG_BSPLINE, GD_BSPLINE); HHVM_RC_INT(IMG_CATMULLROM, GD_CATMULLROM); HHVM_RC_INT(IMG_GAUSSIAN, GD_GAUSSIAN); HHVM_RC_INT(IMG_GENERALIZED_CUBIC, GD_GENERALIZED_CUBIC); HHVM_RC_INT(IMG_HERMITE, GD_HERMITE); HHVM_RC_INT(IMG_HAMMING, GD_HAMMING); HHVM_RC_INT(IMG_HANNING, GD_HANNING); HHVM_RC_INT(IMG_MITCHELL, GD_MITCHELL); HHVM_RC_INT(IMG_POWER, GD_POWER); HHVM_RC_INT(IMG_QUADRATIC, GD_QUADRATIC); HHVM_RC_INT(IMG_SINC, GD_SINC); HHVM_RC_INT(IMG_NEAREST_NEIGHBOUR, GD_NEAREST_NEIGHBOUR); HHVM_RC_INT(IMG_WEIGHTED4, GD_WEIGHTED4); HHVM_RC_INT(IMG_TRIANGLE, GD_TRIANGLE); HHVM_RC_INT(IMG_AFFINE_TRANSLATE, GD_AFFINE_TRANSLATE); HHVM_RC_INT(IMG_AFFINE_SCALE, GD_AFFINE_SCALE); HHVM_RC_INT(IMG_AFFINE_ROTATE, GD_AFFINE_ROTATE); HHVM_RC_INT(IMG_AFFINE_SHEAR_HORIZONTAL, GD_AFFINE_SHEAR_HORIZONTAL); HHVM_RC_INT(IMG_AFFINE_SHEAR_VERTICAL, GD_AFFINE_SHEAR_VERTICAL); HHVM_RC_INT(IMG_FILTER_BRIGHTNESS, IMAGE_FILTER_BRIGHTNESS); HHVM_RC_INT(IMG_FILTER_COLORIZE, IMAGE_FILTER_COLORIZE); HHVM_RC_INT(IMG_FILTER_CONTRAST, IMAGE_FILTER_CONTRAST); HHVM_RC_INT(IMG_FILTER_EDGEDETECT, IMAGE_FILTER_EDGEDETECT); HHVM_RC_INT(IMG_FILTER_EMBOSS, IMAGE_FILTER_EMBOSS); HHVM_RC_INT(IMG_FILTER_GAUSSIAN_BLUR, IMAGE_FILTER_GAUSSIAN_BLUR); HHVM_RC_INT(IMG_FILTER_GRAYSCALE, IMAGE_FILTER_GRAYSCALE); HHVM_RC_INT(IMG_FILTER_MEAN_REMOVAL, IMAGE_FILTER_MEAN_REMOVAL); HHVM_RC_INT(IMG_FILTER_NEGATE, IMAGE_FILTER_NEGATE); HHVM_RC_INT(IMG_FILTER_SELECTIVE_BLUR, IMAGE_FILTER_SELECTIVE_BLUR); HHVM_RC_INT(IMG_FILTER_SMOOTH, IMAGE_FILTER_SMOOTH); HHVM_RC_INT(IMG_FILTER_PIXELATE, IMAGE_FILTER_PIXELATE); HHVM_RC_INT(IMAGETYPE_GIF, IMAGE_FILETYPE_GIF); HHVM_RC_INT(IMAGETYPE_JPEG, IMAGE_FILETYPE_JPEG); HHVM_RC_INT(IMAGETYPE_PNG, IMAGE_FILETYPE_PNG); HHVM_RC_INT(IMAGETYPE_SWF, IMAGE_FILETYPE_SWF); HHVM_RC_INT(IMAGETYPE_PSD, IMAGE_FILETYPE_PSD); HHVM_RC_INT(IMAGETYPE_BMP, IMAGE_FILETYPE_BMP); HHVM_RC_INT(IMAGETYPE_TIFF_II, IMAGE_FILETYPE_TIFF_II); HHVM_RC_INT(IMAGETYPE_TIFF_MM, IMAGE_FILETYPE_TIFF_MM); HHVM_RC_INT(IMAGETYPE_JPC, IMAGE_FILETYPE_JPC); HHVM_RC_INT(IMAGETYPE_JP2, IMAGE_FILETYPE_JP2); HHVM_RC_INT(IMAGETYPE_JPX, IMAGE_FILETYPE_JPX); HHVM_RC_INT(IMAGETYPE_JB2, IMAGE_FILETYPE_JB2); HHVM_RC_INT(IMAGETYPE_IFF, IMAGE_FILETYPE_IFF); HHVM_RC_INT(IMAGETYPE_WBMP, IMAGE_FILETYPE_WBMP); HHVM_RC_INT(IMAGETYPE_XBM, IMAGE_FILETYPE_XBM); HHVM_RC_INT(IMAGETYPE_ICO, IMAGE_FILETYPE_ICO); HHVM_RC_INT(IMAGETYPE_UNKNOWN, IMAGE_FILETYPE_UNKNOWN); HHVM_RC_INT(IMAGETYPE_COUNT, IMAGE_FILETYPE_COUNT); HHVM_RC_INT(IMAGETYPE_SWC, IMAGE_FILETYPE_SWC); HHVM_RC_INT(IMAGETYPE_JPEG2000, IMAGE_FILETYPE_JPC); #ifdef GD_VERSION_STRING HHVM_RC_STR(GD_VERSION, GD_VERSION_STRING); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && \ defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) HHVM_RC_INT_SAME(GD_MAJOR_VERSION); HHVM_RC_INT_SAME(GD_MINOR_VERSION); HHVM_RC_INT_SAME(GD_RELEASE_VERSION); HHVM_RC_STR_SAME(GD_EXTRA_VERSION); #endif #ifdef HAVE_GD_PNG HHVM_RC_INT(PNG_NO_FILTER, 0x00); HHVM_RC_INT(PNG_FILTER_NONE, 0x08); HHVM_RC_INT(PNG_FILTER_SUB, 0x10); HHVM_RC_INT(PNG_FILTER_UP, 0x20); HHVM_RC_INT(PNG_FILTER_AVG, 0x40); HHVM_RC_INT(PNG_FILTER_PAETH, 0x80); HHVM_RC_INT(PNG_ALL_FILTERS, 0x08 | 0x10 | 0x20 | 0x40 | 0x80); #endif HHVM_RC_BOOL(GD_BUNDLED, true); loadSystemlib(); } } s_gd_extension; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_844_0
crossvul-cpp_data_good_1380_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/output-file.h" #include "hphp/runtime/base/execution-context.h" #include "hphp/runtime/base/runtime-error.h" namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // constructor and destructor const StaticString s_php_output("php://output"); const StaticString s_php("PHP"); const StaticString s_output("Output"); OutputFile::OutputFile(const String& filename): File(true, s_php, s_output) { if (filename != s_php_output) { raise_fatal_error("not a php://output file "); } setIsLocal(true); } OutputFile::~OutputFile() { OutputFile::closeImpl(); } void OutputFile::sweep() { closeImpl(); File::sweep(); } bool OutputFile::open(const String& /*filename*/, const String& /*mode*/) { raise_fatal_error("cannot open a php://output file "); } bool OutputFile::close() { invokeFiltersOnClose(); return closeImpl(); } bool OutputFile::closeImpl() { *s_pcloseRet = 0; if (!isClosed()) { setIsClosed(true); return true; } return false; } /////////////////////////////////////////////////////////////////////////////// // virtual functions int64_t OutputFile::readImpl(char* /*buffer*/, int64_t /*length*/) { raise_warning("cannot read from a php://output stream"); return 0; } int OutputFile::getc() { raise_warning("cannot read from a php://output stream"); return -1; } int64_t OutputFile::writeImpl(const char *buffer, int64_t length) { assertx(length > 0); if (isClosed()) return 0; g_context->write(buffer, length); return length; } bool OutputFile::seek(int64_t /*offset*/, int /*whence*/ /* = SEEK_SET */) { raise_warning("cannot seek a php://output stream"); return false; } int64_t OutputFile::tell() { raise_warning("cannot tell a php://output stream"); return -1; } bool OutputFile::eof() { return false; } bool OutputFile::rewind() { raise_warning("cannot rewind a php://output stream"); return false; } bool OutputFile::flush() { if (!isClosed()) { g_context->flush(); return true; } return false; } bool OutputFile::truncate(int64_t /*size*/) { raise_warning("cannot truncate a php://output stream"); return false; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_1380_0
crossvul-cpp_data_bad_2812_1
/***************************************************************** | | AP4 - stsz Atoms | | Copyright 2002-2008 Axiomatic Systems, LLC | | | This file is part of Bento4/AP4 (MP4 Atom Processing Library). | | Unless you have obtained Bento4 under a difference license, | this version of Bento4 is Bento4|GPL. | Bento4|GPL 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 2, or (at your option) | any later version. | | Bento4|GPL 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 Bento4|GPL; see the file COPYING. If not, write to the | Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA | 02111-1307, USA. | ****************************************************************/ /*---------------------------------------------------------------------- | includes +---------------------------------------------------------------------*/ #include "Ap4StszAtom.h" #include "Ap4AtomFactory.h" #include "Ap4Utils.h" /*---------------------------------------------------------------------- | dynamic cast support +---------------------------------------------------------------------*/ AP4_DEFINE_DYNAMIC_CAST_ANCHOR(AP4_StszAtom) /*---------------------------------------------------------------------- | AP4_StszAtom::Create +---------------------------------------------------------------------*/ AP4_StszAtom* AP4_StszAtom::Create(AP4_Size size, AP4_ByteStream& stream) { AP4_UI08 version; AP4_UI32 flags; if (AP4_FAILED(AP4_Atom::ReadFullHeader(stream, version, flags))) return NULL; if (version != 0) return NULL; return new AP4_StszAtom(size, version, flags, stream); } /*---------------------------------------------------------------------- | AP4_StszAtom::AP4_StszAtom +---------------------------------------------------------------------*/ AP4_StszAtom::AP4_StszAtom() : AP4_Atom(AP4_ATOM_TYPE_STSZ, AP4_FULL_ATOM_HEADER_SIZE+8, 0, 0), m_SampleSize(0), m_SampleCount(0) { } /*---------------------------------------------------------------------- | AP4_StszAtom::AP4_StszAtom +---------------------------------------------------------------------*/ AP4_StszAtom::AP4_StszAtom(AP4_UI32 size, AP4_UI08 version, AP4_UI32 flags, AP4_ByteStream& stream) : AP4_Atom(AP4_ATOM_TYPE_STSZ, size, version, flags) { stream.ReadUI32(m_SampleSize); stream.ReadUI32(m_SampleCount); if (m_SampleSize == 0) { // means that the samples have different sizes AP4_Cardinal sample_count = m_SampleCount; m_Entries.SetItemCount(sample_count); unsigned char* buffer = new unsigned char[sample_count*4]; AP4_Result result = stream.Read(buffer, sample_count*4); if (AP4_FAILED(result)) { delete[] buffer; return; } for (unsigned int i=0; i<sample_count; i++) { m_Entries[i] = AP4_BytesToUInt32BE(&buffer[i*4]); } delete[] buffer; } } /*---------------------------------------------------------------------- | AP4_StszAtom::WriteFields +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::WriteFields(AP4_ByteStream& stream) { AP4_Result result; // sample size result = stream.WriteUI32(m_SampleSize); if (AP4_FAILED(result)) return result; // sample count result = stream.WriteUI32(m_SampleCount); if (AP4_FAILED(result)) return result; // entries if needed (the samples have different sizes) if (m_SampleSize == 0) { for (AP4_UI32 i=0; i<m_SampleCount; i++) { result = stream.WriteUI32(m_Entries[i]); if (AP4_FAILED(result)) return result; } } return result; } /*---------------------------------------------------------------------- | AP4_StszAtom::GetSampleCount +---------------------------------------------------------------------*/ AP4_UI32 AP4_StszAtom::GetSampleCount() { return m_SampleCount; } /*---------------------------------------------------------------------- | AP4_StszAtom::GetSampleSize +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::GetSampleSize(AP4_Ordinal sample, AP4_Size& sample_size) { // check the sample index if (sample > m_SampleCount || sample == 0) { sample_size = 0; return AP4_ERROR_OUT_OF_RANGE; } else { // find the size if (m_SampleSize != 0) { // constant size sample_size = m_SampleSize; } else { sample_size = m_Entries[sample - 1]; } return AP4_SUCCESS; } } /*---------------------------------------------------------------------- | AP4_StszAtom::SetSampleSize +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::SetSampleSize(AP4_Ordinal sample, AP4_Size sample_size) { // check the sample index if (sample > m_SampleCount || sample == 0) { return AP4_ERROR_OUT_OF_RANGE; } else { if (m_Entries.ItemCount() == 0) { // all samples must have the same size if (sample_size != m_SampleSize) { // not the same if (sample == 1) { // if this is the first sample, update the global size m_SampleSize = sample_size; return AP4_SUCCESS; } else { // can't have different sizes return AP4_ERROR_INVALID_PARAMETERS; } } } else { // each sample has a different size m_Entries[sample - 1] = sample_size; } return AP4_SUCCESS; } } /*---------------------------------------------------------------------- | AP4_StszAtom::AddEntry +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::AddEntry(AP4_UI32 size) { m_Entries.Append(size); m_SampleCount++; m_Size32 += 4; return AP4_SUCCESS; } /*---------------------------------------------------------------------- | AP4_StszAtom::InspectFields +---------------------------------------------------------------------*/ AP4_Result AP4_StszAtom::InspectFields(AP4_AtomInspector& inspector) { inspector.AddField("sample_size", m_SampleSize); inspector.AddField("sample_count", m_Entries.ItemCount()); if (inspector.GetVerbosity() >= 2) { char header[32]; for (AP4_Ordinal i=0; i<m_Entries.ItemCount(); i++) { AP4_FormatString(header, sizeof(header), "entry %8d", i); inspector.AddField(header, m_Entries[i]); } } return AP4_SUCCESS; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_2812_1
crossvul-cpp_data_good_3390_1
// zinflate.cpp - originally written and placed in the public domain by Wei Dai // This is a complete reimplementation of the DEFLATE decompression algorithm. // It should not be affected by any security vulnerabilities in the zlib // compression library. In particular it is not affected by the double free bug // (http://www.kb.cert.org/vuls/id/368819). #include "pch.h" #include "zinflate.h" #include "secblock.h" #include "smartptr.h" NAMESPACE_BEGIN(CryptoPP) struct CodeLessThan { inline bool operator()(CryptoPP::HuffmanDecoder::code_t lhs, const CryptoPP::HuffmanDecoder::CodeInfo &rhs) {return lhs < rhs.code;} // needed for MSVC .NET 2005 inline bool operator()(const CryptoPP::HuffmanDecoder::CodeInfo &lhs, const CryptoPP::HuffmanDecoder::CodeInfo &rhs) {return lhs.code < rhs.code;} }; inline bool LowFirstBitReader::FillBuffer(unsigned int length) { while (m_bitsBuffered < length) { byte b; if (!m_store.Get(b)) return false; m_buffer |= (unsigned long)b << m_bitsBuffered; m_bitsBuffered += 8; } CRYPTOPP_ASSERT(m_bitsBuffered <= sizeof(unsigned long)*8); return true; } inline unsigned long LowFirstBitReader::PeekBits(unsigned int length) { bool result = FillBuffer(length); CRYPTOPP_UNUSED(result); CRYPTOPP_ASSERT(result); return m_buffer & (((unsigned long)1 << length) - 1); } inline void LowFirstBitReader::SkipBits(unsigned int length) { CRYPTOPP_ASSERT(m_bitsBuffered >= length); m_buffer >>= length; m_bitsBuffered -= length; } inline unsigned long LowFirstBitReader::GetBits(unsigned int length) { unsigned long result = PeekBits(length); SkipBits(length); return result; } inline HuffmanDecoder::code_t HuffmanDecoder::NormalizeCode(HuffmanDecoder::code_t code, unsigned int codeBits) { return code << (MAX_CODE_BITS - codeBits); } void HuffmanDecoder::Initialize(const unsigned int *codeBits, unsigned int nCodes) { // the Huffman codes are represented in 3 ways in this code: // // 1. most significant code bit (i.e. top of code tree) in the least significant bit position // 2. most significant code bit (i.e. top of code tree) in the most significant bit position // 3. most significant code bit (i.e. top of code tree) in n-th least significant bit position, // where n is the maximum code length for this code tree // // (1) is the way the codes come in from the deflate stream // (2) is used to sort codes so they can be binary searched // (3) is used in this function to compute codes from code lengths // // a code in representation (2) is called "normalized" here // The BitReverse() function is used to convert between (1) and (2) // The NormalizeCode() function is used to convert from (3) to (2) if (nCodes == 0) throw Err("null code"); m_maxCodeBits = *std::max_element(codeBits, codeBits+nCodes); if (m_maxCodeBits > MAX_CODE_BITS) throw Err("code length exceeds maximum"); if (m_maxCodeBits == 0) throw Err("null code"); // count number of codes of each length SecBlockWithHint<unsigned int, 15+1> blCount(m_maxCodeBits+1); std::fill(blCount.begin(), blCount.end(), 0); unsigned int i; for (i=0; i<nCodes; i++) blCount[codeBits[i]]++; // compute the starting code of each length code_t code = 0; SecBlockWithHint<code_t, 15+1> nextCode(m_maxCodeBits+1); nextCode[1] = 0; for (i=2; i<=m_maxCodeBits; i++) { // compute this while checking for overflow: code = (code + blCount[i-1]) << 1 if (code > code + blCount[i-1]) throw Err("codes oversubscribed"); code += blCount[i-1]; if (code > (code << 1)) throw Err("codes oversubscribed"); code <<= 1; nextCode[i] = code; } // MAX_CODE_BITS is 32, m_maxCodeBits may be smaller. const word64 shiftedMaxCode = ((word64)1 << m_maxCodeBits); if (code > shiftedMaxCode - blCount[m_maxCodeBits]) throw Err("codes oversubscribed"); else if (m_maxCodeBits != 1 && code < shiftedMaxCode - blCount[m_maxCodeBits]) throw Err("codes incomplete"); // compute a vector of <code, length, value> triples sorted by code m_codeToValue.resize(nCodes - blCount[0]); unsigned int j=0; for (i=0; i<nCodes; i++) { unsigned int len = codeBits[i]; if (len != 0) { code = NormalizeCode(nextCode[len]++, len); m_codeToValue[j].code = code; m_codeToValue[j].len = len; m_codeToValue[j].value = i; j++; } } std::sort(m_codeToValue.begin(), m_codeToValue.end()); // initialize the decoding cache m_cacheBits = STDMIN(9U, m_maxCodeBits); m_cacheMask = (1 << m_cacheBits) - 1; m_normalizedCacheMask = NormalizeCode(m_cacheMask, m_cacheBits); CRYPTOPP_ASSERT(m_normalizedCacheMask == BitReverse(m_cacheMask)); const word64 shiftedCache = ((word64)1 << m_cacheBits); CRYPTOPP_ASSERT(shiftedCache <= SIZE_MAX); if (m_cache.size() != shiftedCache) m_cache.resize((size_t)shiftedCache); for (i=0; i<m_cache.size(); i++) m_cache[i].type = 0; } void HuffmanDecoder::FillCacheEntry(LookupEntry &entry, code_t normalizedCode) const { normalizedCode &= m_normalizedCacheMask; const CodeInfo &codeInfo = *(std::upper_bound(m_codeToValue.begin(), m_codeToValue.end(), normalizedCode, CodeLessThan())-1); if (codeInfo.len <= m_cacheBits) { entry.type = 1; entry.value = codeInfo.value; entry.len = codeInfo.len; } else { entry.begin = &codeInfo; const CodeInfo *last = & *(std::upper_bound(m_codeToValue.begin(), m_codeToValue.end(), normalizedCode + ~m_normalizedCacheMask, CodeLessThan())-1); if (codeInfo.len == last->len) { entry.type = 2; entry.len = codeInfo.len; } else { entry.type = 3; entry.end = last+1; } } } inline unsigned int HuffmanDecoder::Decode(code_t code, /* out */ value_t &value) const { CRYPTOPP_ASSERT(m_codeToValue.size() > 0); LookupEntry &entry = m_cache[code & m_cacheMask]; code_t normalizedCode = 0; if (entry.type != 1) normalizedCode = BitReverse(code); if (entry.type == 0) FillCacheEntry(entry, normalizedCode); if (entry.type == 1) { value = entry.value; return entry.len; } else { const CodeInfo &codeInfo = (entry.type == 2) ? entry.begin[(normalizedCode << m_cacheBits) >> (MAX_CODE_BITS - (entry.len - m_cacheBits))] : *(std::upper_bound(entry.begin, entry.end, normalizedCode, CodeLessThan())-1); value = codeInfo.value; return codeInfo.len; } } bool HuffmanDecoder::Decode(LowFirstBitReader &reader, value_t &value) const { bool result = reader.FillBuffer(m_maxCodeBits); CRYPTOPP_UNUSED(result); // CRYPTOPP_ASSERT(result); unsigned int codeBits = Decode(reader.PeekBuffer(), value); if (codeBits > reader.BitsBuffered()) return false; reader.SkipBits(codeBits); return true; } // ************************************************************* Inflator::Inflator(BufferedTransformation *attachment, bool repeat, int propagation) : AutoSignaling<Filter>(propagation) , m_state(PRE_STREAM), m_repeat(repeat), m_eof(0), m_wrappedAround(0) , m_blockType(0xff), m_storedLen(0xffff), m_nextDecode(), m_literal(0) , m_distance(0), m_reader(m_inQueue), m_current(0), m_lastFlush(0) { Detach(attachment); } void Inflator::IsolatedInitialize(const NameValuePairs &parameters) { m_state = PRE_STREAM; parameters.GetValue("Repeat", m_repeat); m_inQueue.Clear(); m_reader.SkipBits(m_reader.BitsBuffered()); } void Inflator::OutputByte(byte b) { m_window[m_current++] = b; if (m_current == m_window.size()) { ProcessDecompressedData(m_window + m_lastFlush, m_window.size() - m_lastFlush); m_lastFlush = 0; m_current = 0; m_wrappedAround = true; } } void Inflator::OutputString(const byte *string, size_t length) { while (length) { size_t len = UnsignedMin(length, m_window.size() - m_current); memcpy(m_window + m_current, string, len); m_current += len; if (m_current == m_window.size()) { ProcessDecompressedData(m_window + m_lastFlush, m_window.size() - m_lastFlush); m_lastFlush = 0; m_current = 0; m_wrappedAround = true; } string += len; length -= len; } } void Inflator::OutputPast(unsigned int length, unsigned int distance) { size_t start; if (distance <= m_current) start = m_current - distance; else if (m_wrappedAround && distance <= m_window.size()) start = m_current + m_window.size() - distance; else throw BadBlockErr(); if (start + length > m_window.size()) { for (; start < m_window.size(); start++, length--) OutputByte(m_window[start]); start = 0; } if (start + length > m_current || m_current + length >= m_window.size()) { while (length--) OutputByte(m_window[start++]); } else { memcpy(m_window + m_current, m_window + start, length); m_current += length; } } size_t Inflator::Put2(const byte *inString, size_t length, int messageEnd, bool blocking) { if (!blocking) throw BlockingInputOnly("Inflator"); LazyPutter lp(m_inQueue, inString, length); ProcessInput(messageEnd != 0); if (messageEnd) if (!(m_state == PRE_STREAM || m_state == AFTER_END)) throw UnexpectedEndErr(); Output(0, NULLPTR, 0, messageEnd, blocking); return 0; } bool Inflator::IsolatedFlush(bool hardFlush, bool blocking) { if (!blocking) throw BlockingInputOnly("Inflator"); if (hardFlush) ProcessInput(true); FlushOutput(); return false; } void Inflator::ProcessInput(bool flush) { while (true) { switch (m_state) { case PRE_STREAM: if (!flush && m_inQueue.CurrentSize() < MaxPrestreamHeaderSize()) return; ProcessPrestreamHeader(); m_state = WAIT_HEADER; m_wrappedAround = false; m_current = 0; m_lastFlush = 0; m_window.New(((size_t) 1) << GetLog2WindowSize()); break; case WAIT_HEADER: { // maximum number of bytes before actual compressed data starts const size_t MAX_HEADER_SIZE = BitsToBytes(3+5+5+4+19*7+286*15+19*15); if (m_inQueue.CurrentSize() < (flush ? 1 : MAX_HEADER_SIZE)) return; DecodeHeader(); break; } case DECODING_BODY: if (!DecodeBody()) return; break; case POST_STREAM: if (!flush && m_inQueue.CurrentSize() < MaxPoststreamTailSize()) return; ProcessPoststreamTail(); m_state = m_repeat ? PRE_STREAM : AFTER_END; Output(0, NULLPTR, 0, GetAutoSignalPropagation(), true); // TODO: non-blocking if (m_inQueue.IsEmpty()) return; break; case AFTER_END: m_inQueue.TransferTo(*AttachedTransformation()); return; } } } void Inflator::DecodeHeader() { if (!m_reader.FillBuffer(3)) throw UnexpectedEndErr(); m_eof = m_reader.GetBits(1) != 0; m_blockType = (byte)m_reader.GetBits(2); switch (m_blockType) { case 0: // stored { m_reader.SkipBits(m_reader.BitsBuffered() % 8); if (!m_reader.FillBuffer(32)) throw UnexpectedEndErr(); m_storedLen = (word16)m_reader.GetBits(16); word16 nlen = (word16)m_reader.GetBits(16); if (nlen != (word16)~m_storedLen) throw BadBlockErr(); break; } case 1: // fixed codes m_nextDecode = LITERAL; break; case 2: // dynamic codes { if (!m_reader.FillBuffer(5+5+4)) throw UnexpectedEndErr(); unsigned int hlit = m_reader.GetBits(5); unsigned int hdist = m_reader.GetBits(5); unsigned int hclen = m_reader.GetBits(4); FixedSizeSecBlock<unsigned int, 286+32> codeLengths; unsigned int i; static const unsigned int border[] = { // Order of the bit length code lengths 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; std::fill(codeLengths.begin(), codeLengths+19, 0); for (i=0; i<hclen+4; i++) codeLengths[border[i]] = m_reader.GetBits(3); try { HuffmanDecoder codeLengthDecoder(codeLengths, 19); for (i = 0; i < hlit+257+hdist+1; ) { unsigned int k = 0, count = 0, repeater = 0; bool result = codeLengthDecoder.Decode(m_reader, k); if (!result) throw UnexpectedEndErr(); if (k <= 15) { count = 1; repeater = k; } else switch (k) { case 16: if (!m_reader.FillBuffer(2)) throw UnexpectedEndErr(); count = 3 + m_reader.GetBits(2); if (i == 0) throw BadBlockErr(); repeater = codeLengths[i-1]; break; case 17: if (!m_reader.FillBuffer(3)) throw UnexpectedEndErr(); count = 3 + m_reader.GetBits(3); repeater = 0; break; case 18: if (!m_reader.FillBuffer(7)) throw UnexpectedEndErr(); count = 11 + m_reader.GetBits(7); repeater = 0; break; } if (i + count > hlit+257+hdist+1) throw BadBlockErr(); std::fill(codeLengths + i, codeLengths + i + count, repeater); i += count; } m_dynamicLiteralDecoder.Initialize(codeLengths, hlit+257); if (hdist == 0 && codeLengths[hlit+257] == 0) { if (hlit != 0) // a single zero distance code length means all literals throw BadBlockErr(); } else m_dynamicDistanceDecoder.Initialize(codeLengths+hlit+257, hdist+1); m_nextDecode = LITERAL; } catch (HuffmanDecoder::Err &) { throw BadBlockErr(); } break; } default: throw BadBlockErr(); // reserved block type } m_state = DECODING_BODY; } bool Inflator::DecodeBody() { bool blockEnd = false; switch (m_blockType) { case 0: // stored CRYPTOPP_ASSERT(m_reader.BitsBuffered() == 0); while (!m_inQueue.IsEmpty() && !blockEnd) { size_t size; const byte *block = m_inQueue.Spy(size); size = UnsignedMin(m_storedLen, size); CRYPTOPP_ASSERT(size <= 0xffff); OutputString(block, size); m_inQueue.Skip(size); m_storedLen = m_storedLen - (word16)size; if (m_storedLen == 0) blockEnd = true; } break; case 1: // fixed codes case 2: // dynamic codes static const unsigned int lengthStarts[] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; static const unsigned int lengthExtraBits[] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0}; static const unsigned int distanceStarts[] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577}; static const unsigned int distanceExtraBits[] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; const HuffmanDecoder& literalDecoder = GetLiteralDecoder(); const HuffmanDecoder& distanceDecoder = GetDistanceDecoder(); switch (m_nextDecode) { case LITERAL: while (true) { if (!literalDecoder.Decode(m_reader, m_literal)) { m_nextDecode = LITERAL; break; } if (m_literal < 256) OutputByte((byte)m_literal); else if (m_literal == 256) // end of block { blockEnd = true; break; } else { if (m_literal > 285) throw BadBlockErr(); unsigned int bits; case LENGTH_BITS: bits = lengthExtraBits[m_literal-257]; if (!m_reader.FillBuffer(bits)) { m_nextDecode = LENGTH_BITS; break; } m_literal = m_reader.GetBits(bits) + lengthStarts[m_literal-257]; case DISTANCE: if (!distanceDecoder.Decode(m_reader, m_distance)) { m_nextDecode = DISTANCE; break; } case DISTANCE_BITS: // TODO: this surfaced during fuzzing. What do we do??? CRYPTOPP_ASSERT(m_distance < COUNTOF(distanceExtraBits)); if (m_distance >= COUNTOF(distanceExtraBits)) throw BadDistanceErr(); bits = distanceExtraBits[m_distance]; if (!m_reader.FillBuffer(bits)) { m_nextDecode = DISTANCE_BITS; break; } // TODO: this surfaced during fuzzing. What do we do??? CRYPTOPP_ASSERT(m_distance < COUNTOF(distanceStarts)); if (m_distance >= COUNTOF(distanceStarts)) throw BadDistanceErr(); m_distance = m_reader.GetBits(bits) + distanceStarts[m_distance]; OutputPast(m_literal, m_distance); } } break; default: CRYPTOPP_ASSERT(0); } } if (blockEnd) { if (m_eof) { FlushOutput(); m_reader.SkipBits(m_reader.BitsBuffered()%8); if (m_reader.BitsBuffered()) { // undo too much lookahead SecBlockWithHint<byte, 4> buffer(m_reader.BitsBuffered() / 8); for (unsigned int i=0; i<buffer.size(); i++) buffer[i] = (byte)m_reader.GetBits(8); m_inQueue.Unget(buffer, buffer.size()); } m_state = POST_STREAM; } else m_state = WAIT_HEADER; } return blockEnd; } void Inflator::FlushOutput() { if (m_state != PRE_STREAM) { CRYPTOPP_ASSERT(m_current >= m_lastFlush); ProcessDecompressedData(m_window + m_lastFlush, m_current - m_lastFlush); m_lastFlush = m_current; } } struct NewFixedLiteralDecoder { HuffmanDecoder * operator()() const { unsigned int codeLengths[288]; std::fill(codeLengths + 0, codeLengths + 144, 8); std::fill(codeLengths + 144, codeLengths + 256, 9); std::fill(codeLengths + 256, codeLengths + 280, 7); std::fill(codeLengths + 280, codeLengths + 288, 8); member_ptr<HuffmanDecoder> pDecoder(new HuffmanDecoder); pDecoder->Initialize(codeLengths, 288); return pDecoder.release(); } }; struct NewFixedDistanceDecoder { HuffmanDecoder * operator()() const { unsigned int codeLengths[32]; std::fill(codeLengths + 0, codeLengths + 32, 5); member_ptr<HuffmanDecoder> pDecoder(new HuffmanDecoder); pDecoder->Initialize(codeLengths, 32); return pDecoder.release(); } }; const HuffmanDecoder& Inflator::GetLiteralDecoder() const { return m_blockType == 1 ? Singleton<HuffmanDecoder, NewFixedLiteralDecoder>().Ref() : m_dynamicLiteralDecoder; } const HuffmanDecoder& Inflator::GetDistanceDecoder() const { return m_blockType == 1 ? Singleton<HuffmanDecoder, NewFixedDistanceDecoder>().Ref() : m_dynamicDistanceDecoder; } NAMESPACE_END
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_3390_1
crossvul-cpp_data_bad_94_0
/* Copyright 2008-2018 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol(int row, int col) { static const char filter[16][16] = { {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2}, {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1}, {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1}, {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3}, {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2}, {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0}, {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1}, {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}}; if (filters == 1) return filter[(row + top_margin) & 15][(col + left_margin) & 15]; if (filters == 9) return xtrans[(row + 6) % 6][(col + 6) % 6]; return FC(row, col); } #if !defined(__FreeBSD__) static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return (p ? p - s : n); } /* add OS X version check here ?? */ #define strnlen(a, b) local_strnlen(a, b) #endif #ifdef LIBRAW_LIBRARY_BUILD static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten}; static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int); static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300, 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300, 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000}; static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1, LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11, LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35, LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83}; static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int); static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather, LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW}; static int Oly_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Tungsten, 3000, 0x100, 3300, 0x100, 3600, 0x100, 3900, LIBRAW_WBI_FL_W, 4000, 0x100, 4300, LIBRAW_WBI_FL_D, 4500, 0x100, 4800, LIBRAW_WBI_FineWeather, 5300, LIBRAW_WBI_Cloudy, 6000, LIBRAW_WBI_FL_N, 6600, LIBRAW_WBI_Shade, 7500, LIBRAW_WBI_Custom1, 0, LIBRAW_WBI_Custom2, 0, LIBRAW_WBI_Custom3, 0, LIBRAW_WBI_Custom4, 0}; static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash}; static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L}; static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int); static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf, len, 1); buf[len - 1] = 0; return r; } #define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp) #endif #if !defined(__GLIBC__) && !defined(__FreeBSD__) char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp(c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr(char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf, sizeof(buf) - 1) ushort CLASS sget2(uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define nonDNG 0 #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords, int maxlen) { line[maxlen - 1] = 0; char *p = line; int nwords = 0; while (1) { while (isspace(*p)) p++; if (*p == '\0') return nwords; words[nwords++] = p; while (!isspace(*p) && *p != '\0') p++; if (*p == '\0') return nwords; *p++ = '\0'; if (nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f) { if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data) { if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03" "\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5" "\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53" "\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea" "\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3" "\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7" "\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63" "\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd" "\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = {0xff, 0xff}; fread(str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4(uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = {0xff, 0xff, 0xff, 0xff}; fread(str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float(int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal(int type) { union { char c[8]; double d; } u, v; int i, rev; switch (type) { case 3: return (unsigned short)get2(); case 4: return (unsigned int)get4(); case 5: u.d = (unsigned int)get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short)get2(); case 9: return (signed int)get4(); case 10: u.d = (signed int)get4(); v.d = (signed int)get4(); return u.d / (v.d ? v.d : 1); case 11: return int_to_float(get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i = 0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts(ushort *pixel, unsigned count) { if (fread(pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)pixel, (char *)pixel, count * 2); } void CLASS cubic_spline(const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len); if (!A) return; A[0] = (float *)(A + 2 * len); for (i = 1; i < 2 * len; i++) A[i] = A[0] + 2 * len * i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len - 1; i > 0; i--) { b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); d[i - 1] = x[i] - x[i - 1]; } for (i = 1; i < len - 1; i++) { A[i][i] = 2 * (d[i - 1] + d[i]); if (i > 1) { A[i][i - 1] = d[i - 1]; A[i - 1][i] = d[i - 1]; } A[i][len - 1] = 6 * (b[i + 1] - b[i]); } for (i = 1; i < len - 2; i++) { float v = A[i + 1][i] / A[i][i]; for (j = 1; j <= len - 1; j++) A[i + 1][j] -= v * A[i][j]; } for (i = len - 2; i > 0; i--) { float acc = 0; for (j = i; j <= len - 2; j++) acc += A[i][j] * c[j]; c[i] = (A[i][len - 1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len - 1; j++) { if (x[j] <= x_out && x_out <= x[j + 1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v + ((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free(A); } void CLASS canon_600_fixed_wb(int temp) { static const short mul[4][5] = { {667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}}; int lo, hi, i; float frac = 0; for (lo = 4; --lo;) if (*mul[lo] <= temp) break; for (hi = 0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i = 1; i < 5; i++) pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color(int ratio[2], int mar) { int clipped = 0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar * 4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = {0, 0}; int test[8], total[2][8], ratio[2][2], stat[2]; memset(&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row = 14; row < height - 14; row += 4) for (col = 10; col < width; col += 2) { for (i = 0; i < 8; i++) test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1)); for (i = 0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i = 0; i < 4; i++) if (abs(test[i] - test[i + 4]) > 50) goto next; for (i = 0; i < 2; i++) { for (j = 0; j < 4; j += 2) ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j]; stat[i] = canon_600_color(ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i = 0; i < 2; i++) if (stat[i]) for (j = 0; j < 2; j++) test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10; for (i = 0; i < 8; i++) total[st][i] += test[i]; count[st]++; next:; } if (count[0] | count[1]) { st = count[0] * 200 < count[1]; for (i = 0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409}, {-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007}, {-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528}, {-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}}; int t = 0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t = 1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t = 3; else if (yc <= 2) t = 4; } if (flash_used) t = 5; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow = row = 0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row * raw_width; for (dp = data; dp < data + 1120; dp += 10, pix += 8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6); } if ((row += 2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}}; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { if ((val = BAYER(row, col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row, col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row = 0; row < 100; row++) { fseek(ifp, row * 3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff(int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf = 0; static int vbits = 0, reset = 0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar)c; vbits += 8; } c = bitbuf << (32 - vbits) >> (32 - nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar)huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n, 0) #define gethuff(h) getbithuff(*h, h + 1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort *CLASS make_decoder_ref(const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max = 16; max && !count[max]; max--) ; huff = (ushort *)calloc(1 + (1 << max), sizeof *huff); merror(huff, "make_decoder()"); huff[0] = max; for (h = len = 1; len <= max; len++) for (i = 0; i < count[len]; i++, ++*source) for (j = 0; j < 1 << (max - len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); } void CLASS crw_init_tables(unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff}, {0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff}, {0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff}, }; static const uchar second_tree[3][180] = { {0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04, 0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0, 0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29, 0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9, 0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91, 0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4, 0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7, 0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64, 0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3, 0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff}, {0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03, 0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32, 0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61, 0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59, 0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56, 0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85, 0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82, 0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9, 0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64, 0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff}, {0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05, 0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22, 0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58, 0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48, 0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88, 0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94, 0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a, 0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62, 0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1, 0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}}; if (table > 2) table = 2; huff[0] = make_decoder(first_tree[table]); huff[1] = make_decoder(second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret = 1, i; fseek(ifp, 0, SEEK_SET); fread(test, 1, sizeof test, ifp); for (i = 540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i + 1]) return 1; ret = 0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2]; crw_init_tables(tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; nblocks = MIN(8, raw_height - row) * raw_width >> 6; for (block = 0; block < nblocks; block++) { memset(diffbuf, 0, sizeof diffbuf); for (i = 0; i < 64; i++) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i = 0; i < 64; i++) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek(ifp, 26 + row * raw_width / 4, SEEK_SET); for (prow = pixel, i = 0; i < raw_width * 2; i++) { c = fgetc(ifp); for (r = 0; r < 8; r += 2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free(huff[c]); throw; } #endif FORC(2) free(huff[c]); } int CLASS ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end(struct jhead *jh) { int c; FORC4 if (jh->free[c]) free(jh->free[c]); free(jh->row); } int CLASS ljpeg_diff(ushort *huff) { int len, diff; if (!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; return diff; } ushort *CLASS ljpeg_row(int jrow, struct jhead *jh) { int col, c, diff, pred, spred = 0; ushort mark = 0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits - 1); if (jrow) { fseek(ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1); for (col = 0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff(jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0; struct jhead jh; ushort *rp; if (!ljpeg_start(&jh, 0)) return; if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if (jh.clrs == 4 && jwide >= raw_width * 2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2; for (jcol = 0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow * jwide + jcol; i = jidx / (cr2_slice[1] * raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1] * raw_height); row = jidx / cr2_slice[1 + j]; col = jidx % cr2_slice[1 + j] + i * cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--, raw_width); if (row > raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 3); #endif if ((unsigned)row < raw_height) RAW(row, col) = val; if (++col >= raw_width) col = (row++, 0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif ljpeg_end(&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp = 0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c; int v[3] = {0, 0, 0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start(&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if (load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol = slice = 0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width - 1) ecol = raw_width & -2; for (row = 0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short(*)[4])image + row * width; for (col = scol; col < ecol; col += 2, jcol += jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *)ljpeg_row(jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC(jh.clrs - 2) { ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else #endif { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 16384; ip[col][2] = rp[jcol + jh.clrs - 1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end(&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp = model2; *cp && !isdigit(*cp); cp++) ; sscanf(cp, "%d.%d.%d", v, v + 1, v + 2); ver = (v[0] * 1000 + v[1]) * 1000 + v[2]; hue = (jh.sraw + 1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short(*)[4])image; rp = ip[0]; for (row = 0; row < height; row++, ip += width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col = 0; col < width; col += 2) for (c = 1; c < 3; c++) if (row == height - 1) { ip[col][c] = ip[col - width][c]; } else { ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1; } } for (col = 1; col < width; col += 2) for (c = 1; c < 3; c++) if (col == width - 1) ip[col][c] = ip[col - 1][c]; else ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)) #endif for (; rp < ip[0]; rp += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14); pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14); pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } height = saved_h; width = saved_w; #endif ljpeg_end(&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row, col) = curve[**rp]; *rp += tiff_samples; } else { #ifdef LIBRAW_LIBRARY_BUILD if (row < raw_height && col < raw_width) FORC(tiff_samples) image[row * raw_width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #else if (row < height && col < width) FORC(tiff_samples) image[row * width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #endif } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct(struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = {0}; static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; if (!cs[0]) FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2; memset(work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0]; for (i = 1; i < 64; i++) { len = gethuff(jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len - 1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c]; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); if (!ljpeg_start(&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN(is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow = 0; jrow + 7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol = 0; jcol + 7 < jh.wide; jcol += 8) { ljpeg_idct(&jh); rp = jh.idct; row = trow + jcol / tile_width + jrow * 2; col = tcol + jcol % tile_width; for (i = 0; i < 16; i += 2) for (j = 0; j < 8; j++) adobe_copy_pixel(row + i, col + j, &rp); } } break; case 0xc3: for (row = col = jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); for (jcol = 0; jcol < jwide; jcol++) { adobe_copy_pixel(trow + row, tcol + col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif fseek(ifp, save + 4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end(&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel); merror(pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts(pixel, raw_width * tiff_samples); else { getbits(-1); for (col = 0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp = pixel, col = 0; col < raw_width; col++) adobe_copy_pixel(row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek(ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek(ifp, data_offset, SEEK_SET); getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; int bypp = tiff_bps <= 8 ? 1 : 2; int bufsize = width * 3 * bypp; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for (int row = 0; row < raw_height; row++) { int red = fread(buf, 1, bufsize, ifp); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (tiff_bps <= 8) for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } else for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */ 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */ 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}, {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */ 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}, {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */ 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */ 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}, {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */ 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff; fseek(ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek(ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts(vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize - 1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i = 0; i < csize; i++) curve[i * step] = get2(); for (i = 0; i < max; i++) curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; fseek(ifp, meta_offset + 562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts(curve, max = csize); while (curve[max - 2] == curve[max - 1]) max--; huff = make_decoder(nikon_tree[tree]); fseek(ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min = row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free(huff); huff = make_decoder(nikon_tree[tree + 1]); max += (min = 16) << 1; } for (col = 0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len - shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(huff); throw; } #endif free(huff); } void CLASS nikon_yuv_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf = 0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; } for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8; FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705 * yuv[3]; rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3]; rgb[2] = yuv[b] + 1.732446 * yuv[2]; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = {0x00, 0x55, 0xaa, 0xff}; memset(histo, 0, sizeof histo); fseek(ifp, -2000, SEEK_END); for (i = 0; i < 2000; i++) histo[fgetc(ifp)]++; for (i = 0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek(ifp, 0, SEEK_SET); for (i = 0; i < 1024; i++) { fread(t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { {0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}}; fseek(ifp, 3072, SEEK_SET); fread(dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i = 0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy(make, table[i].t_make); strcpy(model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek(ifp, -sizeof tail, SEEK_END); fread(tail, 1, sizeof tail, ifp); for (nz = i = 0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)malloc(thumb_length); merror(thumb, "ppm_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread(thumb, 1, thumb_length, ifp); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)calloc(thumb_length, 2); merror(thumb, "ppm16_thumb()"); read_shorts((ushort *)thumb, thumb_length); for (i = 0; i < thumb_length; i++) thumb[i] = ((ushort *)thumb)[i] >> 8; fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = {"012", "102"}; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width * thumb_height; thumb = (char *)calloc(colors, thumb_length); merror(thumb, "layer_thumb()"); fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread(thumb, thumb_length, colors, ifp); for (i = 0; i < thumb_length; i++) FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp); free(thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *)calloc(thumb_length, 2); merror(thumb, "rollei_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts(thumb, thumb_length); for (i = 0; i < thumb_length; i++) { putc(thumb[i] << 3, ofp); putc(thumb[i] >> 5 << 2, ofp); putc(thumb[i] >> 11 << 3, ofp); } free(thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width > 32767 || raw_height > 32767) throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixel = raw_width*(raw_height+7); isix = raw_width * raw_height * 5 / 8; while (fread(pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i = 0; i < 10; i += 2) { todo[i] = iten++; todo[i + 1] = pixel[i] << 8 | pixel[i + 1]; buffer = pixel[i] >> 2 | buffer << 6; } for (; i < 16; i += 2) { todo[i] = isix++; todo[i + 1] = buffer >> (14 - i) * 5; } for (i = 0; i < 16; i += 2) if(todo[i] < maxpixel) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); else derror(); } maximum = 0x3ff; } int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; } void CLASS phase_one_flat_field(int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts(head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *)calloc(nc * wide, sizeof *mrow); merror(mrow, "phase_one_flat_field()"); for (y = 0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) { num = is_float ? getreal(11) : get2() / 32768.0; if (y == 0) mrow[c * wide + x] = num; else mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5]; } if (y == 0) continue; rend = head[1] + y * head[5]; for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++) { for (x = 1; x < wide; x++) { for (c = 0; c < nc; c += 2) { mult[c] = mrow[c * wide + x - 1]; mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4]; } cend = head[0] + x * head[4]; for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++) { c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0; if (!(c & 1)) { c = RAW(row, col) * mult[c]; RAW(row, col) = LIM(c, 0, 65535); } for (c = 0; c < nc; c += 2) mult[c] += mult[c + 1]; } } for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) mrow[c * wide + x] += mrow[(c + 1) * wide + x]; } } free(mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff = INT_MAX, off_412 = 0; /* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2}, {0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Phase One correction...\n")); #endif fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i = 0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i = 0; i < 0x10000; i++) { num = (poly[5] * i + poly[3]) * i + poly[1]; curve[i] = LIM(num, 0, 65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i = 0; i < 4; i++) poly[i] = getreal(11); for (i = 0; i < 0x10000; i++) { for (num = 0, j = 4; j--;) num = num * i + poly[j]; curve[i] = LIM(num + i, 0, 65535); } apply: /* apply to whole image */ for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1) * ph1.split_col; col < raw_width; col++) RAW(row, col) = curve[RAW(row, col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row = 0; row < raw_height; row++) if (FC(row - top_margin, col - left_margin) == 1) { for (sum = i = 0; i < 4; i++) sum += val[i] = raw(row + dir[i][0], col + dir[i][1]); for (max = i = 0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row, col) = (sum - val[max]) / 3.0 + 0.5; } else { for (sum = 0, i = 8; i < 12; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row - top_margin, col - left_margin) != 1) * 4; for (sum = 0, i = j; i < j + 8; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field(1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field(0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field(0, 4); } else if (tag == 0x412) { fseek(ifp, 36, SEEK_CUR); diff = abs(get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1 + i] = lc[qr][qc][i]; cf[1 + i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = {{1, 1}, {1, 1}}; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col); RAW(row, col) = LIM(i, 0, 65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1 + i] = ref[i]; cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek(ifp, save, SEEK_SET); } if (off_412) { fseek(ifp, off_412, SEEK_SET); for (i = 0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6); merror(yval[0], "phase_one_correct()"); yval[1] = (float *)(yval[0] + head[1] * head[3]); xval[0] = (ushort *)(yval[1] + head[2] * head[4]); xval[1] = (ushort *)(xval[0] + head[1] * head[3]); get2(); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) yval[i][j] = getreal(11); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) xval[i][j] = get2(); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { cfrac = (float)col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row, col) * 0.5; for (i = cip; i < cip + 2; i++) { for (k = j = 0; j < head[1]; j++) if (num < xval[0][k = head[1] * i + j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]); mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac); } i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row, col) = LIM(i, 0, 65535); } } free(yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek(ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555 : 0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()"); if (ph1.black_col) { fseek(ifp, ph1.black_col, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2); } if (ph1.black_row) { fseek(ifp, ph1.black_row, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2); } } #endif fseek(ifp, data_offset, SEEK_SET); read_shorts(raw_image, raw_width * raw_height); if (ph1.format) for (i = 0; i < raw_width * raw_height; i += 2) { a = raw_image[i + 0] ^ akey; b = raw_image[i + 1] ^ bkey; raw_image[i + 0] = (a & t_mask) | (b & ~t_mask); raw_image[i + 1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff(int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf = 0; static int vbits = 0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64 - vbits) >> (64 - nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar)huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n, 0) #define ph1_huff(h) ph1_bithuff(*h, h + 1) void CLASS phase_one_load_raw_c() { static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13}; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short(*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2); merror(pixel, "phase_one_load_raw_c()"); offset = (int *)(pixel + raw_width); fseek(ifp, strip_offset, SEEK_SET); for (row = 0; row < raw_height; row++) offset[row] = get4(); c_black = (short(*)[2])(offset + raw_height); fseek(ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts((ushort *)c_black[0], raw_height * 2); r_black = c_black + raw_height; fseek(ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts((ushort *)r_black[0], raw_width * 2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort)); } #endif for (i = 0; i < 256; i++) curve[i] = i * i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col = 0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i = 0; i < 2; i++) { for (j = 0; j < 5 && !ph1_bits(1); j++) ; if (j--) len[i] = length[j * 2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col = 0; col < raw_width; col++) { int shift = ph1.format == 8 ? 0 : 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row, col) = i; } #else if (ph1.format == 8) memmove(&RAW(row, 0), &pixel[0], raw_width * 2); else for (col = 0; col < raw_width; col++) RAW(row, col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start(&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *)calloc(raw_width, 3 * sizeof **back); merror(back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c * raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c + 3) & 3] = back[c]; for (col = 0; col < raw_width; col += 2) { for (s = 0; s < tiff_samples * 2; s += 2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s + c] = ph1_bits(len[c]); if ((diff[s + c] & (1 << (len[c] - 1))) == 0) diff[s + c] -= (1 << len[c]) - 1; if (diff[s + c] == 65535) diff[s + c] = -32768; } } for (s = col; s < col + 2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s - 2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s] / 2 - back[0][s - 2] / 2; break; } f = (row & 1) * 3 ^ ((col + s) & 1); FORC(tiff_samples) { pred += diff[(s & 1) * tiff_samples + c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row, s) = upix; if (image) { urow = row - top_margin + (c & 1); ucol = col - left_margin - ((c >> 1) & 1); ip = &image[urow * width + ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(back[4]); ljpeg_end(&jh); throw; } #endif free(back[4]); ljpeg_end(&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel = 0; unsigned tile = 0, r, c, row, col; if (!filters || !raw_image) { #ifdef LIBRAW_LIBRARY_BUILD if(!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r = 0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek(ifp, data_offset + 4 * tile++, SEEK_SET); fseek(ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters && raw_image) pixel = raw_image + r * raw_width; read_shorts(pixel, raw_width); if (!filters && image && (row = r - top_margin) < height) for (col = 0; col < width; col++) image[row * width + col][c] = pixel[col + left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free(pixel); } } void CLASS unpacked_load_raw() { int row, col, bits = 0; while (1 << ++bits < maximum) ; read_shorts(raw_image, raw_width * raw_height); if (maximum < 0xffff || load_flags) for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < maximum) ; for (row = raw_height - 1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM(shot_select, 1, 4) - 1; fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot = 0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); for (row = 0; row < raw_height; row++) { read_shorts(pixel, raw_width); if ((r = row - top_margin - (shot >> 1 & 1)) >= height) continue; for (col = 0; col < raw_width; col++) { if ((c = col - left_margin - (shot & 1)) >= width) continue; image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short)); merror(buf, "imacon_full_load_raw"); #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf, width * 3); unsigned short(*rowp)[4] = &image[row * width]; for (col = 0; col < width; col++) { rowp[col][0] = buf[col * 3]; rowp[col][1] = buf[col * 3 + 1]; rowp[col][2] = buf[col * 3 + 2]; rowp[col][3] = 0; } #else for (col = 0; col < width; col++) read_shorts(image[row * width + col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf = 0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height + 1) >> 1; for (irow = 0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits = 0, tiff_compress) fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET); else { fseek(ifp, 0, SEEK_END); fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col = 0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); RAW(row, col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom() { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek(ifp, 0xb0 - 0x20, SEEK_CUR); fread(&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = {0, 0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *)malloc(dwide * 2); merror(data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } #endif free(data); maximum = 0x3ff; if (strncmp(make, "OmniVision", 10)) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1)); merror(words, "canon_rmf_load_raw"); #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words, sizeof(int), raw_width / 3, ifp); for (col = 0; col < raw_width - 2; col += 3) { bits = words[col / 3]; FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #else for (col = 0; col < raw_width - 2; col += 3) { bits = get4(); FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits(int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4002]; static int vbits; #endif int byte; if (!nbits) return vbits = 0; if (!vbits) { fread(buf + load_flags, 1, 0x4000 - load_flags, ifp); fread(buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n = 0] = 0xc0c; for (i = 12; i--;) FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i; fseek(ifp, 7, SEEK_CUR); getbits(-1); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(acarry, 0, sizeof acarry); for (col = 0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++) ; low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12, huff)) == 12) high = getbits(16 - nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row, col - 2); else if (col < 2) pred = RAW(row - 2, col); else { w = RAW(row, col - 2); n = RAW(row - 2, col); nw = RAW(row - 2, col - 2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w - nw) > 32 || ABS(n - nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w - nw) > ABS(n - nw) ? w : n; } if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow = 0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col = 0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1; RAW(row, 1) = pixel[1] << 1; RAW(row, 1533) = pixel[765] << 1; } else for (col = row & 1; col < 1534; col += 2) RAW(row, col) = pixel[col / 2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89}; static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8}, {-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}}; static const short t_curve[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99, 101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261, 265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357, 361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453, 457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620, 631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866, 878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023}; int rb, row, col, sharp, val = 0; #ifdef LIBRAW_LIBRARY_BUILD if(width>640 || height > 480) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif getbits(-1); memset(pixel, 0x80, sizeof pixel); for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 2 + (row & 1); col < width + 2; col += 2) { val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val, 0, 255); if (col < 4) pixel[row][col - 2] = pixel[row + 1][~row & 1] = val; if (row == 2) pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val; } pixel[row][col] = val; } for (rb = 0; rb < 2; rb++) for (row = 2 + rb; row < height + 2; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) + ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val, 0, 255); if (row < 4) pixel[row - 2][col + 2] = val; if (col < 4) pixel[row + 2][col - 2] = val; } } for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100; pixel[row][col] = LIM(val, 0, 255); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = t_curve[pixel[row + 2][col + 2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char)getbithuff(8, huff[tree])) #define FORYX \ for (y = 1; y < 3; y++) \ for (x = col + 1; x >= col; x--) #define PREDICTOR \ (c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4) #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC optimize("no-aggressive-loop-optimizations") #endif #endif void CLASS kodak_radc_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD // All kodak radc images are 768x512 if (width > 768 || raw_width > 768 || height > 512 || raw_height > 512) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif static const signed char src[] = { 1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6, 8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2, 4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3, 3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7, 5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5, 3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0, 2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2, 2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55, 6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37}; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = {16, 16, 16}, mul[3], buf[3][3][386]; static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383}; for (i = 2; i < 12; i += 2) for (c = pt[i - 2]; c <= pt[i]; c++) curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5; for (s = i = 0; i < sizeof src; i += 2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1); getbits(-1); for (i = 0; i < sizeof(buf) / sizeof(short); i++) ((short *)buf)[i] = 2048; for (row = 0; row < height; row += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if (!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10 : 12; x = ~((~0u) << (s - 1)); val <<= 12 - s; for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r = 0; r <= !c; r++) { buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7; for (tree = 1, col = width / 2; col > 0;) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y = 0; y < 2; y++) for (x = 0; x < width / 2; x++) { val = (buf[c][y + 1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val; else RAW(row + r * 2 + y, x * 2 + y) = val; } memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c); } } for (y = row; y < row + 4; y++) for (x = 0; x < width; x++) if ((x + y) & 1) { r = x ? x - 1 : x + 1; s = x + 1 < width ? x + 1 : x - 1; val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2; if (val < 0) val = 0; RAW(y, x) = val; } } for (i = 0; i < height * width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread(jpeg_buffer, 1, 4096, ifp); swab(jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; int row, col; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress(&cinfo); longjmp(failure, 3); } buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if (data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf, "kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char *)malloc(width * 3); jpeg_create_decompress(&cinfo); merror(pixel_buf, "kodak_jpeg_load_raw"); fread(jpg_buf, data_size, 1, ifp); swab((char *)jpg_buf, (char *)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } } catch (...) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve(double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; unsigned sorder = order, ntags, opcode, deg, i, j, c; unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek(ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek(ifp, get4(), SEEK_CUR); continue; } fseek(ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek(ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i = 0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i = 0; i < 256; i++) { for (tot = j = 0; j <= deg; j++) tot += coeff[j] * pow(i / 255.0, (int)j); cur[c][i] = tot * 0xffff; } } order = sorder; } else { gamma_curve(1 / 2.4, 12.92, 1, 255); FORC3 memcpy(cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); while (trow < raw_height) { fseek(ifp, save += 4, SEEK_SET); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src(&cinfo, ifp); #endif jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < cinfo.output_width && tcol + col < width; col++) { FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { jpeg_destroy_decompress(&cinfo); throw; } #endif jpeg_abort_decompress(&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress(&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = {162, 192, 187, 92}; static const int add[4] = {0, 636, 424, 212}; uchar pixel[848]; int row, shift, col; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col = 0; col < width; col++) RAW(row, col) = (ushort)pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *)calloc(raw_width, sizeof *pixel); merror(pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, raw_width, ifp) < raw_width) derror(); for (col = 0; col < raw_width; col++) RAW(row, col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel); merror(pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek(ifp, raw_width * 32, SEEK_CUR); for (col = 0; col < width; col++) { y = pixel[col * 2]; cb = pixel[(col * 2 & -4) | 1] - 128; cr = pixel[(col * 2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel); merror(pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread(pixel, raw_width, 3, ifp) < 3) derror(); for (col = 0; col < width; col++) { y = pixel[width * 2 * (row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2) + 1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { {0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder(kodak_tree[c]); ns = (raw_height + 63) >> 5; pixel = (uchar *)malloc(raw_width * 32 + ns * 4); merror(pixel, "kodak_262_load_raw()"); strip = (int *)(pixel + raw_width * 32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek(ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col = 0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi - 2 : pi - raw_width - 1; pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi - 2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff(huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row, col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); FORC(2) free(huff[c]); } int CLASS kodak_65000_decode(short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf = 0; int save, bits = 0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i = 0; i < bsize; i += 2) { c = fgetc(ifp); if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12) { fseek(ifp, save, SEEK_SET); for (i = 0; i < bsize; i += 8) { read_shorts(raw, 6); out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j = 0; j < 6; j++) out[i + 2 + j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i = 0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j = 0; j < 32; j += 8) bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8)); bits += 32; } diff = bitbuf & (0xffff >> (16 - len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* 264 looks enough */ int row, col, len, pred[2], ret, i; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { pred[0] = pred[1] = 0; len = MIN(256, width - col); ret = kodak_65000_decode(buf, len); for (i = 0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if (idx >= 0 && idx < 0xffff) { if ((RAW(row, col + i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10; for (row = 0; row < height; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 128) { len = MIN(128, width - col); kodak_65000_decode(buf, len * 3); y[0][1] = y[1][1] = cb = cr = 0; for (bp = buf, i = 0; i < len; i += 2, bp += 2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) { if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits) derror(); ip = image[(row + j) * width + col + i + k]; FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif short buf[768], *bp; int row, col, len, c, i, rgb[3], ret; ushort *ip = image[0]; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { len = MIN(256, width - col); ret = kodak_65000_decode(buf, len * 3); memset(rgb, 0, sizeof rgb); for (bp = buf, i = 0; i < len; i++, ip += 4) #ifdef LIBRAW_LIBRARY_BUILD if (load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD if (!image) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif int row, col; colors = thumb_misc >> 5; for (row = 0; row < height; row++) for (col = 0; col < width; col++) read_shorts(image[row * width + col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt(unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p = 0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31; for (p = 4; p < 127; p++) pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31; for (p = 0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek(ifp, 200896, SEEK_SET); fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek(ifp, 164600, SEEK_SET); fread(head, 1, 40, ifp); sony_decrypt((unsigned *)head, 10, 1, key); for (i = 26; i-- > 22;) key = key << 8 | head[i]; fseek(ifp, data_offset, SEEK_SET); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; if (fread(pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key); for (col = 0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809, 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201}; int i, c, n, col, row, sum = 0; huff[0] = 15; for (n = i = 0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--;) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row = 0; row < raw_height + 1; row += 2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row, col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *)malloc(raw_width + 1); merror(data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread(data, 1, raw_width, ifp); for (dp = data, col = 0; col < raw_width - 30; dp += 16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++) ; #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i] = 0; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i = 0; i < 16; i++, col += 2) { unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2]; unsigned step = 1 << sh; RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr ? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000) : 0; } } else { for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1]; } #else for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1 : 31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum = 10000; #endif free(data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; #ifdef LIBRAW_LIBRARY_BUILD if(raw_width> 32768 || raw_height > 32768) // definitely too much for old samsung throw LIBRAW_EXCEPTION_IO_BADFILE; #endif unsigned maxpixels = raw_width*(raw_height+7); order = 0x4949; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, strip_offset + row * 4, SEEK_SET); fseek(ifp, data_offset + get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7 : 4; for (col = 0; col < raw_width; col += 16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; unsigned idest = RAWINDEX(row, col + c); unsigned isrc = (dir ? RAWINDEX(row + (~c | -2), col + c) : col ? RAWINDEX(row, col + (c | -2)) : 0); if(idest < maxpixels && isrc < maxpixels) // less than zero is handled by unsigned conversion RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); else derror(); if (c == 14) c = -1; } } } for (row = 0; row < raw_height - 1; row += 2) for (col = 0; col < raw_width - 1; col += 2) SWAP(RAW(row, col + 1), RAW(row + 1, col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709, 0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402}; ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n = i = 0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek(ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(), get2()); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4; prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green prow[~row & 1] = &RAW(row - 2, 0); // red and blue for (tab = 0; tab + 15 < raw_width; tab += 16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4 * ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row, tab - 2 + (col & 1)) : init) : (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1; diff = ph1_bits(i = len[c >> 2]); if (diff >> (i - 1)) diff -= 1 << i; diff = diff * (mag * 2 + 1) + mag; RAW(row, col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment(unsigned seg[2][2], int holes) { uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {3, 3, 0, 0, 63, 47, 31, 15, 0}}; int low, high = 0xff, carry = 0, nbits = 8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[] = {0, 0}; ushort data = 0, range = 0; fseek(ifp, seg[0][1] + 1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width * raw_height) seg[1][0] = raw_width * raw_height; for (pix = seg[0][0]; pix < seg[1][0]; pix++) { for (s = 0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits - 1)) - 1)) << 1) | ((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4); for (bin = 0; hist[s][bin + 5] > count; bin++) ; low = hist[s][bin + 5] * (high >> 4) >> 2; if (bin) high = hist[s][bin + 4] * (high >> 4) >> 2; high -= low; for (nbits = 0; high << nbits < 128; nbits++) ; range = (range + low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next + 1) & hist[s][0]; hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1) { if (bin < hist[s][1]) for (i = bin; i < hist[s][1]; i++) hist[s][i + 5]--; else if (next <= bin) for (i = hist[s][1]; i < bin; i++) hist[s][i + 5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if (pix >= raw_width * raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek(ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment(seg, 0); } int CLASS median4(int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i = 1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes(int holes) { int row, col, val[4]; for (row = 2; row < height - 2; row++) { if (!HOLE(row)) continue; for (col = 1; col < width - 1; col += 4) { val[0] = RAW(row - 1, col - 1); val[1] = RAW(row - 1, col + 1); val[2] = RAW(row + 1, col - 1); val[3] = RAW(row + 1, col + 1); RAW(row, col) = median4(val); } for (col = 2; col < width - 2; col += 4) if (HOLE(row - 2) || HOLE(row + 2)) RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1; else { val[0] = RAW(row, col - 2); val[1] = RAW(row, col + 2); val[2] = RAW(row - 2, col); val[3] = RAW(row + 2, col); RAW(row, col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek(ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar)fgetc(ifp); fseek(ifp, offset, SEEK_SET); for (i = 0; i < nseg * 2; i++) ((unsigned *)seg)[i] = get4() + data_offset * (i & 1); fseek(ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek(ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i = 0; i < nseg; i++) smal_decode_segment(seg + i, holes); if (holes) fill_holes(holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen(ifname, "rb"); #else in = (jas_stream_t *)ifp->make_jas_stream(); if (!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek(in, data_offset + 20, SEEK_SET); jimg = jas_image_decode(in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp(failure, 3); #else if (!jimg) { jas_stream_close(in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create(height / 2, width / 2); merror(jmat, "redcine_load_raw()"); img = (ushort *)calloc((height + 2), (width + 2) * 2); merror(img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat); data = jas_matrix_getref(jmat, 0, 0); for (row = c >> 1; row < height; row += 2) for (col = c & 1; col < width; col += 2) img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2]; } for (col = 1; col <= width; col++) { img[col] = img[2 * (width + 2) + col]; img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col]; } for (row = 0; row < height + 2; row++) { img[row * (width + 2)] = img[row * (width + 2) + 2]; img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3]; } for (row = 1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1)); for (; col <= width; col += 2, pix += 2) { c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c, 0, 4095); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag = true; } #endif free(img); jas_matrix_destroy(jmat); jas_image_destroy(jimg); jas_stream_close(in); #ifdef LIBRAW_LIBRARY_BUILD if (fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width * 2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row = 0; row < raw_height - top_margin * 2; row++) { for (col = 0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < height && c < width) BAYER(r, c) = RAW(row + top_margin, col + left_margin); } } } else { for (row = 0; row < height; row++) for (col = 0; col < width; col++) BAYER2(row, col) = RAW(row + top_margin, col + left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin + height; mask[0][3] += left_margin; mask[1][1] += left_margin + width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset(mblack, 0, sizeof mblack); for (zero = m = 0; m < 8; m++) for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++) for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++) { c = FC(row - top_margin, col - left_margin); mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)]; mblack[4 + c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4 + c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2); #endif for (row = 0; row < height; row++) for (col = 0; col < width; col++) if (BAYER(row, col) == 0) { tot = n = 0; for (r = row - 2; r <= row + 2; r++) for (c = col - 2; c <= col + 2; c++) if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c)) tot += (n++, BAYER(r, c)); if (n) BAYER(row, col) = tot / n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2); #endif } static const uchar xlat[2][256] = { {0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3, 0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d, 0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b, 0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b, 0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95, 0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b, 0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d, 0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43, 0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f, 0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad, 0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3, 0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17, 0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07, 0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7}, {0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9, 0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68, 0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95, 0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68, 0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42, 0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca, 0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87, 0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45, 0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94, 0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26, 0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe, 0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25, 0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65, 0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}}; void CLASS gamma_curve(double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2] = {0, 0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0) { for (i = 0; i < 48; i++) { g[2] = (bnd[0] + bnd[1]) / 2; if (g[0]) bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2]; else bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1 / g[0] - 1); } if (g[0]) g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1; else g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1; if (!mode--) { memcpy(gamm, g, sizeof gamm); return; } for (i = 0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double)i / imax) < 1) curve[i] = 0x10000 * (mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1)) : (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2])))); } } void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) work[i][j] = j == i + 3; for (j = 0; j < 3; j++) for (k = 0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i = 0; i < 3; i++) { num = work[i][i]; for (j = 0; j < 6; j++) if(fabs(num)>0.00001f) work[i][j] /= num; for (k = 0; k < 3; k++) { if (k == i) continue; num = work[k][i]; for (j = 0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i = 0; i < size; i++) for (j = 0; j < 3; j++) for (out[i][j] = k = 0; k < 3; k++) out[i][j] += work[j][k + 3] * in[i][k]; } void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j = 0; j < 3; j++) for (cam_rgb[i][j] = k = 0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i = 0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if (num > 0.00001) { for (j = 0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j = 0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse(cam_rgb, inverse, colors); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin {0.377, 0.345, 35.8}, // Light Skin {0.247, 0.251, 19.3}, // Blue Sky {0.337, 0.422, 13.3}, // Foliage {0.265, 0.240, 24.3}, // Blue Flower {0.261, 0.343, 43.1}, // Bluish Green {0.506, 0.407, 30.1}, // Orange {0.211, 0.175, 12.0}, // Purplish Blue {0.453, 0.306, 19.8}, // Moderate Red {0.285, 0.202, 6.6}, // Purple {0.380, 0.489, 44.3}, // Yellow Green {0.473, 0.438, 43.1}, // Orange Yellow {0.187, 0.129, 6.1}, // Blue {0.305, 0.478, 23.4}, // Green {0.539, 0.313, 12.0}, // Red {0.448, 0.470, 59.1}, // Yellow {0.364, 0.233, 19.8}, // Magenta {0.196, 0.252, 19.8}, // Cyan {0.310, 0.316, 90.0}, // White {0.310, 0.316, 59.1}, // Neutral 8 {0.310, 0.316, 36.2}, // Neutral 6.5 {0.310, 0.316, 19.8}, // Neutral 5 {0.310, 0.316, 9.0}, // Neutral 3.5 {0.310, 0.316, 3.1}}; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset(gmb_cam, 0, sizeof gmb_cam); for (sq = 0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++) for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++) { c = FC(row, col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row, col); BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse(gmb_xyz, inverse, NSQ); for (pass = 0; pass < 2; pass++) { for (raw_color = i = 0; i < colors; i++) for (j = 0; j < 3; j++) for (cam_xyz[i][j] = k = 0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff(rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq = 0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf(" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5)); puts(" } },"); } #undef NSQ } #endif void CLASS hat_transform(float *temp, float *base, int st, int size, int sc) { int i; for (i = 0; i < sc; i++) temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)]; for (; i + sc < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)]; for (; i < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size) #endif { temp = (float *)malloc((iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #endif // green equilibration void CLASS green_matching() { int i, j; double m1, m2, c1, c2; int o1_1, o1_2, o1_3, o1_4; int o2_1, o2_2, o2_3, o2_4; ushort(*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if (half_size || shrink) return; if (FC(oj, oi) != 3) oj++; if (FC(oj, oi) != 3) oi++; if (FC(oj, oi) != 3) oj--; img = (ushort(*)[4])calloc(height * width, sizeof *image); merror(img, "green_matching()"); memcpy(img, image, height * width * sizeof *image); for (j = oj; j < height - margin; j += 2) for (i = oi; i < width - margin; i += 2) { o1_1 = img[(j - 1) * width + i - 1][1]; o1_2 = img[(j - 1) * width + i + 1][1]; o1_3 = img[(j + 1) * width + i - 1][1]; o1_4 = img[(j + 1) * width + i + 1][1]; o2_1 = img[(j - 2) * width + i][3]; o2_2 = img[(j + 2) * width + i][3]; o2_3 = img[j * width + i - 2][3]; o2_4 = img[j * width + i + 2][3]; m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0; m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0; c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) + abs(o1_2 - o1_4)) / 6.0; c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) + abs(o2_2 - o2_4)) / 6.0; if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr)) { f = image[j * width + i][3] * m1 / m2; image[j * width + i][3] = f > 0xffff ? 0xffff : f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img = 0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2); #endif if (user_mul[0]) memcpy(pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset(dsum, 0, sizeof dsum); bottom = MIN(greybox[1] + greybox[3], height); right = MIN(greybox[0] + greybox[2], width); for (row = greybox[1]; row < bottom; row += 8) for (col = greybox[0]; col < right; col += 8) { memset(sum, 0, sizeof sum); for (y = row; y < row + 8 && y < bottom; y++) for (x = col; x < col + 8 && x < right; x++) FORC4 { if (filters) { c = fcol(y, x); val = BAYER2(y, x); } else val = image[y * width + x][c]; if (val > maximum - 25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c + 4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block:; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset(sum, 0, sizeof sum); for (row = 0; row < 8; row++) for (col = 0; col < 8; col++) { c = FC(row, col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c + 4]++; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy(pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f) { for (c = 0; c < 3; c++) pre_mul[c] /= cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf(stderr, " %f", pre_mul[c]); fputc('\n', stderr); } #endif if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1) { FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight * iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i = 0; i < size * 4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Correcting chromatic aberration...\n")); #endif for (c = 0; c < 4; c += 2) { if (aber[c] == 1) continue; img = (ushort *)malloc(size * sizeof *img); merror(img, "scale_colors()"); for (i = 0; i < size; i++) img[i] = image[i][c]; for (row = 0; row < iheight; row++) { ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5; if (ur > iheight - 2) continue; fr -= ur; for (col = 0; col < iwidth; col++) { uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5; if (uc > iwidth - 2) continue; fc -= uc; pix = img + ur * iwidth + uc; image[row * iwidth + col][c] = (pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2); #endif } void CLASS pre_interpolate() { ushort(*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row = 0; row < 3; row++) for (col = 1; col < 4; col++) if (!(image[row * width + col][0] | image[row * width + col][2])) goto break2; break2: for (; row < height; row += 3) for (col = (col - 1) % 3 + 1; col < width - 1; col += 3) { img = image + row * width + col; for (c = 0; c < 3; c += 2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort(*)[4])calloc(height, width * sizeof *img); merror(img, "pre_interpolate()"); for (row = 0; row < height; row++) for (col = 0; col < width; col++) { c = fcol(row, col); img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c]; } free(image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1, 0) >> 1; row < height; row += 2) for (col = FC(row, 1) & 1; col < width; col += 2) image[row * width + col][1] = image[row * width + col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2); #endif } void CLASS border_interpolate(int border) { unsigned row, col, y, x, f, c, sum[8]; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { if (col == border && row >= border && row < height - border) col = width - border; memset(sum, 0, sizeof sum); for (y = row - 1; y != row + 2; y++) for (x = col - 1; x != col + 2; x++) if (y < height && x < width) { f = fcol(y, x); sum[f] += image[y * width + x][f]; sum[f + 4]++; } f = fcol(row, col); FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4]; } } void CLASS lin_interpolate_loop(int code[16][16][32], int size) { int row; for (row = 1; row < height - 1; row++) { int col, *ip; ushort *pix; for (col = 1; col < width - 1; col++) { int i; int sum[4]; pix = image[row * width + col]; ip = code[row % size][col % size]; memset(sum, 0, sizeof sum); for (i = *ip++; i--; ip += 3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i = colors; --i; ip += 2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size = 16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row = 0; row < size; row++) for (col = 0; col < size; col++) { ip = code[row][col] + 1; f = fcol(row, col); memset(sum, 0, sizeof sum); for (y = -1; y <= 1; y++) for (x = -1; x <= 1; x++) { shift = (y == 0) + (x == 0); color = fcol(row + y, col + x); if (color == f) continue; *ip++ = (width * y + x) * 4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c] > 0 ? 256 / sum[c] : 0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #endif lin_interpolate_loop(code, size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02, -2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02, -2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06, -2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128, -1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120, -1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11, -1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40, -1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10, -1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10, -1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128, +0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40, +0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08, +0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30, +0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40, +0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128, +1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10}, chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1}; ushort(*brow[5])[4], *pix; int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *)calloc(prow * pcol, 1280); merror(ip, "vng_interpolate()"); for (row = 0; row < prow; row++) /* Precalculate for VNG */ for (col = 0; col < pcol; col++) { code[row][col] = ip; for (cp = terms, t = 0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row + y1, col + x1); if (fcol(row + y2, col + x2) != color) continue; diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1; if (abs(y1 - y2) == diag && abs(x1 - x2) == diag) continue; *ip++ = (y1 * width + x1) * 4 + color; *ip++ = (y2 * width + x2) * 4 + color; *ip++ = weight; for (g = 0; g < 8; g++) if (grads & 1 << g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp = chood, g = 0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y * width + x) * 4; color = fcol(row, col); if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color) *ip++ = (y * width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow); merror(brow[4], "vng_interpolate()"); for (row = 0; row < 3; row++) brow[row] = brow[4] + row * width; for (row = 2; row < height - 2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if (!((row - 2) % 256)) RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1); #endif for (col = 2; col < width - 2; col++) { pix = image[row * width + col]; ip = code[row % prow][col % pcol]; memset(gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g = 1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy(brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset(sum, 0, sizeof sum); color = fcol(row, col); for (num = g = 0; g < 8; g++, ip += 2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); for (g = 0; g < 4; g++) brow[(g - 1) & 3] = brow[g]; } memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image); free(brow[4]); free(code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = {1, width, -1, -width, 1}; int row, col, diff[2], guess[2], c, d, i; ushort(*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 3; row < height - 3; row++) for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c]; diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 + (ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0] + guess[1]) >> 2); } } void CLASS cielab(ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if (cbrt[0] < -1.0f) #endif for (i = 0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f; } for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (xyz_cam[i][j] = k = 0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int)xyz[0])]; xyz[1] = cbrt[CLIP((int)xyz[1])]; xyz[2] = cbrt[CLIP((int)xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate(int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4] = {0, 0, 0, 0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1}, patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0}, {0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}}, dir[4] = {1, TS, TS + 1, TS - 1}; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][3], (*lix)[3]; float(*drv)[TS][TS], diff[6], tr; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if (width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row, col)]++; if (cstat[0] < 6 || cstat[0] > 10 || cstat[1] < 16 || cstat[1] > 24 || cstat[2] < 6 || cstat[2] > 10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 2; k++) for (int l = 0; l < 8; l++) allhex[i][j][k][l] = 32700; #endif cielab(0, 0); ndir = 4 << (passes > 1); buffer = (char *)malloc(TS * TS * (ndir * 11 + 6)); merror(buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6)); drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6)); homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6)); int minv = 0, maxv = 0, minh = 0, maxh = 0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) for (ng = d = 0; d < 10; d += 2) { g = fcol(row, col) == 1; if (fcol(row + orth[d], col + orth[d + 2]) == 1) ng = 0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g + 1) FORC(8) { v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1]; h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1]; minv = MIN(v, minv); maxv = MAX(v, maxv); minh = MIN(v, minh); maxh = MAX(v, maxh); allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width; allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 2; k++) for (int l = 0; l < 8; l++) if (allhex[i][j][k][l] > maxh + maxv * width + 1 || allhex[i][j][k][l] < minh + minv * width - 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row = 2; row < height - 2; row++) for (min = ~(max = 0), col = 2; col < width - 2; col++) { if (fcol(row, col) == 1 && (min = ~(max = 0))) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row - sgrow) % 3) { case 1: if (row < height - 3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if (retrycount++ > width * height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top = 3; top < height - 19; top += TS - 16) for (left = 3; left < width - 19; left += TS - 16) { mrow = MIN(top + TS, height - 3); mcol = MIN(left + TS, width - 3); for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) memcpy(rgb[0][row - top][col - left], image[row * width + col], 6); FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]); color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]); FORC(2) color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] + 33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]); FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]); } for (pass = 0; pass < passes; pass++) { if (pass == 1) memcpy(rgb += 4, buffer, 4 * sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row = top + 2; row < mrow - 2; row++) for (col = left + 2; col < mcol - 2; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][1]; for (d = 3; d < 6; d++) { rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left]; val = rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f]; rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3) for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3) { rix = &rgb[0][row - top][col - left]; h = fcol(row, col + 1); memset(diff, 0, sizeof diff); for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2) { for (c = 0; c < 2; c++, h ^= 2) { g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1]; color[h][d] = g + rix[i << c][h] + rix[-i << c][h]; if (d > 1) diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d - 1] < diff[d]) FORC(2) color[c * 2][d] = color[c * 2][d - 1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2); rix += TS * TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row = top + 3; row < mrow - 3; row++) for (col = left + 3; col < mcol - 3; col++) { if ((f = 2 - fcol(row, col)) == 1) continue; rix = &rgb[0][row - top][col - left]; c = (row - sgrow) % 3 ? TS : 1; h = 3 * (c ^ TS ^ 1); for (d = 0; d < 4; d++, rix += TS * TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) < 2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1]))) ? c : h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row = top + 2; row < mrow - 2; row++) if ((row - sgrow) % 3) for (col = left + 2; col < mcol - 2; col++) if ((col - sgcol) % 3) { rix = &rgb[0][row - top][col - left]; hex = allhex[row % 3][col % 3][1]; for (d = 0; d < ndir; d += 2, rix += TS * TS) if (hex[d] + hex[d + 1]) { g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3); } else { g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2); } } } rgb = (ushort(*)[TS][TS][3])buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d = 0; d < ndir; d++) { for (row = 2; row < mrow - 2; row++) for (col = 2; col < mcol - 2; col++) cielab(rgb[d][row][col], lab[row][col]); for (f = dir[d & 3], row = 3; row < mrow - 3; row++) for (col = 3; col < mcol - 3; col++) { lix = &lab[row][col]; g = 2 * lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) + SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir * TS * TS); for (row = 4; row < mrow - 4; row++) for (col = 4; col < mcol - 4; col++) { for (tr = FLT_MAX, d = 0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d = 0; d < ndir; d++) for (v = -1; v <= 1; v++) for (h = -1; h <= 1; h++) if (drv[d][row + v][col + h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height - top < TS + 4) mrow = height - top + 2; if (width - left < TS + 4) mcol = width - left + 2; for (row = MIN(top, 8); row < mrow - 8; row++) for (col = MIN(left, 8); col < mcol - 8; col++) { for (d = 0; d < ndir; d++) for (hm[d] = 0, v = -2; v <= 2; v++) for (h = -2; h <= 2; h++) hm[d] += homo[d][row + v][col + h]; for (d = 0; d < ndir - 4; d++) if (hm[d] < hm[d + 4]) hm[d] = 0; else if (hm[d] > hm[d + 4]) hm[d + 4] = 0; for (max = hm[0], d = 1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset(avg, 0, sizeof avg); for (d = 0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort(*pix)[4]; const int rowlimit = MIN(top + TS, height - 2); const int collimit = MIN(left + TS, width - 2); for (row = top; row < rowlimit; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < collimit; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort(*pix)[4]; ushort(*rix)[3]; short(*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4 * width; const unsigned rowlimit = MIN(top + TS - 1, height - 3); const unsigned collimit = MIN(left + TS - 1, width - 3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top + 1; row < rowlimit; row++) { pix = image + row * width + left; rix = &inout_rgb[row - top][0]; lix = &out_lab[row - top][0]; for (col = left + 1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row + 1, col); t1 = 2 - c; val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1); } else { t1 = -4 + c; /* -4+c: pixel of color c to the left */ t2 = 4 + c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short(*lix)[3]; short(*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = {-1, 1, -TS, TS}; const int rowlimit = MIN(top + TS - 2, height - 4); const int collimit = MIN(left + TS - 2, width - 4); int homogeneity; char(*homogeneity_map_p)[2]; memset(out_homogeneity_map, 0, 2 * TS * TS); for (row = top + 2; row < rowlimit; row++) { tr = row - top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction = 0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col = left + 2; col < collimit; col++) { tc = col - left; homogeneity_map_p++; for (direction = 0; direction < 2; direction++) { lix = ++lixs[direction]; for (i = 0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (direction = 0; direction < 2; direction++) { homogeneity = 0; for (i = 0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top + TS - 3, height - 5); const int collimit = MIN(left + TS - 3, width - 5); ushort(*pix)[4]; ushort(*rix[2])[3]; for (row = top + 3; row < rowlimit; row++) { tr = row - top; pix = &image[row * width + left + 2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col = left + 3; col < collimit; col++) { tc = col - left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction = 0; direction < 2; direction++) { hm[direction] = 0; for (i = tr - 1; i <= tr + 1; i++) { for (j = tc - 1; j <= tc + 1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4], r; char *buffer; ushort(*rgb)[TS][TS][3]; short(*lab)[TS][TS][3]; char(*homo)[TS][2]; int terminate_flag = 0; cielab(0, 0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag) #endif #endif { buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */ merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][2])(buffer + 24 * TS * TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top = 2; top < height - 5; top += TS - 6) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if (0 == omp_get_thread_num()) #endif if (callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7); if (rr) terminate_flag = 1; } #endif for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free(buffer); } #ifdef LIBRAW_LIBRARY_BUILD if (terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = {-1, 1, -TS, TS}; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][TS][3], (*lix)[3]; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("AHD interpolation...\n")); #endif cielab(0, 0); border_interpolate(5); buffer = (char *)malloc(26 * TS * TS); merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][TS])(buffer + 24 * TS * TS); for (top = 2; top < height - 5; top += TS - 6) for (left = 2; left < width - 5; left += TS - 6) { /* Interpolate green horizontally and vertically: */ for (row = top; row < top + TS && row < height - 2; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < left + TS && col < width - 2; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d = 0; d < 2; d++) for (row = top + 1; row < top + TS - 1 && row < height - 3; row++) for (col = left + 1; col < left + TS - 1 && col < width - 3; col++) { pix = image + row * width + col; rix = &rgb[d][row - top][col - left]; lix = &lab[d][row - top][col - left]; if ((c = 2 - FC(row, col)) == 1) { c = FC(row + 1, col); val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1); rix[0][2 - c] = CLIP(val); val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1); } else val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset(homo, 0, 2 * TS * TS); for (row = top + 2; row < top + TS - 2 && row < height - 4; row++) { tr = row - top; for (col = left + 2; col < left + TS - 2 && col < width - 4; col++) { tc = col - left; for (d = 0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i = 0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (d = 0; d < 2; d++) for (i = 0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row = top + 3; row < top + TS - 3 && row < height - 5; row++) { tr = row - top; for (col = left + 3; col < left + TS - 3 && col < width - 5; col++) { tc = col - left; for (d = 0; d < 2; d++) for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++) for (j = tc - 1; j <= tc + 1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free(buffer); } #endif #undef TS void CLASS median_filter() { ushort(*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ {1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0, 3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2}; for (pass = 1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Median filter pass %d...\n"), pass); #endif for (c = 0; c < 3; c += 2) { for (pix = image; pix < image + width * height; pix++) pix[0][3] = pix[0][c]; for (pix = image + width; pix < image + width * (height - 1); pix++) { if ((pix - image + 1) % width < 2) continue; for (k = 0, i = -width; i <= width; i += width) for (j = i - 1; j <= i + 1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i = 0; i < sizeof opt; i += 2) if (med[opt[i]] > med[opt[i + 1]]) SWAP(med[opt[i]], med[opt[i + 1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip = INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned)(colors - 3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2); #endif FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { FORCC if (image[row * width + col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row * width + col][c]; cam[1][c] = MIN(cam[0][c], clip); } for (i = 0; i < 2; i++) { FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j]; for (sum[i] = 0, c = 1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1] / sum[0]); for (c = 1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j]; FORCC image[row * width + col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rebuilding highlights...\n")); #endif grow = pow(2.0, 4 - highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc = 0, c = 1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *)calloc(high, wide * sizeof *map); merror(map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1); #endif memset(map, 0, high * wide * sizeof *map); for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE * SCALE) map[mrow * wide + mcol] = sum / wgt; } for (spread = 32 / grow; spread--;) { for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { if (map[mrow * wide + mcol]) continue; sum = count = 0; for (d = 0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y * wide + x] > 0) { sum += (1 + (d & 1)) * map[y * wide + x]; count += 1 + (d & 1); } } if (count > 3) map[mrow * wide + mcol] = -(sum + grow) / (count + grow); } for (change = i = 0; i < high * wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i = 0; i < high * wide; i++) if (map[i] == 0) map[i] = 1; for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow * wide + mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free(map); } #undef SCALE void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { #ifdef LIBRAW_IOSPACE_CHECK INT64 pos = ftell(ifp); INT64 fsize = ifp->size(); if(fsize < 12 || (fsize-pos) < 12) throw LIBRAW_EXCEPTION_IO_EOF; #endif *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4) fseek(ifp, get4() + base, SEEK_SET); } void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4() + base; if (tag == tlen) thumb_length = get4(); fseek(ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); } static float libraw_powf64l(float a, float b) { return powf_lim(a, b, 64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return libraw_powf64l(2.0, in / 64.0); } static float _CanonConvertEV(short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float)Frac; return ((float)Sign * ((float)EV + Frac_f)) / 32.0f; } unsigned CLASS setCanonBodyFeatures(unsigned id) { if (id == 0x03740000) // EOS M3 id = 0x80000374; else if (id == 0x03840000) // EOS M10 id = 0x80000384; else if (id == 0x03940000) // EOS M5 id = 0x80000394; else if (id == 0x04070000) // EOS M6 id = 0x80000407; else if (id == 0x03980000) // EOS M100 id = 0x80000398; imgdata.lens.makernotes.CamID = id; if ((id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) || // M5 (id == 0x80000407) || // M6 (id == 0x80000398) // M100 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ((id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return id; } void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if (maxlen < 16) return; // too short CameraInfo[0] = 0; CameraInfo[1] = 0; if (type == 4) { if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) || (maxlen == 171) || (maxlen == 264) || (maxlen > 400)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 3) << 2)); else if (maxlen == 72) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 1) << 2)); else if ((maxlen == 85) || (maxlen == 93)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 2) << 2)); else if ((maxlen == 96) || (maxlen == 104)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen - 4) << 2)); } switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); imgdata.other.CameraTemperature = 0.0f; break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if (iCanonFocalType >= maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if (iCanonCurFocal >= maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if (iCanonLensID >= maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if (iCanonMinFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if (iCanonMaxFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if (iCanonLens + 64 >= maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings() { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets(int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets(short WBCTversion) { if (WBCTversion == 0) for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x80000407) || // M6 (unique_id == 0x80000398) || // M100 (unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000))) // G1 X Mark III for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData(uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * libraw_powf64l(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = libraw_powf64l(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 | (unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 | (unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 | (unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures(unsigned long long id) { imgdata.lens.makernotes.CamID = id; if (id == 0x5330303638ULL) { strcpy(model, "E-M10MarkIII"); } if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 24, SEEK_CUR); tempAp = get2(); if (tempAp != 0) imgdata.other.CameraTemperature = (float)(tempAp - 128); tempAp = get2(); if (tempAp != -1) imgdata.other.FlashGN = ((float)tempAp) / 32; get2(); // fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8 - 32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x000c) { unsigned tS = get4(); sprintf (imgdata.shootinginfo.BodySerial, "%d", tS); } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x009a) { get4(); imgdata.sizes.raw_crop.cwidth = get4(); imgdata.sizes.raw_crop.cheight = get4(); imgdata.sizes.raw_crop.cleft = get4(); imgdata.sizes.raw_crop.ctop = get4(); } else if (tag == 0x00a9) { long int save1 = ftell(ifp); int c; fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(), get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4013) { get4(); imgdata.makernotes.canon.AFMicroAdjMode = get4(); imgdata.makernotes.canon.AFMicroAdjValue = ((float)get4()) / ((float)get4()); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek(ifp, save1 + (0x1e << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x41 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x46 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x23 << 1), SEEK_SET); Canon_WBpresets(2, 2); fseek(ifp, save1 + (0x4b << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek(ifp, save1 + (0x18 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x90 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x95 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x9a << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x27 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa4 << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x71 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x76 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x7b << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x4e << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x53 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa8 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek(ifp, save1 + (0x2b8 << 1), SEEK_SET); // offset 696 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek(ifp, save1 + (0x2cf << 1), SEEK_SET); // offset 719 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek(ifp, save1 + (0x2d3 << 1), SEEK_SET); // offset 723 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6 { if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000) || // G1 X Mark III (unique_id == 0x80000394) || // EOS M5 (unique_id == 0x80000398) || // EOS M100 (unique_id == 0x80000407)) // EOS M6 { fseek(ifp, save1 + (0x4f << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8, 24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets(2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { fseek(ifp, save1 + (0x4c << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xba << 1), SEEK_SET); Canon_WBCTpresets(2); // BCADT fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short } int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x67 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xbc << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } fseek(ifp, save1 + (0x1e3 << 1), SEEK_SET); // offset 483 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xd5 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek(ifp, save1 + (0x1fc << 1), SEEK_SET); // offset 508 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek(ifp, save1 + (0x2dc << 1), SEEK_SET); // offset 732 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D case 1560: case 1592: case 1353: case 1602: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x107 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek(ifp, save1 + (0x230 << 1), SEEK_SET); // offset 560 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek(ifp, save1 + (0x30e << 1), SEEK_SET); // offset 782 shorts imgdata.makernotes.canon.NormalWhiteLevel = get2(); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek(ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: case 0x1322c: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO(ushort c) { int code[] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code) / sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar *)malloc(MAX(len, 128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10 * (table_buf[iLensData + 9] >> 2) * libraw_powf64l(4, (table_buf[iLensData + 9] & 0x03) - 2); if (table_buf[iLensData + 10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f); if (table_buf[iLensData + 10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07); if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures(unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333, "Mamiya"}, {329, "Universal"}, {330, "Hasselblad H1/H2"}, {332, "Contax"}, {336, "AFi"}, {327, "Mamiya"}, {324, "Universal"}, {325, "Hasselblad H1/H2"}, {326, "Contax"}, {335, "AFi"}, {340, "Mamiya"}, {337, "Universal"}, {338, "Hasselblad H1/H2"}, {339, "Contax"}, {323, "Mamiya"}, {320, "Universal"}, {322, "Hasselblad H1/H2"}, {321, "Contax"}, {334, "AFi"}, {369, "Universal"}, {370, "Mamiya"}, {371, "Hasselblad H1/H2"}, {372, "Contax"}, {373, "Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes(unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures(unsigned id) { ushort idx; static const struct { ushort scf[8]; /* scf[0] camera id scf[1] camera format scf[2] camera mount: Minolta A, Sony E, fixed, scf[3] camera type: DSLR, NEX, SLT, ILCE, ILCA, DSC scf[4] lens mount scf[5] tag 0x2010 group (0 if not used) scf[6] offset of Sony ISO in 0x2010 table, 0xffff if not valid scf[7] offset of ImageCount3 in 0x9050 table, 0xffff if not valid */ } SonyCamFeatures[] = { {256, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {257, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {258, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {259, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {260, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {261, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {262, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {263, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {264, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {265, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {266, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {267, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {268, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {269, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {270, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {271, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {272, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {273, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {274, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {275, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {276, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {277, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {278, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff}, {279, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff}, {280, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff}, {281, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff}, {282, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {283, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_DSLR, 0, 0, 0xffff, 0xffff}, {284, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 0, 0xffff, 0xffff}, {285, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 0, 0xffff, 0xffff}, {286, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd}, {287, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 2, 0x1218, 0x01bd}, {288, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 1, 0x113e, 0x01bd}, {289, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd}, {290, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 2, 0x1218, 0x01bd}, {291, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd}, {292, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 3, 0x11f4, 0x01bd}, {293, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 3, 0x11f4, 0x01bd}, {294, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1254, 0x01aa}, {295, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {296, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {297, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1254, 0xffff}, {298, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff}, {299, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {300, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {301, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {302, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 5, 0x1280, 0x01aa}, {303, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_SLT, 0, 5, 0x1280, 0x01aa}, {304, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {305, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1280, 0x01aa}, {306, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {307, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_NEX, 0, 5, 0x1254, 0x01aa}, {308, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 6, 0x113c, 0xffff}, {309, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff}, {310, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 5, 0x1258, 0xffff}, {311, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {312, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {313, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01aa}, {314, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {315, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {316, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {317, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 7, 0x0344, 0xffff}, {318, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {319, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0}, {320, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {321, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {322, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {323, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {324, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {325, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {326, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {327, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {328, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {329, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {330, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {331, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {332, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {333, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {334, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {335, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {336, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {337, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {338, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {339, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0}, {340, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0xffff}, {341, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {342, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {343, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {344, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {345, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {346, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 7, 0x0344, 0x01a0}, {347, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb}, {348, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {349, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {350, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cb}, {351, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {352, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {353, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 7, 0x0344, 0x01a0}, {354, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Minolta_A, LIBRAW_SONY_ILCA, 0, 8, 0x0346, 0x01cd}, {355, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {356, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {357, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd}, {358, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f}, {359, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {360, LIBRAW_FORMAT_APSC, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 8, 0x0346, 0x01cd}, {361, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {362, LIBRAW_FORMAT_FF, LIBRAW_MOUNT_Sony_E, LIBRAW_SONY_ILCE, 0, 9, 0x0320, 0x019f}, {363, 0, 0, 0, 0, 0, 0xffff, 0xffff}, {364, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 8, 0x0346, 0xffff}, {365, LIBRAW_FORMAT_1INCH, LIBRAW_MOUNT_FixedLens, LIBRAW_SONY_DSC, LIBRAW_MOUNT_FixedLens, 9, 0x0320, 0xffff}, }; imgdata.lens.makernotes.CamID = id; if (id == 2) { imgdata.lens.makernotes.CameraMount = imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; imgdata.makernotes.sony.group2010 = 0; imgdata.makernotes.sony.real_iso_offset = 0xffff; imgdata.makernotes.sony.ImageCount3_offset = 0xffff; return; } else idx = id - 256; if ((idx >= 0) && (idx < sizeof SonyCamFeatures / sizeof *SonyCamFeatures)) { if (!SonyCamFeatures[idx].scf[2]) return; imgdata.lens.makernotes.CameraFormat = SonyCamFeatures[idx].scf[1]; imgdata.lens.makernotes.CameraMount = SonyCamFeatures[idx].scf[2]; imgdata.makernotes.sony.SonyCameraType = SonyCamFeatures[idx].scf[3]; if (SonyCamFeatures[idx].scf[4]) imgdata.lens.makernotes.LensMount = SonyCamFeatures[idx].scf[4]; imgdata.makernotes.sony.group2010 = SonyCamFeatures[idx].scf[5]; imgdata.makernotes.sony.real_iso_offset = SonyCamFeatures[idx].scf[6]; imgdata.makernotes.sony.ImageCount3_offset = SonyCamFeatures[idx].scf[7]; } char *sbstr = strstr(software, " v"); if (sbstr != NULL) { sbstr += 2; imgdata.makernotes.sony.firmware = atof(sbstr); if ((id == 306) || (id == 311)) { if (imgdata.makernotes.sony.firmware < 1.2f) imgdata.makernotes.sony.ImageCount3_offset = 0x01aa; else imgdata.makernotes.sony.ImageCount3_offset = 0x01c0; } else if (id == 312) { if (imgdata.makernotes.sony.firmware < 2.0f) imgdata.makernotes.sony.ImageCount3_offset = 0x01aa; else imgdata.makernotes.sony.ImageCount3_offset = 0x01c0; } else if ((id == 318) || (id == 340)) { if (imgdata.makernotes.sony.firmware < 1.2f) imgdata.makernotes.sony.ImageCount3_offset = 0x01a0; else imgdata.makernotes.sony.ImageCount3_offset = 0x01b6; } } } void CLASS parseSonyLensType2(uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a) << 8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf))) void CLASS parseSonyLensFeatures(uchar a, uchar b) { ushort features; features = (((ushort)a) << 8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA"); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1); return; } #undef strnXcat void CLASS process_Sony_0x0116(uchar *buf, ushort len, unsigned id) { short bufx; if (((id == 257) || (id == 262) || (id == 269) || (id == 270)) && (len >= 2)) bufx = buf[1]; else if ((id >= 273) && (len >= 3)) bufx = buf[2]; else return; imgdata.other.BatteryTemperature = (float)(bufx - 32) / 1.8f; } void CLASS process_Sony_0x2010(uchar *buf, ushort len) { if ((!imgdata.makernotes.sony.group2010) || (imgdata.makernotes.sony.real_iso_offset == 0xffff) || (len < (imgdata.makernotes.sony.real_iso_offset + 2))) return; if (imgdata.other.real_ISO < 0.1f) { uchar s[2]; s[0] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset]]; s[1] = SonySubstitution[buf[imgdata.makernotes.sony.real_iso_offset + 1]]; imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f)); } } void CLASS process_Sony_0x9050(uchar *buf, ushort len, unsigned id) { ushort lid; uchar s[4]; int c; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (len < 2) return; if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(libraw_powf64l(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(libraw_powf64l(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (len <= 0x106) return; if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { if (len <= 0x108) return; parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if (len <= 0x10a) return; if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) { if (len <= 0x116) return; // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); } else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (len <= 0x117) return; parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); } if ((id == 347) || (id == 350) || (id == 354) || (id == 357) || (id == 358) || (id == 360) || (id == 362)) { if (len <= 0x8d) return; unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) { if (len <= 0xf4) return; unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { if (len <= 0x7f) return; unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } if ((imgdata.makernotes.sony.ImageCount3_offset != 0xffff) && (len >= (imgdata.makernotes.sony.ImageCount3_offset + 4))) { FORC4 s[c] = SonySubstitution[buf[imgdata.makernotes.sony.ImageCount3_offset + c]]; imgdata.makernotes.sony.ImageCount3 = sget4(s); } if (id == 362) { for (c = 0; c < 6; c++) { imgdata.makernotes.sony.TimeStamp[c] = SonySubstitution[buf[0x0066 + c]]; } } return; } void CLASS process_Sony_0x9400(uchar *buf, ushort len, unsigned id) { uchar s[4]; int c; short bufx = buf[0]; if (((bufx == 0x23) || (bufx == 0x24) || (bufx == 0x26)) && (len >= 0x1f)) { // 0x9400 'c' version if ((id == 358) || (id == 362) || (id == 365)) { imgdata.makernotes.sony.ShotNumberSincePowerUp = SonySubstitution[buf[0x0a]]; } else { FORC4 s[c] = SonySubstitution[buf[0x0a + c]]; imgdata.makernotes.sony.ShotNumberSincePowerUp = sget4(s); } imgdata.makernotes.sony.Sony0x9400_version = 0xc; imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x09]]; FORC4 s[c] = SonySubstitution[buf[0x12 + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x16]]; // shots FORC4 s[c] = SonySubstitution[buf[0x1a + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_SequenceLength2 = SonySubstitution[buf[0x1e]]; // files } else if ((bufx == 0x0c) && (len >= 0x1f)) { // 0x9400 'b' version imgdata.makernotes.sony.Sony0x9400_version = 0xb; FORC4 s[c] = SonySubstitution[buf[0x08 + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s); FORC4 s[c] = SonySubstitution[buf[0x0c + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]]; imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x1e]]; } else if ((bufx == 0x0a) && (len >= 0x23)) { // 0x9400 'a' version imgdata.makernotes.sony.Sony0x9400_version = 0xa; FORC4 s[c] = SonySubstitution[buf[0x08 + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceImageNumber = sget4(s); FORC4 s[c] = SonySubstitution[buf[0x0c + c]]; imgdata.makernotes.sony.Sony0x9400_SequenceFileNumber = sget4(s); imgdata.makernotes.sony.Sony0x9400_ReleaseMode2 = SonySubstitution[buf[0x10]]; imgdata.makernotes.sony.Sony0x9400_SequenceLength1 = SonySubstitution[buf[0x22]]; } else return; } void CLASS process_Sony_0x9402(uchar *buf, ushort len) { if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_SLT) || (imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA)) return; if (len < 5) return; short bufx = buf[0x00]; if ((bufx == 0x05) || (bufx == 0xff) || (buf[0x02] != 0xff)) return; imgdata.other.AmbientTemperature = (float)((short)SonySubstitution[buf[0x04]]); return; } void CLASS process_Sony_0x9403(uchar *buf, ushort len) { if (len < 6) return; short bufx = SonySubstitution[buf[4]]; if ((bufx == 0x00) || (bufx == 0x94)) return; imgdata.other.SensorTemperature = (float)((short)SonySubstitution[buf[5]]); return; } void CLASS process_Sony_0x9406(uchar *buf, ushort len) { if (len < 6) return; short bufx = buf[0]; if ((bufx != 0x01) && (bufx != 0x08) && (bufx != 0x1b)) return; bufx = buf[2]; if ((bufx != 0x08) && (bufx != 0x1b)) return; imgdata.other.BatteryTemperature = (float)(SonySubstitution[buf[5]] - 32) / 1.8f; return; } void CLASS process_Sony_0x940c(uchar *buf, ushort len) { if ((imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_ILCE) && (imgdata.makernotes.sony.SonyCameraType != LIBRAW_SONY_NEX)) return; if (len <= 0x000a) return; ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x940e(uchar *buf, ushort len, unsigned id) { if (((id == 286) || (id == 287) || (id == 294)) && (len >= 0x017e)) { imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x017d]]; } else if ((imgdata.makernotes.sony.SonyCameraType == LIBRAW_SONY_ILCA) && (len >= 0x0051)) { imgdata.makernotes.sony.AFMicroAdjValue = SonySubstitution[buf[0x0050]]; } else return; if (imgdata.makernotes.sony.AFMicroAdjValue != 0) imgdata.makernotes.sony.AFMicroAdjOn = 1; } void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x0116, ushort &table_buf_0x0116_len, uchar *&table_buf_0x2010, ushort &table_buf_0x2010_len, uchar *&table_buf_0x9050, ushort &table_buf_0x9050_len, uchar *&table_buf_0x9400, ushort &table_buf_0x9400_len, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_len, uchar *&table_buf_0x9403, ushort &table_buf_0x9403_len, uchar *&table_buf_0x9406, ushort &table_buf_0x9406_len, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_len, uchar *&table_buf_0x940e, ushort &table_buf_0x940e_len) { ushort lid; uchar *table_buf; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x0116_len) { process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, unique_id); free(table_buf_0x0116); table_buf_0x0116_len = 0; } if (table_buf_0x2010_len) { process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len); free(table_buf_0x2010); table_buf_0x2010_len = 0; } if (table_buf_0x9050_len) { process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, unique_id); free(table_buf_0x9050); table_buf_0x9050_len = 0; } if (table_buf_0x9400_len) { process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id); free(table_buf_0x9400); table_buf_0x9400_len = 0; } if (table_buf_0x9402_len) { process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len); free(table_buf_0x9402); table_buf_0x9402_len = 0; } if (table_buf_0x9403_len) { process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len); free(table_buf_0x9403); table_buf_0x9403_len = 0; } if (table_buf_0x9406_len) { process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len); free(table_buf_0x9406); table_buf_0x9406_len = 0; } if (table_buf_0x940c_len) { process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len); free(table_buf_0x940c); table_buf_0x940c_len = 0; } if (table_buf_0x940e_len) { process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, unique_id); free(table_buf_0x940e); table_buf_0x940e_len = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if ((!dng_writer) || (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); if (len == 5478) { imgdata.makernotes.sony.AFMicroAdjValue = table_buf[304] - 20; imgdata.makernotes.sony.AFMicroAdjOn = (((table_buf[305] & 0x80) == 0x80) ? 1 : 0); imgdata.makernotes.sony.AFMicroAdjRegisteredLenses = table_buf[305] & 0x7f; } } break; default: // CameraInfo2 & 3 if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if ((tag == 0x3000) && (len < 256000)) { uchar *table_buf_0x3000; table_buf_0x3000 = (uchar *)malloc(len); fread(table_buf_0x3000, len, 1, ifp); for (int i = 0; i < 20; i++) imgdata.makernotes.sony.SonyDateTime[i] = table_buf_0x3000[6 + i]; } else if (tag == 0x0116 && len < 256000) { table_buf_0x0116 = (uchar *)malloc(len); table_buf_0x0116_len = len; fread(table_buf_0x0116, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x0116(table_buf_0x0116, table_buf_0x0116_len, imgdata.lens.makernotes.CamID); free(table_buf_0x0116); table_buf_0x0116_len = 0; } } else if (tag == 0x2010 && len < 256000) { table_buf_0x2010 = (uchar *)malloc(len); table_buf_0x2010_len = len; fread(table_buf_0x2010, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x2010(table_buf_0x2010, table_buf_0x2010_len); free(table_buf_0x2010); table_buf_0x2010_len = 0; } } else if (tag == 0x201a) { imgdata.makernotes.sony.ElectronicFrontCurtainShutter = get4(); } else if (tag == 0x201b) { uchar uc; fread(&uc, 1, 1, ifp); imgdata.shootinginfo.FocusMode = (short)uc; } else if (tag == 0x202c) { imgdata.makernotes.sony.MeteringMode2 = get2(); } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_len = len; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, table_buf_0x9050_len, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_len = 0; } } else if (tag == 0x9400 && len < 256000) { table_buf_0x9400 = (uchar *)malloc(len); table_buf_0x9400_len = len; fread(table_buf_0x9400, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9400(table_buf_0x9400, table_buf_0x9400_len, unique_id); free(table_buf_0x9400); table_buf_0x9400_len = 0; } } else if (tag == 0x9402 && len < 256000) { table_buf_0x9402 = (uchar *)malloc(len); table_buf_0x9402_len = len; fread(table_buf_0x9402, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9402(table_buf_0x9402, table_buf_0x9402_len); free(table_buf_0x9402); table_buf_0x9402_len = 0; } } else if (tag == 0x9403 && len < 256000) { table_buf_0x9403 = (uchar *)malloc(len); table_buf_0x9403_len = len; fread(table_buf_0x9403, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9403(table_buf_0x9403, table_buf_0x9403_len); free(table_buf_0x9403); table_buf_0x9403_len = 0; } } else if ((tag == 0x9405) && (len < 256000) && (len > 0x64)) { uchar *table_buf_0x9405; table_buf_0x9405 = (uchar *)malloc(len); short bufx = table_buf_0x9405[0x0]; fread(table_buf_0x9405, len, 1, ifp); if (imgdata.other.real_ISO < 0.1f) { if ((bufx == 0x25) || (bufx == 0x3a) || (bufx == 0x76) || (bufx == 0x7e) || (bufx == 0x8b) || (bufx == 0x9a) || (bufx == 0xb3) || (bufx == 0xe1)) { uchar s[2]; s[0] = SonySubstitution[table_buf_0x9405[0x04]]; s[1] = SonySubstitution[table_buf_0x9405[0x05]]; imgdata.other.real_ISO = 100.0f * libraw_powf64l(2.0f, (16 - ((float)sget2(s)) / 256.0f)); } } free(table_buf_0x9405); } else if (tag == 0x9406 && len < 256000) { table_buf_0x9406 = (uchar *)malloc(len); table_buf_0x9406_len = len; fread(table_buf_0x9406, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9406(table_buf_0x9406, table_buf_0x9406_len); free(table_buf_0x9406); table_buf_0x9406_len = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_len = len; fread(table_buf_0x940c, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x940c(table_buf_0x940c, table_buf_0x940c_len); free(table_buf_0x940c); table_buf_0x940c_len = 0; } } else if (tag == 0x940e && len < 256000) { table_buf_0x940e = (uchar *)malloc(len); table_buf_0x940e_len = len; fread(table_buf_0x940e, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x940e(table_buf_0x940e, table_buf_0x940e_len, imgdata.lens.makernotes.CamID); free(table_buf_0x940e); table_buf_0x940e_len = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } else if ((tag == 0xb02b) && !imgdata.sizes.raw_crop.cwidth && (len == 2)) { imgdata.sizes.raw_crop.cheight = get4(); imgdata.sizes.raw_crop.cwidth = get4(); } } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x0116; ushort table_buf_0x0116_len = 0; uchar *table_buf_0x2010; ushort table_buf_0x2010_len = 0; uchar *table_buf_0x9050; ushort table_buf_0x9050_len = 0; uchar *table_buf_0x9400; ushort table_buf_0x9400_len = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_len = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_len = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_len = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_len = 0; uchar *table_buf_0x940e; ushort table_buf_0x940e_len = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if (len > 8 && pos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } tag |= uptag << 16; if (len > 100 * 1024 * 1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16, len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes(tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) && !strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)) imgdata.other.CameraTemperature = getreal(type); if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } else if (tag == 0x00b9) { uchar uc; int8_t sc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTune = uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneIndex = uc; fread(&sc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneAdj = sc; } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * libraw_powf64l(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { short nWB, tWB; int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) && strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2040) || (tag == 0x2050) || (tag == 0x3000)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) || (((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; if ((tag >= 0x20400101) && (tag <= 0x20400111)) { if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } for (i = 64; i < 256; i++) { imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } else if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } else if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } else if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } else if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } else if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } else { switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 | (unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x20200306: { uchar uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.olympus.AFFineTune = uc; } break; case 0x20200307: FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2(); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float)temp; else imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x000d) { imgdata.makernotes.pentax.FocusMode = get2(); } else if (tag == 0x000e) { imgdata.makernotes.pentax.AFPointSelected = get2(); } else if (tag == 0x000f) { imgdata.makernotes.pentax.AFPointsInFocus = getint(type); } else if (tag == 0x0010) { imgdata.makernotes.pentax.FocusPosition = get2(); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x0034) { uchar uc; FORC4 { fread(&uc, 1, 1, ifp); imgdata.makernotes.pentax.DriveMode[c] = uc; } } else if (tag == 0x0038) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); } else if (tag == 0x0039) { imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x0072) { imgdata.makernotes.pentax.AFAdjustment = get2(); } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float)temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010, table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400, table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403, table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c, table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len); } next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */ } #endif void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x0116; ushort table_buf_0x0116_len = 0; uchar *table_buf_0x2010; ushort table_buf_0x2010_len = 0; uchar *table_buf_0x9050; ushort table_buf_0x9050_len = 0; uchar *table_buf_0x9400; ushort table_buf_0x9400_len = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_len = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_len = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_len = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_len = 0; uchar *table_buf_0x940e; ushort table_buf_0x940e_len = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make, "Nokia", 5)) return; fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */ !strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4)) return; if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */ !strncmp(buf, "MLY", 3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, "SAMSUNG", 7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (!strncasecmp(model, "KODAK P880", 10) || !strncasecmp(model, "KODAK P850", 10) || !strncasecmp(model, "KODAK P712", 10)) { if (tag == 0xf90b) { imgdata.makernotes.kodak.clipBlack = get2(); } else if (tag == 0xf90c) { imgdata.makernotes.kodak.clipWhite = get2(); } } if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16, len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16, len * 4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2) ystr[j / 2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) || !strncasecmp(model, "Hasselblad A6D", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp(make, "Leica Camera AG", 15) && !strncmp(buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) / (float)c; } else if (tag == 0x003b) // all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0045) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) // Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } else if (tag == 0x00b9) { uchar uc; int8_t sc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTune = uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneIndex = uc; fread(&sc, 1, 1, ifp); imgdata.makernotes.nikon.AFFineTuneAdj = sc; } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, getreal(type) / 2); break; case 0x20400612: case 0x30000612: imgdata.sizes.raw_crop.cleft = get2(); break; case 0x20400613: case 0x30000613: imgdata.sizes.raw_crop.ctop = get2(); break; case 0x20400614: case 0x30000614: imgdata.sizes.raw_crop.cwidth = get2(); break; case 0x20400615: case 0x30000615: imgdata.sizes.raw_crop.cheight = get2(); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float)temp; else imgdata.other.CameraTemperature = (float)(temp - 32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f * (float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x000d) { imgdata.makernotes.pentax.FocusMode = get2(); } else if (tag == 0x000e) { imgdata.makernotes.pentax.AFPointSelected = get2(); } else if (tag == 0x000f) { imgdata.makernotes.pentax.AFPointsInFocus = getint(type); } else if (tag == 0x0010) { imgdata.makernotes.pentax.FocusPosition = get2(); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x0034) { uchar uc; FORC4 { fread(&uc, 1, 1, ifp); imgdata.makernotes.pentax.DriveMode[c] = uc; } } else if (tag == 0x0038) { imgdata.sizes.raw_crop.cleft = get2(); imgdata.sizes.raw_crop.ctop = get2(); } else if (tag == 0x0039) { imgdata.sizes.raw_crop.cwidth = get2(); imgdata.sizes.raw_crop.cheight = get2(); } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x0072) { imgdata.makernotes.pentax.AFAdjustment = get2(); } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float)temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x0116, table_buf_0x0116_len, table_buf_0x2010, table_buf_0x2010_len, table_buf_0x9050, table_buf_0x9050_len, table_buf_0x9400, table_buf_0x9400_len, table_buf_0x9402, table_buf_0x9402_len, table_buf_0x9403, table_buf_0x9403_len, table_buf_0x9406, table_buf_0x9406_len, table_buf_0x940c, table_buf_0x940c_len, table_buf_0x940e, table_buf_0x940e_len); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, "NIKON") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * libraw_powf64l(2.0f, float(cc) / 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * libraw_powf64l(2.0, i / 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = libraw_powf64l(2.0, i / 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = libraw_powf64l(2.0, (short)i / -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, "Canon", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 /* Canon rotation data is handled by EXIF.Orientation */ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = "065"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, "Olympus", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200306) { uchar uc; fread(&uc, 1, 1, ifp); imgdata.makernotes.olympus.AFFineTune = uc; } if (tag == 0x20200307) { FORC3 imgdata.makernotes.olympus.AFFineTuneAdj[c] = get2(); } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, "NRW ", 4)) { fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, "PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) // Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) // Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, "NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, "Samsung", 7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } /* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); } */ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp(int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i = 19; i--;) str[i] = fgetc(ifp); else fread(str, 19, 1, ifp); memset(&t, 0, sizeof t); if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif(int base) { unsigned kodak, entries, tag, type, len, save, c; double expo, ape; kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34865: if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4)) iso_speed = getreal(type); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = libraw_powf64l(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = libraw_powf64l(2.0, ape / 2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, MIN(len,511), ifp); mn_text[511] = 0; pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm="); if(pos) { pos +=4; char *pos2 = strstr(pos, " "); if(pos2) { l = pos2 - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; #if defined WIN32 || defined(__MINGW32__) // Win32 strtok is already thread-safe pos = strtok(ccms, ","); #else char *last=0; pos = strtok_r(ccms, ",",&last); #endif if(pos) { for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; #if defined WIN32 || defined(__MINGW32__) pos = strtok(NULL, ","); #else pos = strtok_r(NULL, ",",&last); #endif if(!pos) goto end; // broken } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } } } end:; } else #endif parse_makernote(base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; // no GPS tags are 1k or larger } switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; // no GPS tags are 1k or larger } switch (tag) { case 1: case 3: case 5: gpsdata[29 + tag / 2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag / 3 * 6 + c] = get4(); break; case 6: FORC(2) gpsdata[18 + c] = get4(); break; case 18: case 29: fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp); } fseek(ifp, save, SEEK_SET); } } void CLASS romm_coeff(float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ {{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}}; int i, j, k; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) for (cmatrix[i][j] = k = 0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos(int offset) { char data[40]; int skip, from, i, c, neut[4], planes = 0, frot = 0; static const char *mod[] = {"", "DCB2", "Volare", "Cantare", "CMost", "Valeo 6", "Valeo 11", "Valeo 22", "Valeo 11p", "Valeo 17", "", "Aptus 17", "Aptus 22", "Aptus 75", "Aptus 65", "Aptus 54S", "Aptus 65S", "Aptus 75S", "AFi 5", "AFi 6", "AFi 7", "AFi-II 7", "Aptus-II 7", "", "Aptus-II 6", "", "", "Aptus-II 10", "Aptus-II 5", "", "", "", "", "Aptus-II 10R", "Aptus-II 8", "", "Aptus-II 12", "", "AFi-II 12"}; float romm_cam[3][3]; fseek(ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread(data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data, "CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data, "back_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial)); strcpy(imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data, "CaptProf_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data, "JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data, "icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data, "ShootObj_back_type")) { fscanf(ifp, "%d", &i); if ((unsigned)i < sizeof mod / sizeof(*mod)) strcpy(model, mod[i]); } if (!strcmp(data, "icc_camera_to_tone_matrix")) { for (i = 0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_color_matrix")) { for (i = 0; i < 9; i++) fscanf(ifp, "%f", (float *)romm_cam + i); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_number_of_planes")) fscanf(ifp, "%d", &planes); if (!strcmp(data, "CaptProf_raw_data_rotation")) fscanf(ifp, "%d", &flip); if (!strcmp(data, "CaptProf_mosaic_pattern")) FORC4 { fscanf(ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data, "ImgProf_rotation_angle")) { fscanf(ifp, "%d", &i); flip = i - flip; } if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf(ifp, "%d", neut + c); FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1]; } if (!strcmp(data, "Rows_data")) load_flags = get4(); parse_mos(from); fseek(ifp, skip + from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3]; } void CLASS linear_table(unsigned len) { int i; if (len > 0x10000) len = 0x10000; else if(len < 1) return; read_shorts(curve, len); for (i = len; i < 0x10000; i++) curve[i] = curve[i - 1]; maximum = curve[len < 0x1000 ? 0xfff : len - 1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags(int wb, unsigned type) { float mul[3] = {1, 1, 1}, num, mul2; int c; FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int j, c, wbi = -2, romm_camTemp[9], romm_camScale[3]; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; // int a_blck = 0; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } if (tag == 1003) imgdata.sizes.raw_crop.cleft = get2(); if (tag == 1004) imgdata.sizes.raw_crop.ctop = get2(); if (tag == 1005) imgdata.sizes.raw_crop.cwidth = get2(); if (tag == 1006) imgdata.sizes.raw_crop.cheight = get2(); if (tag == 1007) imgdata.makernotes.kodak.BlackLevelTop = get2(); if (tag == 1008) imgdata.makernotes.kodak.BlackLevelBottom = get2(); if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2()); wbi = -2; } if ((tag == 1030) && (len == 1)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 1043) && (len == 1)) imgdata.other.SensorTemperature = getreal(type); if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C"))) black = get2(); if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C"))) { if (black) // already set by tag 0x03ef black = (black + get2()) / 2; else black = get2(); } INT64 _pos2 = ftell(ifp); if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x084c) Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type); if (tag == 0x084d) Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } fseek(ifp, _pos2, SEEK_SET); if (((tag == 0x07e4) || (tag == 0xfb01)) && (len == 9)) { short validM = 0; if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camDaylight)[j] = getreal(type); } validM = 1; } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camDaylight)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } validM = 1; } } if (validM) { romm_coeff(imgdata.makernotes.kodak.romm_camDaylight); } } if (((tag == 0x07e5) || (tag == 0xfb02)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camTungsten)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camTungsten)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e6) || (tag == 0xfb03)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camFluorescent)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camFluorescent)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e7) || (tag == 0xfb04)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camFlash)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camFlash)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e8) || (tag == 0xfb05)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camCustom)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camCustom)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (((tag == 0x07e9) || (tag == 0xfb06)) && (len == 9)) { if (type == 10) { for (j = 0; j < 9; j++) { ((float *)imgdata.makernotes.kodak.romm_camAuto)[j] = getreal(type); } } else if (type == 9) { FORC3 { romm_camScale[c] = 0; for (j = 0; j < 3; j++) { romm_camTemp[c * 3 + j] = get4(); romm_camScale[c] += romm_camTemp[c * 3 + j]; } } if ((romm_camScale[0] > 0x1fff) && (romm_camScale[1] > 0x1fff) && (romm_camScale[2] > 0x1fff)) { FORC3 for (j = 0; j < 3; j++) { ((float *)imgdata.makernotes.kodak.romm_camAuto)[c * 3 + j] = ((float)romm_camTemp[c * 3 + j]) / ((float)romm_camScale[c]); } } } } if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table(len); if (tag == 0x903) iso_speed = getreal(type); // if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 0xfa13) width = getint(type); if (tag == 0xfa14) height = (getint(type) + 1) & -2; /* height = getint(type); if (tag == 0xfa16) raw_width = get2(); if (tag == 0xfa17) raw_height = get2(); */ if (tag == 0xfa18) { imgdata.makernotes.kodak.offset_left = getint(8); if (type != 8) imgdata.makernotes.kodak.offset_left += 1; } if (tag == 0xfa19) { imgdata.makernotes.kodak.offset_top = getint(8); if (type != 8) imgdata.makernotes.kodak.offset_top += 1; } if (tag == 0xfa31) imgdata.sizes.raw_crop.cwidth = get2(); if (tag == 0xfa32) imgdata.sizes.raw_crop.cheight = get2(); if (tag == 0xfa3e) imgdata.sizes.raw_crop.cleft = get2(); if (tag == 0xfa3f) imgdata.sizes.raw_crop.ctop = get2(); fseek(ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2, wbtemp = 6500; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num = i = 0; i < 4; i++) num += getreal(type) * pow(wbtemp / 100.0, i); cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c])); } if (tag == 2317) linear_table(len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > 2 * fsize) { fseek(ifp, save, SEEK_SET); // Recover tiff-read position!! continue; } if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : ((ifd + 1) << 20)), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = get2(); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: if (len == 3) { FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } else if (len == 1) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = getreal(type); // Is non-short possible here?? } break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; break; #ifdef LIBRAW_LIBRARY_BUILD case 10: if (pana_raw && len == 1 && type == 3) { libraw_internal_data.unpacker_data.pana_bpp = get2(); } break; #endif case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; case 0x0120: if (pana_raw) { unsigned sorder = order; unsigned long sbase = base; base = ftell(ifp); order = get2(); fseek(ifp, 2, SEEK_CUR); fseek(ifp, get4()-8, SEEK_CUR); parse_tiff_ifd (base); base = sbase; order = sorder; } break; case 0x2009: if ((libraw_internal_data.unpacker_data.pana_encoding == 4) || (libraw_internal_data.unpacker_data.pana_encoding == 5)) { int n = MIN (8, len); int permut[8] = {3, 2, 1, 0, 3+4, 2+4, 1+4, 0+4}; imgdata.makernotes.panasonic.BlackLevelDim = len; for (int i=0; i < n; i++) { imgdata.makernotes.panasonic.BlackLevel[permut[i]] = (float) (get2()) / (float) (powf(2.f, 14.f-libraw_internal_data.unpacker_data.pana_bpp)); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 45: if (pana_raw && len == 1 && type == 3) { libraw_internal_data.unpacker_data.pana_encoding = get2(); } break; #endif case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread(desc, 512, 1, ifp); break; case 271: /* Make */ fgets(make, 64, ifp); break; case 272: /* Model */ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: // FujiFilm "As Shot" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: /* Software */ if ((pana_raw) && (tag == 11) && (type == 3)) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.makernotes.panasonic.Compression = get2(); #endif break; } fgets(software, 64, ifp); if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) || !strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: /* SubIFDs */ if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP(cam_mul[i], cam_mul[i + 1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets(model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { if(cfa_pat[i] > 31) continue; // Skip wrong data colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, "\003\004\005", 3); /* CMY */ if (cfa == 072) memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 { int q = get2(); if(q > 0) cam_mul[c ^ 1] = 4096.0 / q; } break; case 34307: /* Leaf CatchLight color matrix */ fread(software, 1, 7, ifp); if (strncmp(software, "MATRIX", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1, num); } break; case 34310: /* Leaf metadata */ parse_mos(ftell(ifp)); case 34303: strcpy(make, "Leaf"); break; case 34665: /* EXIF tag */ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy(make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, "Ixpress %d-Mp", height * width / 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n')) if (!strncmp(++cp, "Neutral ", 8)) sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, "X-A3") && strcmp(model, "X-A10") && strcmp(model, "X-A5") && strcmp(model, "X-A20")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, "X-A3") && strcmp(model, "X-A10") && strcmp(model, "X-A5") && strcmp(model, "X-A20")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5; tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_black = #endif black = getreal(type); } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) cblack[6 + c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); if(len>0) { black += num / len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif } break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) // Linear DNG case for (i = 1; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: /* DefaultScale */ { float q1 = getreal(type); float q2 = getreal(type); if(q1 > 0.00001f && q2 > 0.00001f) { pixel_aspect = q1/q2; if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; } } break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: /* DefaultCropOrigin */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); if (!strncasecmp(make, "SONY", 4)) { imgdata.sizes.raw_crop.cleft = tiff_ifd[ifd].dng_levels.default_crop[0]; imgdata.sizes.raw_crop.ctop = tiff_ifd[ifd].dng_levels.default_crop[1]; } } break; case 50720: /* DefaultCropSize */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); if (!strncasecmp(make, "SONY", 4)) { imgdata.sizes.raw_crop.cwidth = tiff_ifd[ifd].dng_levels.default_crop[2]; imgdata.sizes.raw_crop.cheight = tiff_ifd[ifd].dng_levels.default_crop[3]; } } break; case 0x74c7: if ((len == 2) && !strncasecmp(make, "SONY", 4)) { imgdata.makernotes.sony.raw_crop.cleft = get4(); imgdata.makernotes.sony.raw_crop.ctop = get4(); } break; case 0x74c8: if ((len == 2) && !strncasecmp(make, "SONY", 4)) { imgdata.makernotes.sony.raw_crop.cwidth = get4(); imgdata.makernotes.sony.raw_crop.cheight = get4(); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORCC for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; INT64 save_pos = ifp->tell(); parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); curr_pos = save_pos + MakN_length - 6; fseek(ifp, curr_pos, SEEK_SET); fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "SR2 ", 4)) { order = 0x4d4d; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; unsigned *buf_SR2; uchar *cbuf_SR2; unsigned icbuf_SR2; unsigned entries, tag, type, len, save; int ival; unsigned SR2SubIFDOffset = 0; unsigned SR2SubIFDLength = 0; unsigned SR2SubIFDKey = 0; int base = curr_pos + 6 - pos_in_original_raw; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 0x7200) { SR2SubIFDOffset = get4(); } else if (tag == 0x7201) { SR2SubIFDLength = get4(); } else if (tag == 0x7221) { SR2SubIFDKey = get4(); } fseek(ifp, save, SEEK_SET); } if (SR2SubIFDLength && (SR2SubIFDLength < 10240000) && (buf_SR2 = (unsigned *)malloc(SR2SubIFDLength+1024))) // 1024b for safety { fseek(ifp, SR2SubIFDOffset + base, SEEK_SET); fread(buf_SR2, SR2SubIFDLength, 1, ifp); sony_decrypt(buf_SR2, SR2SubIFDLength / 4, 1, SR2SubIFDKey); cbuf_SR2 = (uchar *)buf_SR2; entries = sget2(cbuf_SR2); icbuf_SR2 = 2; while (entries--) { tag = sget2(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 2; type = sget2(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 2; len = sget4(cbuf_SR2 + icbuf_SR2); icbuf_SR2 += 4; if (len * ("11124811248484"[type < 14 ? type : 0] - '0') > 4) { ival = sget4(cbuf_SR2 + icbuf_SR2) - SR2SubIFDOffset; } else { ival = icbuf_SR2; } if(ival > SR2SubIFDLength) // points out of orig. buffer size break; // END processing. Generally we should check against SR2SubIFDLength minus 6 of 8, depending on tag, but we allocated extra 1024b for buffer, so this does not matter icbuf_SR2 += 4; switch (tag) { case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = sget2(cbuf_SR2 + ival + 2 * c); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = sget2(cbuf_SR2 + ival + 2 * c); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = sget2(cbuf_SR2 + ival + 2 * c); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; } } free(buf_SR2); } } /* SR2 processed */ break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: /* PreviewColorSpace */ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: /* OpcodeList2 */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length / 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC if(fabs(asn[c])>0.0001) cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC if(fabs(cc[c][c])>0.0001) pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff(int base) { int doff; fseek(ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek(ifp, doff + base, SEEK_SET); if (parse_tiff_ifd(base)) break; } return 1; } void CLASS apply_tiff() { int max_samp = 0, ties = 0, raw = -1, thm = -1, i; unsigned long long ns, os; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i = tiff_nifds; i--;) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i = 0; i < tiff_nifds; i++) { if( tiff_ifd[i].t_width < 1 || tiff_ifd[i].t_width > 65535 || tiff_ifd[i].t_height < 1 || tiff_ifd[i].t_height > 65535) continue; /* wrong image dimensions */ if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width * raw_height; ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i = tiff_nifds; i--;) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: #ifdef LIBRAW_LIBRARY_BUILD if (INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height)) #else if (tiff_ifd[raw].bytes == raw_width * raw_height) #endif { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL) #else if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) #endif { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } #ifdef LIBRAW_LIBRARY_BUILD if (INT64(tiff_ifd[raw].bytes) * 8ULL != INT64(raw_width) * INT64(raw_height) * INT64(tiff_bps)) #else if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps) #endif { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if (!strncasecmp(make, "Sony", 4) && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 2ULL) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].samples == 4 && INT64(tiff_ifd[raw].bytes) == INT64(raw_width) * INT64(raw_height) * 8ULL) // Sony ARQ { tiff_bps = 14; tiff_samples = 4; load_raw = &CLASS sony_arq_load_raw; filters = 0; strcpy(cdesc, "RGBG"); break; } if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 2ULL == INT64(raw_width) * INT64(raw_height) * 3ULL) #else if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3) #endif load_flags = 24; #ifdef LIBRAW_LIBRARY_BUILD if (INT64(tiff_ifd[raw].bytes) * 5ULL == INT64(raw_width) * INT64(raw_height) * 8ULL) #else if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8) #endif { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "OLYMPUS", 7) && INT64(tiff_ifd[raw].bytes) * 7ULL > INT64(raw_width) * INT64(raw_height)) #else if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height) #endif load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: #ifdef LIBRAW_LIBRARY_BUILD if ((INT64(raw_width) + 9ULL) / 10ULL * 16ULL * INT64(raw_height) == INT64(tiff_ifd[raw].bytes)) #else if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes) #endif { load_raw = &CLASS packed_load_raw; load_flags = 1; } #ifdef LIBRAW_LIBRARY_BUILD else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL) #else else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) #endif { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } #ifdef LIBRAW_LIBRARY_BUILD else if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes)) #else else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes) #endif { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); memset(cblack, 0, sizeof cblack); filters = 0; } #ifdef LIBRAW_LIBRARY_BUILD else if (INT64(raw_width) * INT64(raw_height) * 2ULL == INT64(tiff_ifd[raw].bytes)) #else else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes) #endif { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if (INT64(raw_width) * INT64(raw_height) * 3ULL == INT64(tiff_ifd[raw].bytes) * 2ULL) { load_raw = &CLASS packed_load_raw; load_flags = 80; } else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last if (INT64(tiff_ifd[raw].strip_byte_counts[i]) * 2ULL != INT64(tiff_ifd[raw].rows_per_strip) * INT64(raw_width) * 3ULL) { fit = 0; break; } if (fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") && !strstr(model2, "DEBUG RAW"))) && strncmp(software, "Nikon Scan", 10)) is_raw = 0; for (i = 0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) > thumb_width * thumb_height / (SQR(thumb_misc) + 1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make, "Imacon", 6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta(int base) { int save, tag, len, offset, high = 0, wide = 0, i, c; short sorder = order; fseek(ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save = ftell(ifp)) < offset) { for (tag = i = 0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek(ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model, "DiMAGE A200") ? 0 : 3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff(ftell(ifp)); data_offset = offset; } fseek(ifp, save + len + 8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save = ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if (ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length() - 3, 3, L"JPG"); if (!ifp->subfile_open(rawfile.c_str())) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif if (!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif ext = strrchr(ifname, '.'); file = strrchr(ifname, '/'); if (!file) file = strrchr(ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname - 1; #else if (!file) file = (char *)ifname - 1; #endif file++; if (!ext || strlen(ext) != 4 || ext - file != 8) return; jname = (char *)malloc(strlen(ifname) + 1); merror(jname, "parse_external_jpeg()"); strcpy(jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp(ext, ".jpg")) { strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg"); if (isdigit(*file)) { memcpy(jfile, file + 4, 4); memcpy(jfile + 4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp(jname, ifname)) { if ((ifp = fopen(jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Reading metadata from %s ...\n"), jname); #endif parse_tiff(12); thumb_offset = 0; is_raw = 1; fclose(ifp); } } #else if (strcmp(jname, ifname)) { if (!ifp->subfile_open(jname)) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("Failed to read metadata from %s\n"), jname); #endif } free(jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = {0x410, 0x45f3}; int i, bpp, row, col, vbits = 0; unsigned long bitbuf = 0; if ((get2(), get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i = row = 0; row < 8; row++) for (col = 0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff(int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi = -1; ushort key[] = {0x410, 0x45f3}; fseek(ifp, offset + length - 4, SEEK_SET); tboff = get4() + offset; fseek(ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek(ifp, offset + get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff(ftell(ifp), len, depth + 1); #endif if (type == 0x0810) fread(artist, 64, 1, ifp); if (type == 0x080a) { fread(make, 64, 1, ifp); fseek(ifp, strbuflen(make) - 63, SEEK_CUR); fread(model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = libraw_powf64l(2.0f, -int_to_float((get4(), get4()))); aperture = libraw_powf64l(2.0f, int_to_float(get4()) / 2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = libraw_powf64l(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(), get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = libraw_powf64l(2.0, (get2(), (short)get2()) / 64.0); #endif shutter = libraw_powf64l(2.0, -((short)get2()) / 32.0); wbi = (get2(), get2()); if (wbi > 17) wbi = 0; fseek(ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2() / 10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek(ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek(ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, o, SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp, o, SEEK_SET); } if (type == 0x580b) { if (strcmp(model, "Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek(ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0, wbi, 17)] - '0'; key[0] = key[1] = 0; } fseek(ifp, 78 + c * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0, wbi, 9)] - '0'; fseek(ifp, 2 + wbi * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(), get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if (imgdata.lens.makernotes.CanonFocalUnits > 1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD unique_id = setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime(gmtime(&timestamp)); #endif fseek(ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek(ifp, 0, SEEK_SET); memset(&t, 0, sizeof t); do { fgets(line, 128, ifp); if ((val = strchr(line, '='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line, "DAT")) sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line, "TIM")) sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line, "HDR")) thumb_offset = atoi(val); if (!strcmp(line, "X ")) raw_width = atoi(val); if (!strcmp(line, "Y ")) raw_height = atoi(val); if (!strcmp(line, "TX ")) thumb_width = atoi(val); if (!strcmp(line, "TY ")) thumb_height = atoi(val); } while (strncmp(line, "EOHD", 4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy(make, "Rollei"); strcpy(model, "d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek(ifp, 4, SEEK_SET); entries = get4(); fseek(ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread(str, 8, 1, ifp); if (!strcmp(str, "META")) meta_offset = off; if (!strcmp(str, "THUMB")) thumb_offset = off; if (!strcmp(str, "RAW0")) data_offset = off; } fseek(ifp, meta_offset + 20, SEEK_SET); fread(make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(), get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one(int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset(&ph1, 0, sizeof ph1); fseek(ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek(ifp, get4() + base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, base + data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0211: imgdata.other.SensorTemperature2 = int_to_float(data); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f)); else imgdata.lens.makernotes.CurAp = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = libraw_powf64l(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3] - '0'; break; case 0x106: for (i = 0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i] = #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff(romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data + base; break; case 0x110: meta_offset = data + base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.SensorTemperature = ph1.tag_210; #endif break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data + base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data + base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data + base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i = 0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread(model, 1, 63, ifp); if ((cp = strstr(model, " camera"))) *cp = 0; } fseek(ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek(ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy(make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy(model, "LightPhase"); break; case 2682: strcpy(model, "H 10"); break; case 4128: strcpy(model, "H 20"); break; case 5488: strcpy(model, "H 25"); break; } } void CLASS parse_fuji(int offset) { unsigned entries, tag, len, save, c; fseek(ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0, MIN(q, 2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); // IB start #ifdef LIBRAW_LIBRARY_BUILD } else if (tag == 0x110) { imgdata.sizes.raw_crop.ctop = get2(); imgdata.sizes.raw_crop.cleft = get2(); } else if (tag == 0x111) { imgdata.sizes.raw_crop.cheight = get2(); imgdata.sizes.raw_crop.cwidth = get2(); } else if ((tag == 0x122) && !strcmp(model, "DBP for GX680")) { int k = get2(); int l = get2(); /* margins? */ int m = get2(); /* margins? */ int n = get2(); // printf ("==>>0x122: height= %d l= %d m= %d width= %d\n", k, l, m, n); } else if (tag == 0x9650) { short a = (short)get2(); float b = fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2f00) { int nWBs = get4(); nWBs = MIN(nWBs, 6); for (int wb_ind = 0; wb_ind < nWBs; wb_ind++) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2(); fseek(ifp, 8, SEEK_CUR); } } else if (tag == 0x2000) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2(); } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } else if (tag == 0x2410) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2(); #endif // IB end } else if (tag == 0xc000) /* 0xc000 tag versions, second ushort; valid if the first ushort is 0 X100F 0x0259 X100T 0x0153 X-E2 0x014f 0x024f depends on firmware X-A1 0x014e XQ2 0x0150 XQ1 0x0150 X100S 0x0149 0x0249 depends on firmware X30 0x0152 X20 0x0146 X-T10 0x0154 X-T2 0x0258 X-M1 0x014d X-E2s 0x0355 X-A2 0x014e X-T20 0x025b GFX 50S 0x025a X-T1 0x0151 0x0251 0x0351 depends on firmware X70 0x0155 X-Pro2 0x0255 */ { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10") || !strcmp(model, "X-A5") || !strcmp(model, "X-A20")) { int wb[4]; int nWB, tWB, pWB; int iCCT = 0; int cnt; fseek(ifp, save + 0x200, SEEK_SET); for (int wb_ind = 0; wb_ind < 42; wb_ind++) { nWB = get4(); tWB = get4(); wb[0] = get4() << 1; wb[1] = get4(); wb[3] = get4(); wb[2] = get4() << 1; if (tWB && (iCCT < 255)) { imgdata.color.WBCT_Coeffs[iCCT][0] = tWB; for (cnt = 0; cnt < 4; cnt++) imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt]; iCCT++; } if (nWB != 70) { for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2) { if (Fuji_wb_list2[pWB] == nWB) { for (cnt = 0; cnt < 4; cnt++) imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt]; break; } } } } } else { libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len >> 1); } #endif order = c; } fseek(ifp, save + len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save + hlen) >= 0 && (save + hlen) <= ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm t; order = 0x4949; fread(tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4)) { int maxloop = 1000; get4(); while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag, "nctg", 4)) { while (ftell(ifp) + 7 < end) { i = get2(); size = get2(); if ((i + 1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek(ifp, size, SEEK_CUR); } } else if (!memcmp(tag, "IDIT", 4) && size < 64) { fread(date, 64, 1, ifp); date[size] = 0; memset(&t, 0, sizeof t); if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i = 0; i < 12 && strcasecmp(mon[i], month); i++) ; t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek(ifp, size, SEEK_CUR); } void CLASS parse_qt(int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp) + 7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread(tag, 4, 1, ifp); if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4)) parse_qt(save + size); if (!memcmp(tag, "CNDA", 4)) parse_jpeg(ftell(ifp)); fseek(ifp, save + size, SEEK_SET); } } void CLASS parse_smal(int offset, int fsize) { int ver; fseek(ifp, offset + 2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek(ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy(make, "SMaL"); sprintf(model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek(ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek(ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek(ifp, off_head + 4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(), get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek(ifp, off_setup + 792, SEEK_SET); strcpy(make, "CINE"); sprintf(model, "%d", get4()); fseek(ifp, 12, SEEK_CUR); switch ((i = get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek(ifp, 72, SEEK_CUR); switch ((get4() + 3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek(ifp, 668, SEEK_CUR); shutter = get4() / 1000000000.0; fseek(ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek(ifp, shot_select * 8, SEEK_CUR); data_offset = (INT64)get4() + 8; data_offset += (INT64)get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek(ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek(ifp, 0, SEEK_END); fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek(ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek(ifp, len - 8, SEEK_CUR); } } else { rdvo = get4(); fseek(ifp, 12, SEEK_CUR); is_raw = get4(); fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff(const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD , int internal_only #endif ) { // clang-format off static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, /* updated */ { 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } }, { "Canon EOS D60", 0, 0xfa0, /* updated */ { 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } }, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D Mark II", 0, 0x38de, /* updated */ { 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } }, { "Canon EOS 6D", 0, 0x3c82, /* skipped update */ { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 77D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 800D", 0, 0, { 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 200D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60Da", 0, 0x2ff7, /* added */ { 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } }, { "Canon EOS M6", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M5", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M2", 0, 0, /* added */ { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M100", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, /* updated */ { 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */ { 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, {"Canon PowerShot 600", 0, 0, /* added */ { -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, /* updated */ { 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } }, { "Canon PowerShot G1 X Mark III", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, /* updated */ { -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } }, { "Canon PowerShot G2", 0, 0, /* updated */ { 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, /* updated */ { 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, /* updated */ { 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X Mark II", 0, 0, { 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, /* updated */ { -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } }, { "Canon PowerShot Pro90", 0, 0, /* updated */ { -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } }, { "Canon PowerShot S30", 0, 0, /* updated */ { 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } }, { "Canon PowerShot S40", 0, 0, /* updated */ { 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } }, { "Canon PowerShot S45", 0, 0, /* updated */ { 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } }, { "Canon PowerShot S50", 0, 0, /* updated */ { 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot D10", 127, 0, /* DJC */ { 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-F1", 0, 0, /* added */ { 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } }, { "Casio EX-FH100", 0, 0, /* added */ { 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, /* updated */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F810", 0, 0, /* added */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, /* updated */ { 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100F", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A10", 0, 0, { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A20", 0, 0, /* temp */ { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-A3", 0, 0, { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-A5", 0, 0, /* temp */ { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-E3", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T20", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T10", 0, 0, /* updated */ { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-H1", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm GFX 50S", 0, 0, { 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } }, { "GITUP GIT2P", 4160, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "GITUP GIT2", 3200, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Hasselblad HV", 0, 0, /* added */ { 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } }, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Lusso", 0, 0, /* added */ { 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad 500 mech.", 0, 0, /* added */ { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad CFV", 0, 0, { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad 39-Coated", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H-39MP",0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H2D-39", 0, 0, /* added */ { 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } }, { "Hasselblad H3D-50", 0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H3D", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, { 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } }, { "Hasselblad H5D-50c",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "Hasselblad H5D-50",0, 0, { 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } }, { "Hasselblad H6D-100c",0, 0, { 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } }, { "Hasselblad X1D",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Photo Control Camerz ZDS 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf C-Most", 0, 0, /* updated */ { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus-II 8", 0, 0, /* added */ { 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } }, { "Leaf AFi-II 7", 0, 0, /* added */ { 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } }, { "Leaf Aptus-II 5", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 65S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 75S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 50", 0, 0, { 3984,0,0,0,10000,0,0,0,7666 } }, { "Leaf Credo 60", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leica M10", 0, 0, /* added */ { 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } }, { "Leica M9", 0, 0, /* added */ { 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } }, { "Leica M8", 0, 0, /* added */ { 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } }, { "Leica M (Typ 240)", 0, 0, /* added */ { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica M (Typ 262)", 0, 0, { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Leica S2", 0, 0, /* added */ { 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } }, {"Leica S-E (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, {"Leica S (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica Q (Typ 116)", 0, 0, /* updated */ { 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } }, { "Leica T (Typ 701)", 0, 0, /* added */ { 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } }, { "Leica X2", 0, 0, /* added */ { 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } }, { "Leica X1", 0, 0, /* added */ { 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } }, { "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */ { 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } }, { "Mamiya M31", 0, 0, /* added */ { 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } }, { "Mamiya M22", 0, 0, /* added */ { 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } }, { "Mamiya M18", 0, 0, /* added */ { 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, /* updated */ { 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */ { 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } }, { "Minolta DiMAGE 7i", 0, 0xf7d, /* added */ { 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } }, { "Minolta DiMAGE 7", 0, 0xf7d, /* updated */ { 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } }, { "Minolta DiMAGE A1", 0, 0xf8b, /* updated */ { 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta Maxxum 5D", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta Maxxum 7D", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, /* updated */ { 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } }, { "Nikon D2X", 0, 0, /* updated */ { 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D5600", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, /* updated */ { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D850", 0, 0, { 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } }, { "Nikon D810A", 0, 0, { 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, /* updated */ { -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } }, { "Nikon E5400", 0, 0, /* updated */ { 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } }, { "Nikon E5700", 0, 0, /* updated */ { -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Kalon", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Deneb", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, /* updated */ { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, /* updated */ { 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, /* updated */ { 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, /* updated */ { 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL9", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, { 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } }, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP565UZ", 0, 0, /* added */ { 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, /* updated */ { 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus TG-5", 0, 0, { 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax GR", 0, 0, /* added */ { 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } }, { "Pentax K-01", 0, 0, /* added */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K10D", 0, 0, /* updated */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax K-m", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax KP", 0, 0, { 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, /* updated */ { 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } }, { "Pentax K-30", 0, 0, /* updated */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K-3 II", 0, 0, /* updated */ { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-500", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-50", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, { 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } }, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax KP", 0, 0, /* temp */ { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax Q7", 0, 0, /* added */ { 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } }, { "Pentax Q10", 0, 0, /* updated */ { 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } }, { "Pentax Q", 0, 0, /* added */ { 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } }, { "Pentax MX-1", 0, 0, /* updated */ { 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* updated */ { 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } }, { "Panasonic DMC-CM10", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */ { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Leica V-LUX 1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX3", 0, 0xf7f, /* added */ { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX2", 0, 0, /* added */ { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-LUX 2", 0, 0xf7f, /* added */ { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX 3", 0, 0, /* added */ { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */ { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ2500", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZH1", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-FX180", -15, 0xfff, /* added */ { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-G9", -15, 0, { 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic AG-GH4", -15, 0, /* added */ { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, {"Panasonic DC-GH5s", -15, 0, { 6929,-2355,-708,-4192,12534,1828,-1097,1989,5195 } }, { "Panasonic DC-GH5", -15, 0, { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DC-GF10", -15, 0, /* temp, markets: GF10, GF90 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF90", -15, 0, /* temp, markets: GF10, GF90 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DC-GX9", -15, 0, /* temp */ { 7685,-2375,-634,-3687,11700,2249,-748,1546,5111 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DC-ZS200", -15, 0, /* temp, markets: ZS200 TZ200 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DC-TZ200", -15, 0, /* temp, markets: ZS200 TZ200 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One H25", 0, 0, /* added */ { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ280", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ260", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ250",0, 0, // {3984,0,0,0,10000,0,0,0,7666}}, {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */ { "Phase One IQ180", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ160", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ150", 0, 0, /* added */ {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */ // { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ140", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P 45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P 30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P 21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ3 100MP", 0, 0, /* added */ // {2423,0,0,0,9901,0,0,0,7989}}, { 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */ { "Phase One IQ3 80MP", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ3 60MP", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ3 50MP", 0, 0, /* added */ // { 3984,0,0,0,10000,0,0,0,7666 } }, {10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */ { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Polaroid x530", 0, 0, { 13458,-2556,-510,-5444,15081,205,0,0,12120 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */ { 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } }, { "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */ { 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } }, { "Ricoh GR DIGITAL 3", 0, 0, /* added */ { 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } }, { "Ricoh GR DIGITAL 4", 0, 0, /* added */ { 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Ricoh GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh RICOH GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh GXR MOUNT A12", 0, 0, /* added */ { 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } }, { "Ricoh GXR A16", 0, 0, /* added */ { 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } }, { "Ricoh GXR A12", 0, 0, /* added */ { 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } }, { "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN120", 0, 0, /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung Galaxy S7 Edge", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy S7", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy NX", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX U", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* used for NX10/NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NXF1", 0, 0, /* added */ { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */ { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma sd Quattro", 2047, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma SD9", 15, 4095, /* updated */ { 13564,-2537,-751,-5465,15154,194,-67,116,10425 } }, { "Sigma SD10", 15, 16383, /* updated */ { 6787,-1682,575,-3091,8357,160,217,-369,12314 } }, { "Sigma SD14", 15, 16383, /* updated */ { 13589,-2509,-739,-5440,15104,193,-61,105,10554 } }, { "Sigma SD15", 15, 4095, /* updated */ { 13556,-2537,-730,-5462,15144,195,-61,106,10577 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP1X", 0, 4095, /* updated */ { 13704,-2452,-857,-5413,15073,186,-89,151,9820 } }, { "Sigma DP1", 0, 4095, /* updated */ { 12774,-2591,-394,-5333,14676,207,15,-21,12127 } }, { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, {"Sony DSC-RX10M4", -800, 0, { 7699,-2566,-629,-2967,11270,1928,-378,1286,4807 } }, { "Sony DSC-RX10",0, 0, /* same for M2/M3 */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, /* updated */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, {"Sony DSC-RX0", -800, 0, /* temp */ { 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 16596, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 16596, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A550", 0, 16596, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A5", 0, 0xfeb, /* Is there any cameras not covered above? */ { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, { 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } }, { "Sony ILCE-9", 0, 0, { 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } }, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM3", 0, 0, { 6640,-1847,-503,-5238,13010,2474,-993,1673,6527 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony MODEL-NAME", 0, 0, /* added */ { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-VG30", 0, 0, /* added */ { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-VG900", 0, 0, /* added */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; // clang-format on double cam_xyz[4][3]; char name[130]; int i, j; if (colors > 4 || colors < 1) return; int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0; if (cblack[4] * cblack[5] > 0) { for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) bl64 += cblack[c + 6]; bl64 /= cblack[4] * cblack[5]; } int rblack = black + bl4 + bl64; sprintf(name, "%s %s", t_make, t_model); for (i = 0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (!dng_version) { if (table[i].t_black > 0) { black = (ushort)table[i].t_black; memset(cblack, 0, sizeof(cblack)); } else if (table[i].t_black < 0 && rblack == 0) { black = (ushort)(-table[i].t_black); memset(cblack, 0, sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort)table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j = 0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if (internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if (!internal_only) #endif cam_xyz_coeff(rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff(int index) { static const float table[][12] = {/* index 0 -- all Foveon cameras */ {1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113}, /* index 1 -- Kodak DC20 and DC25 */ {2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25}, /* index 2 -- Logitech Fotoman Pixtura */ {1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672}, /* index 3 -- Nikon E880, E900, and E990 */ {-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705}}; int i, c; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i * colors + c]; } short CLASS guess_byte_order(int words) { uchar test[4][2]; int t = 2, msb; double diff, sum[2] = {0, 0}; fread(test[0], 2, 2, ifp); for (words -= 2; words--;) { fread(test[t], 2, 1, ifp); for (msb = 0; msb < 2; msb++) { diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]); sum[msb] += diff * diff; } t = (t + 1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green(int bps, int bite, int off0, int off1) { UINT64 bitbuf = 0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; if(width > 2064) return 0.f; // too wide FORC(2) { fseek(ifp, c ? off1 : off0, SEEK_SET); for (vbits = col = 0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps); } } FORC(width - 1) { sum[c & 1] += ABS(img[0][c] - img[1][c + 1]); sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]); } return 100 * log(sum[0] / sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace((unsigned char)string[i])) string[i] = 0; else break; } } void CLASS initdata() { tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } for (int i = 0; i < 0x10000; i++) curve[i] = i; memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { {3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0}, {3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0}, {3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4}, {3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21}, {3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2}, {3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0}, {4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19}, {4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6}, }; static const ushort canon[][11] = { {1944, 1416, 0, 0, 48, 0}, {2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25}, {2224, 1456, 48, 6, 0, 2}, {2376, 1728, 12, 6, 52, 2}, {2672, 1968, 12, 6, 44, 2}, {3152, 2068, 64, 12, 0, 0, 16}, {3160, 2344, 44, 12, 4, 4}, {3344, 2484, 4, 6, 52, 6}, {3516, 2328, 42, 14, 0, 0}, {3596, 2360, 74, 12, 0, 0}, {3744, 2784, 52, 12, 8, 12}, {3944, 2622, 30, 18, 6, 2}, {3948, 2622, 42, 18, 0, 2}, {3984, 2622, 76, 20, 0, 2, 14}, {4104, 3048, 48, 12, 24, 12}, {4116, 2178, 4, 2, 0, 0}, {4152, 2772, 192, 12, 0, 0}, {4160, 3124, 104, 11, 8, 65}, {4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49}, {4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49}, {4312, 2876, 22, 18, 0, 2}, {4352, 2874, 62, 18, 0, 0}, {4476, 2954, 90, 34, 0, 0}, {4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49}, {4480, 3366, 80, 50, 0, 0}, {4496, 3366, 80, 50, 12, 0}, {4768, 3516, 96, 16, 0, 0, 0, 16}, {4832, 3204, 62, 26, 0, 0}, {4832, 3228, 62, 51, 0, 0}, {5108, 3349, 98, 13, 0, 0}, {5120, 3318, 142, 45, 62, 0}, {5280, 3528, 72, 52, 0, 0}, /* EOS M */ {5344, 3516, 142, 51, 0, 0}, {5344, 3584, 126, 100, 0, 2}, {5360, 3516, 158, 51, 0, 0}, {5568, 3708, 72, 38, 0, 0}, {5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49}, {5712, 3774, 62, 20, 10, 2}, {5792, 3804, 158, 51, 0, 0}, {5920, 3950, 122, 80, 2, 0}, {6096, 4056, 72, 34, 0, 0}, /* EOS M3 */ {6288, 4056, 266, 36, 0, 0}, /* EOS 80D */ {6384, 4224, 120, 44, 0, 0}, /* 6D II */ {6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */ {8896, 5920, 160, 64, 0, 0}, }; static const struct { ushort id; char t_model[20]; } unique[] = { {0x001, "EOS-1D"}, {0x167, "EOS-1DS"}, {0x168, "EOS 10D"}, {0x169, "EOS-1D Mark III"}, {0x170, "EOS 300D"}, {0x174, "EOS-1D Mark II"}, {0x175, "EOS 20D"}, {0x176, "EOS 450D"}, {0x188, "EOS-1Ds Mark II"}, {0x189, "EOS 350D"}, {0x190, "EOS 40D"}, {0x213, "EOS 5D"}, {0x215, "EOS-1Ds Mark III"}, {0x218, "EOS 5D Mark II"}, {0x232, "EOS-1D Mark II N"}, {0x234, "EOS 30D"}, {0x236, "EOS 400D"}, {0x250, "EOS 7D"}, {0x252, "EOS 500D"}, {0x254, "EOS 1000D"}, {0x261, "EOS 50D"}, {0x269, "EOS-1D X"}, {0x270, "EOS 550D"}, {0x281, "EOS-1D Mark IV"}, {0x285, "EOS 5D Mark III"}, {0x286, "EOS 600D"}, {0x287, "EOS 60D"}, {0x288, "EOS 1100D"}, {0x289, "EOS 7D Mark II"}, {0x301, "EOS 650D"}, {0x302, "EOS 6D"}, {0x324, "EOS-1D C"}, {0x325, "EOS 70D"}, {0x326, "EOS 700D"}, {0x327, "EOS 1200D"}, {0x328, "EOS-1D X Mark II"}, {0x331, "EOS M"}, {0x335, "EOS M2"}, {0x374, "EOS M3"}, /* temp */ {0x384, "EOS M10"}, /* temp */ {0x394, "EOS M5"}, /* temp */ {0x398, "EOS M100"}, /* temp */ {0x346, "EOS 100D"}, {0x347, "EOS 760D"}, {0x349, "EOS 5D Mark IV"}, {0x350, "EOS 80D"}, {0x382, "EOS 5DS"}, {0x393, "EOS 750D"}, {0x401, "EOS 5DS R"}, {0x404, "EOS 1300D"}, {0x405, "EOS 800D"}, {0x406, "EOS 6D Mark II"}, {0x407, "EOS M6"}, {0x408, "EOS 77D"}, {0x417, "EOS 200D"}, }, sonique[] = { {0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"}, {0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"}, {0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"}, {0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"}, {0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"}, {0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"}, {0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"}, {0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"}, {0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"}, {0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"}, {0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"}, {0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"}, {0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"}, {0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"}, {0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"}, {0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"}, {0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"}, {0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16c, "DSC-RX0"}, {0x16d, "DSC-RX10M4"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { {786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"}, {1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"}, {1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"}, {5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"}, {5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12}, {10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"}, {10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12}, {16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"}, {15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"}, {31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"}, {23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"}, {32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"}, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb {1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"}, {2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"}, {2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"}, {2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"}, {3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"}, {3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"}, {5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"}, {5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"}, {6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"}, {6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"}, {9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"}, {10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"}, {10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"}, {10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"}, {10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"}, {15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"}, {16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"}, {16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"}, {17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"}, {17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"}, {19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"}, {19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"}, {20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"}, {20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"}, {21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"}, {26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"}, {26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"}, {26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"}, {41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"}, {42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"}, // Android Raw dumps id end {20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff}, {2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078}, {5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"}, {6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"}, {6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"}, {6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"}, {7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"}, {9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"}, {9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"}, {10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"}, {10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"}, {12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"}, {15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"}, {15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"}, {15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"}, {18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"}, {18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"}, {19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"}, {21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"}, {24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"}, {30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"}, {1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"}, {3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"}, {6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"}, {7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"}, {2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"}, {4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"}, {6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"}, {7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"}, {7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"}, {7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"}, {7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"}, {7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"}, {9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"}, {10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"}, {10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"}, {10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"}, {12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"}, {12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"}, {15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"}, {18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"}, {7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"}, {787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"}, {28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"}, {15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"}, {3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"}, {307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"}, {62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"}, {4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"}, {4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160}, {2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"}, {6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160}, {460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"}, {12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556}, {18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"}, {614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"}, {15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"}, {3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212}, {1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513}, {1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"}, {2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"}, {2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"}, {4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"}, {4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"}, {5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"}, {5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"}, {7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"}, {8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"}, {5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"}, {3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"}, {4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"}, {6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"}, {10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"}, {4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"}, {4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8}, {13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"}, {6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"}, {311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"}, {16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, {2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])]; #endif static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"}; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize = 1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings); for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++) memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0])); camera_count += sizeof(const_table) / sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 = imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature = imgdata.other.exifAmbientTemperature = -1000.0f; for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } #endif memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i = 0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i = 0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek(ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if(fread(head, 1, 64, ifp) < 64) throw LIBRAW_EXCEPTION_IO_CORRUPT; libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread(head, 1, 32, ifp); #endif fseek(ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4))) { parse_phase_one(cp - head); if (cp - head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp(head + 6, "HEAPCCDR", 8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(hlen, flen - hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4)) { fseek(ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek(ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp(head + 25, "ARECOYK", 7)) { strcpy(make, "Contax"); strcpy(model, "N Digital"); fseek(ifp, 33, SEEK_SET); get_timestamp(1); fseek(ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = libraw_powf64l(2.0f, (((float)get4()) / 8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek(ifp, 88, SEEK_SET); aperture = libraw_powf64l(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = libraw_powf64l(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp(head, "PXN")) { strcpy(make, "Logitech"); strcpy(model, "Fotoman Pixtura"); } else if (!strcmp(head, "qktk")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp(head, "qktn")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp(head, "FUJIFILM", 8)) { #ifdef LIBRAW_LIBRARY_BUILD strncpy(model, head + 0x1c,0x20); model[0x20]=0; memcpy(model2, head + 0x3c, 4); model2[4] = 0; #endif fseek(ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek(ifp, 92, SEEK_SET); parse_fuji(get4()); if (thumb_offset > 120) { fseek(ifp, 120, SEEK_SET); is_raw += (i = get4()) ? 1 : 0; if (is_raw == 2 && shot_select) parse_fuji(i); } load_raw = &CLASS unpacked_load_raw; fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET); parse_tiff(data_offset = get4()); parse_tiff(thumb_offset + 12); apply_tiff(); } else if (!memcmp(head, "RIFF", 4)) { fseek(ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp(head + 4, "ftypqt ", 9)) { fseek(ifp, 0, SEEK_SET); parse_qt(fsize); is_raw = 0; } else if (!memcmp(head, "\0\001\0\001\0@", 6)) { fseek(ifp, 6, SEEK_SET); fread(make, 1, 8, ifp); fread(model, 1, 8, ifp); fread(model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp(head, "NOKIARAW", 8)) { strcpy(make, "NOKIA"); order = 0x4949; fseek(ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); // bytes count width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // Data integrity check if (width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width * height) || i > (2 * width * height)) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif switch (tiff_bps = i * 8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp(head, "ARRI", 4)) { order = 0x4949; fseek(ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy(make, "ARRI"); fseek(ifp, 668, SEEK_SET); fread(model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp(head, "XPDS", 4)) { order = 0x4949; fseek(ifp, 0x800, SEEK_SET); fread(make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek(ifp, 56, SEEK_CUR); fread(model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve(0, 12.25, 1, 1023); } else if (!memcmp(head + 4, "RED1", 4)) { strcpy(make, "Red"); strcpy(model, "One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp(head, "DSC-Image", 9)) parse_rollei(); else if (!memcmp(head, "PWAD", 4)) parse_sinar_ia(); else if (!memcmp(head, "\0MRM", 4)) parse_minolta(0); else if (!memcmp(head, "FOVb", 4)) { #ifdef LIBRAW_LIBRARY_BUILD /* no foveon support for dcraw build from libraw source */ parse_x3f(); #endif } else if (!memcmp(head, "CI", 2)) parse_cine(); if (make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize = i = 0; i < camera_count; i++) #else for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy(make, table[i].t_make); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon", 5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy(model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff ? 0 : table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); break; } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal(0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp, 0, SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); strcpy(model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); if (!strncmp(model, "ov5647", 6)) strcpy(model, "RPi OV5647 v.1"); else strcpy(model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) && fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn")) { strcpy(make, "OmniVision"); data_offset = ftell(ifp) + 0x8000 - 32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i = 0; i < sizeof corp / sizeof *corp; i++) if (strcasestr(make, corp[i])) /* Simplify company names */ strcpy(make, corp[i]); if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) && ((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION")))) *cp = 0; if (!strncasecmp(model, "PENTAX", 6)) strcpy(make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make, sizeof(make)); remove_trailing_spaces(model, sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp(model, make, i) && model[i++] == ' ') memmove(model, model + i, 64 - i); if (!strncmp(model, "FinePix ", 8)) memmove(model, model + 8,strlen(model)-7); if (!strncmp(model, "Digital Camera ", 15)) memmove(model, model + 15,strlen(model)-14); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model, "K-5", 3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model, "K-70")) { height = 4016; top_margin = 32; width = 6020; left_margin = 60; } if (width == 4736 && !strcmp(model, "K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6112 && !strcmp(model, "KP")) { /* From DNG, maybe too strict */ left_margin = 54; top_margin = 28; width = 6028; height = raw_height - top_margin; } if (width == 6080 && !strcmp(model, "K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model, "645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i = 0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff("Canon", unique[i].t_model); strcpy(model, unique[i].t_model); } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff("Sony", sonique[i].t_model); strcpy(model, sonique[i].t_model); } } if (!strncmp(make, "Nikon", 5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy(model, "C603"); } #ifndef LIBRAW_LIBRARY_BUILD if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); #else /* Always 512 for arw2_load_raw */ if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12)); #endif if (is_foveon) { if (height * 2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; } else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3)) { top_margin = 18; height = raw_height - top_margin; if (raw_width == 7392) { left_margin = 6; width = 7376; } } else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height, width); SWAP(raw_height, raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model, "PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256 / 235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model, "PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model, "PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model, "PowerShot A610")) { if (canon_s2is()) strcpy(model + 10, "S2 IS"); } else if (!strcmp(model, "PowerShot SX220 HS")) { mask[1][3] = -4; top_margin = 16; left_margin = 92; } else if (!strcmp(model, "PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model, "PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width - left_margin - 48; height = raw_height - top_margin - 14; } else if (!strcmp(model, "PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model, "EOS D2000C")) { filters = 0x61616161; if (!black) black = curve[200]; } else if (!strcmp(model, "D1")) { cam_mul[0] *= 256 / 527.0; cam_mul[2] *= 256 / 317.0; } else if (!strcmp(model, "D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000")) { height -= 3; width -= 4; } else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model, "D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model, "D5000") || !strcmp(model, "D90")) { width -= 42; } else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A")) { width -= 44; } else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4)) { width -= 46; } else if (!strcmp(model, "D4") || !strcmp(model, "Df")) { width -= 52; left_margin = 2; } else if (!strcmp(model, "D500")) { // Empty - to avoid width-1 below } else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3)) { width--; } else if (!strcmp(model, "D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model, "D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model, "D2H", 3)) { left_margin = 6; width -= 14; } else if (!strncmp(model, "D2X", 3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model, "D300", 4)) { width -= 32; } else if (!strncmp(make, "Nikon", 5) && raw_width == 4032) { if (!strcmp(model, "COOLPIX P7700")) { adobe_coeff("Nikon", "COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P7800")) { adobe_coeff("Nikon", "COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P340")) load_flags = 0; } else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2")) black = 255; } else if (!strncmp(model, "COOLPIX B700", 12)) { load_flags = 24; black = 200; } else if (!strncmp(model, "1 ", 2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy(model, "E995"); if (strcmp(model, "E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy(model, "E2500"); if (!strcmp(model, "E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model + 1) < 3700) filters = 0x49494949; if (!strcmp(model, "Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green(12, 32, 1188864, 3576832); c = find_green(12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i, c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy(make, "Minolta"); strcpy(model, "DiMAGE Z2"); } load_flags = 6 + 24 * (make[0] == 'M'); } else if (fsize == 6291456) { fseek(ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy(make, "ISG"); model[0] = 0; } } else if (!strncmp(make, "Fujifilm", 8)) { if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { left_margin = 0; top_margin = 0; width = raw_width; height = raw_height; } if (!strcmp(model + 7, "S2Pro")) { strcpy(model, "S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2) && filters >=1000) // Bayer and not X-models maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if (!strcmp(model, "GFX 50S")) { left_margin = 0; top_margin = 0; } if (!strcmp(model, "S5500")) { height -= (top_margin = 6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6]; } else if (!strcmp(model, "KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model, "KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make, "Minolta", 7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model, "DiMAGE A", 8)) { if (!strcmp(model, "DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6)) { sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M')); adobe_coeff(make, model + 20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "DiMAGE G", 8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model, "*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model, "*ist DS")) { height -= 2; } else if (!strncmp(make, "Samsung", 7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000")) { top_margin = 38; left_margin = 92; width = 5456; height = 3634; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make, "Samsung", 7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model, "EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model, "WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model, "WB550")) { strcpy(model, "WB550"); } else if (!strcmp(model, "EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin = 24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model, "STV680 VGA")) { black = 16; } else if (!strcmp(model, "N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model, "640x480")) { gamma_curve(0.45, 4.5, 1, 255); } else if (!strncmp(make, "Hasselblad", 10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if (!strncasecmp(model, "H3D", 3)) { adobe_coeff("Hasselblad", "H3DII-39"); strcpy(model, "H3DII-39"); } } else if (raw_width == 12000) // H6D 100c, A6D 100c { left_margin = 64; width = 11608; top_margin = 108; height = raw_height - top_margin; adobe_coeff("Hasselblad", "H6D-100c"); } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad", "H4D-40"); strcpy(model, "H4D-40"); } else if (raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad", "X1D"); maximum = 0xffff; tiff_bps = 16; } else if (raw_width == 9044) { if (black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H4D-60"); strcpy(model, "H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model, "H3DII-60"); } } else if (raw_width == 4090) { strcpy(model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if (!strncasecmp(model, "H5D", 3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model, "H5D-50"); } else if (!strncasecmp(model, "H3D", 3)) { black = 0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H3D-50"); strcpy(model, "H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model, "H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples + 1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make, "Sinar", 5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make, "Leaf", 4)) { maximum = 0x3fff; fseek(ifp, data_offset, SEEK_SET); if (ljpeg_start(&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy(cdesc, "RBTG"); strcpy(model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy(model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width + height == 3144 + 2060) { if (!model[0]) strcpy(model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6)) { if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height)) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; if ((height += 12) > raw_height) height = raw_height; for (i = 0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model, "C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make, "Olympus", 7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model, "E-300") || !strcmp(model, "E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset(cblack, 0, sizeof cblack); } } else if (!strcmp(model, "STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model, "E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model, "SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model, "TG-4")) { width -= 16; } else if (!strcmp(model, "TG-5")) { width -= 26; } } else if (!strcmp(model, "N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model, "DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy(cdesc, "RGBE"); } else if (!strcmp(model, "DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make, "Sony", 4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make, "Sony", 4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make, "Sony", 4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make, "Sony", 4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make, "Sony", 4) && raw_width == 6048) { width -= 24; if (strstr(model, "RX1") || strstr(model, "A99")) width -= 6; } else if (!strncmp(make, "Sony", 4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make, "Sony", 4) && raw_width == 8000) { width -= 32; } else if (!strcmp(model, "DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model, "PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve(0, 7, 1, 255); } else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP")) { order = 0x4949; if (filters && data_offset) { fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts(curve, 256); } else gamma_curve(0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model, "EasyShare", 9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make, "Kodak", 5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model, "DCS460A")) goto bw; } else if (!strcmp(model, "DCS660M")) { black = 214; goto bw; } else if (!strcmp(model, "DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model + 4, "20X")) strcpy(cdesc, "MYCY"); if (strstr(model, "DC25")) { strcpy(model, "DC25"); data_offset = 15424; } if (!strncmp(model, "DC2", 3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0 * height) / (3.0 * width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0 * height) / (373.0 * width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model, "40")) { strcpy(model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model, "DC50")) { strcpy(model, "DC50"); height = 512; width = 768; iso_speed = 84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model, "DC120")) { strcpy(model, "DC120"); raw_height = height = 976; raw_width = width = 848; iso_speed = 160; pixel_aspect = height / 0.75 / width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model, "DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed = 140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model, "Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model, "QuickTake", 9)) { if (head[5]) strcpy(model + 10, "200"); fseek(ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(), get2()) == 30 ? 738 : 736; if (height > width) { SWAP(height, width); fseek(ifp, data_offset - 6, SEEK_SET); flip = ~get2() & 3 ? 5 : 6; } filters = 0x61616161; } else if (!strncmp(make, "Rollei", 6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model, "GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model, "BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1 /* alloc in unpack() may be fooled by size adjust */ || ((int)width + (int)left_margin > 65535) || ((int)height + (int)top_margin > 65535)) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if (!model[0]) sprintf(model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if (dng_version) /* Override black level by DNG tags */ { /* copy DNG data from per-IFD field to color.dng */ int iifd = 0; // Active IFD we'll show to user. for (; iifd < tiff_nifds; iifd++) if (tiff_ifd[iifd].offset == data_offset) // found break; int pifd = -1; for (int ii = 0; ii < tiff_nifds; ii++) if (tiff_ifd[ii].offset == thumb_offset) // found { pifd = ii; break; } #define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < tiff_nifds) { int sidx; // Per field, not per structure if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2 && tiff_ifd[sidx].dng_levels.default_crop[2] > 0 && tiff_ifd[sidx].dng_levels.default_crop[3] > 0) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ maximum = imgdata.color.dng_levels.dng_whitelevel[0]; black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for (int i = 0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125) { memcpy(rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff(make, model); #ifdef LIBRAW_LIBRARY_BUILD else if (imgdata.color.cam_xyz[0][0] < 0.01) adobe_coeff(make, model, 1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff("Apple", "Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if (fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED)) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY"); if (!raw_height) raw_height = height; if (!raw_width) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if (flip > 89 || flip < -89) { switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { {0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}}; static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static const double adobe_rgb[3][3] = { {0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}}; static const double wide_rgb[3][3] = { {0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}}; static const double prophoto_rgb[3][3] = { {0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}}; static const double aces_rgb[3][3] = { {0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}}; static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb}; static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"}; static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d}; unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20}; /* bXYZ */ static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc}; unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000}; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2); #endif gamma_curve(gamm[0], gamm[1], 0, 0); memcpy(out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *)calloc(phead[0], 1); merror(oprof, "convert_to_rgb()"); memcpy(oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12 * pbody[0]; for (i = 0; i < pbody[0]; i++) { oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i * 3 + 2] = oprof[0]; oprof[0] += (pbody[i * 3 + 3] + 3) & -4; } memcpy(oprof + 32, pbody, sizeof pbody); oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1; memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite); pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16; for (i = 4; i < 7; i++) memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve); pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { for (num = k = 0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5; } for (i = 0; i < phead[0] / 4; i++) oprof[i] = htonl(oprof[i]); strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw"); strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (out_cam[i][j] = k = 0; k < 3; k++) out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color - 1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset(histogram, 0, sizeof histogram); for (img = image[0], row = 0; row < height; row++) for (col = 0; col < width; col++, img += 4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int)out[c]); } else if (document_mode) img[0] = img[fcol(row, col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort(*)[4])calloc(high, wide * sizeof *img); merror(img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2); #endif for (row = 0; row < high; row++) for (col = 0; col < wide; col++) { ur = r = fuji_width + (row - col) * step; uc = c = (row + col) * step; if (ur > height - 2 || uc > width - 2) continue; fr = r - ur; fc = c - uc; pix = image + ur * width + uc; for (i = 0; i < colors; i++) img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) + (pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr; } free(image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort(*)[4])calloc(width, newdim * sizeof *img); merror(img, "stretch()"); for (rc = row = 0; row < newdim; row++, rc += pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c * width]; if (c + 1 < height) pix1 += width * 4; for (col = 0; col < width; col++, pix0 += 4, pix1 += 4) FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort(*)[4])calloc(height, newdim * sizeof *img); merror(img, "stretch()"); for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c + 1 < width) pix1 += 4; for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4) FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } width = newdim; } free(image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2); #endif } int CLASS flip_index(int row, int col) { if (flip & 4) SWAP(row, col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct libraw_tiff_tag *tt; int c; tt = (struct libraw_tiff_tag *)(ntag + 1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count - 1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val + c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head(struct tiff_hdr *th, int full) { int c, psize = 0; struct tm *t; memset(th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4 + c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy(th->t_desc, desc, 512); strncpy(th->t_make, make, 64); strncpy(th->t_model, model, 64); strcpy(th->soft, "dcraw v" DCRAW_VERSION); t = localtime(&timestamp); sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); strncpy(th->t_artist, artist, 64); if (full) { tiff_set(th, &th->ntag, 254, 4, 1, 0); tiff_set(th, &th->ntag, 256, 4, 1, width); tiff_set(th, &th->ntag, 257, 4, 1, height); tiff_set(th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag - 1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set(th, &th->ntag, 259, 3, 1, 1); tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set(th, &th->ntag, 277, 3, 1, colors); tiff_set(th, &th->ntag, 278, 4, 1, height); tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8); } else tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0'); tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set(th, &th->ntag, 284, 3, 1, 1); tiff_set(th, &th->ntag, 296, 3, 1, 2); tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set(th, &th->ngps, 0, 1, 4, 0x202); tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy(th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc(0xff, tfp); fputc(0xd8, tfp); if (strcmp(t_humb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, tfp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, tfp); } fwrite(t_humb + 2, 1, t_humb_length - 2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp, thumb, thumb_length); free(thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); fputc(0xff, ofp); fputc(0xd8, ofp); if (strcmp(thumb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, ofp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, ofp); } fwrite(thumb + 2, 1, thumb_length - 2, ofp); free(thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white = 0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white = c = 0; c < colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height, width); ppm = (uchar *)calloc(width, colors * output_bps / 8); ppm2 = (ushort *)ppm; merror(ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head(&th, 1); fwrite(&th, sizeof th, 1, ofp); if (oprof) fwrite(oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps) - 1, cdesc); else fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1); soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, width); for (row = 0; row < height; row++, soff += rstep) { for (col = 0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col * colors + c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab((char *)ppm2, (char *)ppm2, width * colors * 2); fwrite(ppm, colors * output_bps / 8, width, ofp); } free(ppm); }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_94_0
crossvul-cpp_data_bad_93_0
/* -*- C++ -*- * File: libraw_cxx.cpp * Copyright 2008-2018 LibRaw LLC (info@libraw.org) * Created: Sat Mar 8 , 2008 * * LibRaw C++ interface (implementation) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). */ #include <math.h> #include <errno.h> #include <float.h> #include <new> #include <exception> #include <sys/types.h> #include <sys/stat.h> #if !defined(_WIN32) && !defined(__MINGW32__) #include <netinet/in.h> #else #include <winsock2.h> #endif #define LIBRAW_LIBRARY_BUILD #include "libraw/libraw.h" #include "internal/defines.h" #ifdef USE_ZLIB #include <zlib.h> #endif #ifdef USE_RAWSPEED #include "../RawSpeed/rawspeed_xmldata.cpp" #include <RawSpeed/StdAfx.h> #include <RawSpeed/FileMap.h> #include <RawSpeed/RawParser.h> #include <RawSpeed/RawDecoder.h> #include <RawSpeed/CameraMetaData.h> #include <RawSpeed/ColorFilterArray.h> #endif #ifdef USE_DNGSDK #include "dng_host.h" #include "dng_negative.h" #include "dng_simple_image.h" #include "dng_info.h" #endif #include "libraw_fuji_compressed.cpp" #ifdef __cplusplus extern "C" { #endif void default_memory_callback(void *, const char *file, const char *where) { fprintf(stderr, "%s: Out of memory in %s\n", file ? file : "unknown file", where); } void default_data_callback(void *, const char *file, const int offset) { if (offset < 0) fprintf(stderr, "%s: Unexpected end of file\n", file ? file : "unknown file"); else fprintf(stderr, "%s: data corrupted at %d\n", file ? file : "unknown file", offset); } const char *libraw_strerror(int e) { enum LibRaw_errors errorcode = (LibRaw_errors)e; switch (errorcode) { case LIBRAW_SUCCESS: return "No error"; case LIBRAW_UNSPECIFIED_ERROR: return "Unspecified error"; case LIBRAW_FILE_UNSUPPORTED: return "Unsupported file format or not RAW file"; case LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE: return "Request for nonexisting image number"; case LIBRAW_OUT_OF_ORDER_CALL: return "Out of order call of libraw function"; case LIBRAW_NO_THUMBNAIL: return "No thumbnail in file"; case LIBRAW_UNSUPPORTED_THUMBNAIL: return "Unsupported thumbnail format"; case LIBRAW_INPUT_CLOSED: return "No input stream, or input stream closed"; case LIBRAW_UNSUFFICIENT_MEMORY: return "Unsufficient memory"; case LIBRAW_DATA_ERROR: return "Corrupted data or unexpected EOF"; case LIBRAW_IO_ERROR: return "Input/output error"; case LIBRAW_CANCELLED_BY_CALLBACK: return "Cancelled by user callback"; case LIBRAW_BAD_CROP: return "Bad crop box"; default: return "Unknown error code"; } } #ifdef __cplusplus } #endif #define Sigma_X3F 22 const double LibRaw_constants::xyz_rgb[3][3] = { {0.4124564, 0.3575761, 0.1804375}, {0.2126729, 0.7151522, 0.0721750}, {0.0193339, 0.1191920, 0.9503041}}; const float LibRaw_constants::d65_white[3] = {0.95047f, 1.0f, 1.08883f}; #define P1 imgdata.idata #define S imgdata.sizes #define O imgdata.params #define C imgdata.color #define T imgdata.thumbnail #define IO libraw_internal_data.internal_output_params #define ID libraw_internal_data.internal_data #define EXCEPTION_HANDLER(e) \ do \ { \ /* fprintf(stderr,"Exception %d caught\n",e);*/ \ switch (e) \ { \ case LIBRAW_EXCEPTION_ALLOC: \ recycle(); \ return LIBRAW_UNSUFFICIENT_MEMORY; \ case LIBRAW_EXCEPTION_DECODE_RAW: \ case LIBRAW_EXCEPTION_DECODE_JPEG: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_DECODE_JPEG2000: \ recycle(); \ return LIBRAW_DATA_ERROR; \ case LIBRAW_EXCEPTION_IO_EOF: \ case LIBRAW_EXCEPTION_IO_CORRUPT: \ recycle(); \ return LIBRAW_IO_ERROR; \ case LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK: \ recycle(); \ return LIBRAW_CANCELLED_BY_CALLBACK; \ case LIBRAW_EXCEPTION_BAD_CROP: \ recycle(); \ return LIBRAW_BAD_CROP; \ default: \ return LIBRAW_UNSPECIFIED_ERROR; \ } \ } while (0) const char *LibRaw::version() { return LIBRAW_VERSION_STR; } int LibRaw::versionNumber() { return LIBRAW_VERSION; } const char *LibRaw::strerror(int p) { return libraw_strerror(p); } unsigned LibRaw::capabilities() { unsigned ret = 0; #ifdef USE_RAWSPEED ret |= LIBRAW_CAPS_RAWSPEED; #endif #ifdef USE_DNGSDK ret |= LIBRAW_CAPS_DNGSDK; #endif return ret; } unsigned LibRaw::parse_custom_cameras(unsigned limit, libraw_custom_camera_t table[], char **list) { if (!list) return 0; unsigned index = 0; for (int i = 0; i < limit; i++) { if (!list[i]) break; if (strlen(list[i]) < 10) continue; char *string = (char *)malloc(strlen(list[i]) + 1); strcpy(string, list[i]); char *start = string; memset(&table[index], 0, sizeof(table[0])); for (int j = 0; start && j < 14; j++) { char *end = strchr(start, ','); if (end) { *end = 0; end++; } // move to next char while (isspace(*start) && *start) start++; // skip leading spaces? unsigned val = strtol(start, 0, 10); switch (j) { case 0: table[index].fsize = val; break; case 1: table[index].rw = val; break; case 2: table[index].rh = val; break; case 3: table[index].lm = val; break; case 4: table[index].tm = val; break; case 5: table[index].rm = val; break; case 6: table[index].bm = val; break; case 7: table[index].lf = val; break; case 8: table[index].cf = val; break; case 9: table[index].max = val; break; case 10: table[index].flags = val; break; case 11: strncpy(table[index].t_make, start, sizeof(table[index].t_make) - 1); break; case 12: strncpy(table[index].t_model, start, sizeof(table[index].t_model) - 1); break; case 13: table[index].offset = val; break; default: break; } start = end; } free(string); if (table[index].t_make[0]) index++; } return index; } void LibRaw::derror() { if (!libraw_internal_data.unpacker_data.data_error && libraw_internal_data.internal_data.input) { if (libraw_internal_data.internal_data.input->eof()) { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), -1); throw LIBRAW_EXCEPTION_IO_EOF; } else { if (callbacks.data_cb) (*callbacks.data_cb)(callbacks.datacb_data, libraw_internal_data.internal_data.input->fname(), libraw_internal_data.internal_data.input->tell()); // throw LIBRAW_EXCEPTION_IO_CORRUPT; } } libraw_internal_data.unpacker_data.data_error++; } void LibRaw::dcraw_clear_mem(libraw_processed_image_t *p) { if (p) ::free(p); } int LibRaw::is_sraw() { return load_raw == &LibRaw::canon_sraw_load_raw || load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::is_coolscan_nef() { return load_raw == &LibRaw::nikon_coolscan_load_raw; } int LibRaw::is_jpeg_thumb() { return thumb_load_raw == 0 && write_thumb == &LibRaw::jpeg_thumb; } int LibRaw::is_nikon_sraw() { return load_raw == &LibRaw::nikon_load_sraw; } int LibRaw::sraw_midpoint() { if (load_raw == &LibRaw::canon_sraw_load_raw) return 8192; else if (load_raw == &LibRaw::nikon_load_sraw) return 2048; else return 0; } #ifdef USE_RAWSPEED using namespace RawSpeed; class CameraMetaDataLR : public CameraMetaData { public: CameraMetaDataLR() : CameraMetaData() {} CameraMetaDataLR(char *filename) : CameraMetaData(filename) {} CameraMetaDataLR(char *data, int sz); }; CameraMetaDataLR::CameraMetaDataLR(char *data, int sz) : CameraMetaData() { ctxt = xmlNewParserCtxt(); if (ctxt == NULL) { ThrowCME("CameraMetaData:Could not initialize context."); } xmlResetLastError(); doc = xmlCtxtReadMemory(ctxt, data, sz, "", NULL, XML_PARSE_DTDVALID); if (doc == NULL) { ThrowCME("CameraMetaData: XML Document could not be parsed successfully. Error was: %s", ctxt->lastError.message); } if (ctxt->valid == 0) { if (ctxt->lastError.code == 0x5e) { // printf("CameraMetaData: Unable to locate DTD, attempting to ignore."); } else { ThrowCME("CameraMetaData: XML file does not validate. DTD Error was: %s", ctxt->lastError.message); } } xmlNodePtr cur; cur = xmlDocGetRootElement(doc); if (xmlStrcmp(cur->name, (const xmlChar *)"Cameras")) { ThrowCME("CameraMetaData: XML document of the wrong type, root node is not cameras."); return; } cur = cur->xmlChildrenNode; while (cur != NULL) { if ((!xmlStrcmp(cur->name, (const xmlChar *)"Camera"))) { Camera *camera = new Camera(doc, cur); addCamera(camera); // Create cameras for aliases. for (unsigned int i = 0; i < camera->aliases.size(); i++) { addCamera(new Camera(camera, i)); } } cur = cur->next; } if (doc) xmlFreeDoc(doc); doc = 0; if (ctxt) xmlFreeParserCtxt(ctxt); ctxt = 0; } #define RAWSPEED_DATA_COUNT (sizeof(_rawspeed_data_xml) / sizeof(_rawspeed_data_xml[0])) static CameraMetaDataLR *make_camera_metadata() { int len = 0, i; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { len += strlen(_rawspeed_data_xml[i]); } char *rawspeed_xml = (char *)calloc(len + 1, sizeof(_rawspeed_data_xml[0][0])); if (!rawspeed_xml) return NULL; int offt = 0; for (i = 0; i < RAWSPEED_DATA_COUNT; i++) if (_rawspeed_data_xml[i]) { int ll = strlen(_rawspeed_data_xml[i]); if (offt + ll > len) break; memmove(rawspeed_xml + offt, _rawspeed_data_xml[i], ll); offt += ll; } rawspeed_xml[offt] = 0; CameraMetaDataLR *ret = NULL; try { ret = new CameraMetaDataLR(rawspeed_xml, offt); } catch (...) { // Mask all exceptions } free(rawspeed_xml); return ret; } #endif #define ZERO(a) memset(&a, 0, sizeof(a)) static void cleargps(libraw_gps_info_t *q) { for (int i = 0; i < 3; i++) q->latitude[i] = q->longtitude[i] = q->gpstimestamp[i] = 0.f; q->altitude = 0.f; q->altref = q->latref = q->longref = q->gpsstatus = q->gpsparsed = 0; } LibRaw::LibRaw(unsigned int flags) : memmgr(1024) { double aber[4] = {1, 1, 1, 1}; double gamm[6] = {0.45, 4.5, 0, 0, 0, 0}; unsigned greybox[4] = {0, 0, UINT_MAX, UINT_MAX}; unsigned cropbox[4] = {0, 0, UINT_MAX, UINT_MAX}; #ifdef DCRAW_VERBOSE verbose = 1; #else verbose = 0; #endif ZERO(imgdata); cleargps(&imgdata.other.parsed_gps); ZERO(libraw_internal_data); ZERO(callbacks); _rawspeed_camerameta = _rawspeed_decoder = NULL; dnghost = NULL; _x3f_data = NULL; #ifdef USE_RAWSPEED CameraMetaDataLR *camerameta = make_camera_metadata(); // May be NULL in case of exception in make_camera_metadata() _rawspeed_camerameta = static_cast<void *>(camerameta); #endif callbacks.mem_cb = (flags & LIBRAW_OPIONS_NO_MEMERR_CALLBACK) ? NULL : &default_memory_callback; callbacks.data_cb = (flags & LIBRAW_OPIONS_NO_DATAERR_CALLBACK) ? NULL : &default_data_callback; callbacks.exif_cb = NULL; // no default callback callbacks.pre_identify_cb = NULL; callbacks.post_identify_cb = NULL; callbacks.pre_subtractblack_cb = callbacks.pre_scalecolors_cb = callbacks.pre_preinterpolate_cb = callbacks.pre_interpolate_cb = callbacks.interpolate_bayer_cb = callbacks.interpolate_xtrans_cb = callbacks.post_interpolate_cb = callbacks.pre_converttorgb_cb = callbacks.post_converttorgb_cb = NULL; memmove(&imgdata.params.aber, &aber, sizeof(aber)); memmove(&imgdata.params.gamm, &gamm, sizeof(gamm)); memmove(&imgdata.params.greybox, &greybox, sizeof(greybox)); memmove(&imgdata.params.cropbox, &cropbox, sizeof(cropbox)); imgdata.params.bright = 1; imgdata.params.use_camera_matrix = 1; imgdata.params.user_flip = -1; imgdata.params.user_black = -1; imgdata.params.user_cblack[0] = imgdata.params.user_cblack[1] = imgdata.params.user_cblack[2] = imgdata.params.user_cblack[3] = -1000001; imgdata.params.user_sat = -1; imgdata.params.user_qual = -1; imgdata.params.output_color = 1; imgdata.params.output_bps = 8; imgdata.params.use_fuji_rotate = 1; imgdata.params.exp_shift = 1.0; imgdata.params.auto_bright_thr = LIBRAW_DEFAULT_AUTO_BRIGHTNESS_THRESHOLD; imgdata.params.adjust_maximum_thr = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; imgdata.params.use_rawspeed = 1; imgdata.params.use_dngsdk = LIBRAW_DNG_DEFAULT; imgdata.params.no_auto_scale = 0; imgdata.params.no_interpolation = 0; imgdata.params.raw_processing_options = LIBRAW_PROCESSING_DP2Q_INTERPOLATERG | LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF | LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT; imgdata.params.sony_arw2_posterization_thr = 0; imgdata.params.green_matching = 0; imgdata.params.custom_camera_strings = 0; imgdata.params.coolscan_nef_gamma = 1.0f; imgdata.parent_class = this; imgdata.progress_flags = 0; imgdata.color.baseline_exposure = -999.f; _exitflag = 0; tls = new LibRaw_TLS; tls->init(); } int LibRaw::set_rawspeed_camerafile(char *filename) { #ifdef USE_RAWSPEED try { CameraMetaDataLR *camerameta = new CameraMetaDataLR(filename); if (_rawspeed_camerameta) { CameraMetaDataLR *d = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete d; } _rawspeed_camerameta = static_cast<void *>(camerameta); } catch (...) { // just return error code return -1; } #endif return 0; } LibRaw::~LibRaw() { recycle(); delete tls; #ifdef USE_RAWSPEED if (_rawspeed_camerameta) { CameraMetaDataLR *cmeta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); delete cmeta; _rawspeed_camerameta = NULL; } #endif } void *LibRaw::malloc(size_t t) { void *p = memmgr.malloc(t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::realloc(void *q, size_t t) { void *p = memmgr.realloc(q, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void *LibRaw::calloc(size_t n, size_t t) { void *p = memmgr.calloc(n, t); if (!p) throw LIBRAW_EXCEPTION_ALLOC; return p; } void LibRaw::free(void *p) { memmgr.free(p); } void LibRaw::recycle_datastream() { if (libraw_internal_data.internal_data.input && libraw_internal_data.internal_data.input_internal) { delete libraw_internal_data.internal_data.input; libraw_internal_data.internal_data.input = NULL; } libraw_internal_data.internal_data.input_internal = 0; } void x3f_clear(void *); void LibRaw::recycle() { recycle_datastream(); #define FREE(a) \ do \ { \ if (a) \ { \ free(a); \ a = NULL; \ } \ } while (0) FREE(imgdata.image); FREE(imgdata.thumbnail.thumb); FREE(libraw_internal_data.internal_data.meta_data); FREE(libraw_internal_data.output_data.histogram); FREE(libraw_internal_data.output_data.oprof); FREE(imgdata.color.profile); FREE(imgdata.rawdata.ph1_cblack); FREE(imgdata.rawdata.ph1_rblack); FREE(imgdata.rawdata.raw_alloc); FREE(imgdata.idata.xmpdata); #undef FREE ZERO(imgdata.sizes); imgdata.sizes.raw_crop.cleft = 0xffff; imgdata.sizes.raw_crop.ctop = 0xffff; ZERO(imgdata.idata); ZERO(imgdata.makernotes); ZERO(imgdata.color); ZERO(imgdata.other); ZERO(imgdata.thumbnail); ZERO(imgdata.rawdata); imgdata.makernotes.olympus.OlympusCropID = -1; imgdata.makernotes.sony.raw_crop.cleft = 0xffff; imgdata.makernotes.sony.raw_crop.ctop = 0xffff; cleargps(&imgdata.other.parsed_gps); imgdata.color.baseline_exposure = -999.f; imgdata.makernotes.fuji.FujiExpoMidPointShift = -999.f; imgdata.makernotes.fuji.FujiDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiFilmMode = 0xffff; imgdata.makernotes.fuji.FujiDynamicRangeSetting = 0xffff; imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = 0xffff; imgdata.makernotes.fuji.FujiAutoDynamicRange = 0xffff; imgdata.makernotes.fuji.FocusMode = 0xffff; imgdata.makernotes.fuji.AFMode = 0xffff; imgdata.makernotes.fuji.FocusPixel[0] = imgdata.makernotes.fuji.FocusPixel[1] = 0xffff; imgdata.makernotes.fuji.ImageStabilization[0] = imgdata.makernotes.fuji.ImageStabilization[1] = imgdata.makernotes.fuji.ImageStabilization[2] = 0xffff; imgdata.makernotes.sony.SonyCameraType = 0xffff; imgdata.makernotes.sony.real_iso_offset = 0xffff; imgdata.makernotes.sony.ImageCount3_offset = 0xffff; imgdata.makernotes.sony.ElectronicFrontCurtainShutter = 0xffff; imgdata.makernotes.kodak.BlackLevelTop = 0xffff; imgdata.makernotes.kodak.BlackLevelBottom = 0xffff; imgdata.color.dng_color[0].illuminant = imgdata.color.dng_color[1].illuminant = 0xffff; for (int i = 0; i < 4; i++) imgdata.color.dng_levels.analogbalance[i] = 1.0f; ZERO(libraw_internal_data); ZERO(imgdata.lens); imgdata.lens.makernotes.CanonFocalUnits = 1; imgdata.lens.makernotes.LensID = 0xffffffffffffffffULL; ZERO(imgdata.shootinginfo); imgdata.shootinginfo.DriveMode = -1; imgdata.shootinginfo.FocusMode = -1; imgdata.shootinginfo.MeteringMode = -1; imgdata.shootinginfo.AFPoint = -1; imgdata.shootinginfo.ExposureMode = -1; imgdata.shootinginfo.ImageStabilization = -1; _exitflag = 0; #ifdef USE_RAWSPEED if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); delete d; } _rawspeed_decoder = 0; #endif if (_x3f_data) { x3f_clear(_x3f_data); _x3f_data = 0; } memmgr.cleanup(); imgdata.thumbnail.tformat = LIBRAW_THUMBNAIL_UNKNOWN; imgdata.progress_flags = 0; load_raw = thumb_load_raw = 0; tls->init(); } const char *LibRaw::unpack_function_name() { libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); return decoder_info.decoder_name; } int LibRaw::get_decoder_info(libraw_decoder_info_t *d_info) { if (!d_info) return LIBRAW_UNSPECIFIED_ERROR; d_info->decoder_name = 0; d_info->decoder_flags = 0; if (!load_raw) return LIBRAW_OUT_OF_ORDER_CALL; int rawdata = (imgdata.idata.filters || P1.colors == 1); // dcraw.c names order if (load_raw == &LibRaw::android_tight_load_raw) { d_info->decoder_name = "android_tight_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::android_loose_load_raw) { d_info->decoder_name = "android_loose_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_600_load_raw) { d_info->decoder_name = "canon_600_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::fuji_compressed_load_raw) { d_info->decoder_name = "fuji_compressed_load_raw()"; } else if (load_raw == &LibRaw::fuji_14bit_load_raw) { d_info->decoder_name = "fuji_14bit_load_raw()"; } else if (load_raw == &LibRaw::canon_load_raw) { d_info->decoder_name = "canon_load_raw()"; } else if (load_raw == &LibRaw::lossless_jpeg_load_raw) { d_info->decoder_name = "lossless_jpeg_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::canon_sraw_load_raw) { d_info->decoder_name = "canon_sraw_load_raw()"; // d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::lossless_dng_load_raw) { d_info->decoder_name = "lossless_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::packed_dng_load_raw) { d_info->decoder_name = "packed_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_ADOBECOPYPIXEL; } else if (load_raw == &LibRaw::pentax_load_raw) { d_info->decoder_name = "pentax_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_load_raw) { d_info->decoder_name = "nikon_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::nikon_coolscan_load_raw) { d_info->decoder_name = "nikon_coolscan_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_load_sraw) { d_info->decoder_name = "nikon_load_sraw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nikon_yuv_load_raw) { d_info->decoder_name = "nikon_load_yuv_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::rollei_load_raw) { // UNTESTED d_info->decoder_name = "rollei_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::phase_one_load_raw) { d_info->decoder_name = "phase_one_load_raw()"; } else if (load_raw == &LibRaw::phase_one_load_raw_c) { d_info->decoder_name = "phase_one_load_raw_c()"; } else if (load_raw == &LibRaw::hasselblad_load_raw) { d_info->decoder_name = "hasselblad_load_raw()"; } else if (load_raw == &LibRaw::leaf_hdr_load_raw) { d_info->decoder_name = "leaf_hdr_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw) { d_info->decoder_name = "unpacked_load_raw()"; } else if (load_raw == &LibRaw::unpacked_load_raw_reversed) { d_info->decoder_name = "unpacked_load_raw_reversed()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sinar_4shot_load_raw) { // UNTESTED d_info->decoder_name = "sinar_4shot_load_raw()"; } else if (load_raw == &LibRaw::imacon_full_load_raw) { d_info->decoder_name = "imacon_full_load_raw()"; } else if (load_raw == &LibRaw::hasselblad_full_load_raw) { d_info->decoder_name = "hasselblad_full_load_raw()"; } else if (load_raw == &LibRaw::packed_load_raw) { d_info->decoder_name = "packed_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::broadcom_load_raw) { // UNTESTED d_info->decoder_name = "broadcom_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::nokia_load_raw) { // UNTESTED d_info->decoder_name = "nokia_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::canon_rmf_load_raw) { // UNTESTED d_info->decoder_name = "canon_rmf_load_raw()"; } else if (load_raw == &LibRaw::panasonic_load_raw) { d_info->decoder_name = "panasonic_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::olympus_load_raw) { d_info->decoder_name = "olympus_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::minolta_rd175_load_raw) { // UNTESTED d_info->decoder_name = "minolta_rd175_load_raw()"; } else if (load_raw == &LibRaw::quicktake_100_load_raw) { // UNTESTED d_info->decoder_name = "quicktake_100_load_raw()"; } else if (load_raw == &LibRaw::kodak_radc_load_raw) { d_info->decoder_name = "kodak_radc_load_raw()"; } else if (load_raw == &LibRaw::kodak_jpeg_load_raw) { // UNTESTED + RBAYER d_info->decoder_name = "kodak_jpeg_load_raw()"; } else if (load_raw == &LibRaw::lossy_dng_load_raw) { // Check rbayer d_info->decoder_name = "lossy_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_dc120_load_raw) { d_info->decoder_name = "kodak_dc120_load_raw()"; } else if (load_raw == &LibRaw::eight_bit_load_raw) { d_info->decoder_name = "eight_bit_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c330_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_c603_load_raw) { d_info->decoder_name = "kodak_yrgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_262_load_raw) { d_info->decoder_name = "kodak_262_load_raw()"; // UNTESTED! d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_65000_load_raw) { d_info->decoder_name = "kodak_65000_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { // UNTESTED d_info->decoder_name = "kodak_ycbcr_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::kodak_rgb_load_raw) { // UNTESTED d_info->decoder_name = "kodak_rgb_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::sony_load_raw) { d_info->decoder_name = "sony_load_raw()"; } else if (load_raw == &LibRaw::sony_arw_load_raw) { d_info->decoder_name = "sony_arw_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::sony_arw2_load_raw) { d_info->decoder_name = "sony_arw2_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE | LIBRAW_DECODER_TRYRAWSPEED | LIBRAW_DECODER_SONYARW2; } else if (load_raw == &LibRaw::sony_arq_load_raw) { d_info->decoder_name = "sony_arq_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::samsung_load_raw) { d_info->decoder_name = "samsung_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_TRYRAWSPEED; } else if (load_raw == &LibRaw::samsung2_load_raw) { d_info->decoder_name = "samsung2_load_raw()"; } else if (load_raw == &LibRaw::samsung3_load_raw) { d_info->decoder_name = "samsung3_load_raw()"; } else if (load_raw == &LibRaw::smal_v6_load_raw) { // UNTESTED d_info->decoder_name = "smal_v6_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::smal_v9_load_raw) { // UNTESTED d_info->decoder_name = "smal_v9_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_FIXEDMAXC; } else if (load_raw == &LibRaw::redcine_load_raw) { d_info->decoder_name = "redcine_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_HASCURVE; } else if (load_raw == &LibRaw::x3f_load_raw) { d_info->decoder_name = "x3f_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC | LIBRAW_DECODER_FIXEDMAXC | LIBRAW_DECODER_LEGACY_WITH_MARGINS; } else if (load_raw == &LibRaw::pentax_4shot_load_raw) { d_info->decoder_name = "pentax_4shot_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::deflate_dng_load_raw) { d_info->decoder_name = "deflate_dng_load_raw()"; d_info->decoder_flags = LIBRAW_DECODER_OWNALLOC; } else if (load_raw == &LibRaw::nikon_load_striped_packed_raw) { d_info->decoder_name = "nikon_load_striped_packed_raw()"; } else { d_info->decoder_name = "Unknown unpack function"; d_info->decoder_flags = LIBRAW_DECODER_NOTSET; } return LIBRAW_SUCCESS; } int LibRaw::adjust_maximum() { ushort real_max; float auto_threshold; if (O.adjust_maximum_thr < 0.00001) return LIBRAW_SUCCESS; else if (O.adjust_maximum_thr > 0.99999) auto_threshold = LIBRAW_DEFAULT_ADJUST_MAXIMUM_THRESHOLD; else auto_threshold = O.adjust_maximum_thr; real_max = C.data_maximum; if (real_max > 0 && real_max < C.maximum && real_max > C.maximum * auto_threshold) { C.maximum = real_max; } return LIBRAW_SUCCESS; } void LibRaw::merror(void *ptr, const char *where) { if (ptr) return; if (callbacks.mem_cb) (*callbacks.mem_cb)( callbacks.memcb_data, libraw_internal_data.internal_data.input ? libraw_internal_data.internal_data.input->fname() : NULL, where); throw LIBRAW_EXCEPTION_ALLOC; } int LibRaw::open_file(const char *fname, INT64 max_buf_size) { #ifndef WIN32 struct stat st; if (stat(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #else struct _stati64 st; if (_stati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; #endif LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) int LibRaw::open_file(const wchar_t *fname, INT64 max_buf_size) { struct _stati64 st; if (_wstati64(fname, &st)) return LIBRAW_IO_ERROR; int big = (st.st_size > max_buf_size) ? 1 : 0; LibRaw_abstract_datastream *stream; try { if (big) stream = new LibRaw_bigfile_datastream(fname); else stream = new LibRaw_file_datastream(fname); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } #endif int LibRaw::open_buffer(void *buffer, size_t size) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, size); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input_internal = 0; // preserve from deletion on error int ret = open_datastream(stream); if (ret == LIBRAW_SUCCESS) { ID.input_internal = 1; // flag to delete datastream on recycle } else { delete stream; ID.input_internal = 0; } return ret; } int LibRaw::open_bayer(unsigned char *buffer, unsigned datalen, ushort _raw_width, ushort _raw_height, ushort _left_margin, ushort _top_margin, ushort _right_margin, ushort _bottom_margin, unsigned char procflags, unsigned char bayer_pattern, unsigned unused_bits, unsigned otherflags, unsigned black_level) { // this stream will close on recycle() if (!buffer || buffer == (void *)-1) return LIBRAW_IO_ERROR; LibRaw_buffer_datastream *stream; try { stream = new LibRaw_buffer_datastream(buffer, datalen); } catch (std::bad_alloc) { recycle(); return LIBRAW_UNSUFFICIENT_MEMORY; } if (!stream->valid()) { delete stream; return LIBRAW_IO_ERROR; } ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); // From identify initdata(); strcpy(imgdata.idata.make, "BayerDump"); snprintf(imgdata.idata.model, sizeof(imgdata.idata.model) - 1, "%u x %u pixels", _raw_width, _raw_height); S.flip = procflags >> 2; libraw_internal_data.internal_output_params.zero_is_bad = procflags & 2; libraw_internal_data.unpacker_data.data_offset = 0; S.raw_width = _raw_width; S.raw_height = _raw_height; S.left_margin = _left_margin; S.top_margin = _top_margin; S.width = S.raw_width - S.left_margin - _right_margin; S.height = S.raw_height - S.top_margin - _bottom_margin; imgdata.idata.filters = 0x1010101 * bayer_pattern; imgdata.idata.colors = 4 - !((imgdata.idata.filters & imgdata.idata.filters >> 1) & 0x5555); libraw_internal_data.unpacker_data.load_flags = otherflags; switch (libraw_internal_data.unpacker_data.tiff_bps = (datalen)*8 / (S.raw_width * S.raw_height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((datalen) / S.raw_height * 3 >= S.raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (libraw_internal_data.unpacker_data.load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: libraw_internal_data.unpacker_data.load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: libraw_internal_data.unpacker_data.order = 0x4949 | 0x404 * (libraw_internal_data.unpacker_data.load_flags & 1); libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags >> 4; libraw_internal_data.unpacker_data.tiff_bps -= libraw_internal_data.unpacker_data.load_flags = libraw_internal_data.unpacker_data.load_flags >> 1 & 7; load_raw = &CLASS unpacked_load_raw; } C.maximum = (1 << libraw_internal_data.unpacker_data.tiff_bps) - (1 << unused_bits); C.black = black_level; S.iwidth = S.width; S.iheight = S.height; imgdata.idata.colors = 3; imgdata.idata.filters |= ((imgdata.idata.filters >> 2 & 0x22222222) | (imgdata.idata.filters << 2 & 0x88888888)) & imgdata.idata.filters << 1; imgdata.idata.raw_count = 1; for (int i = 0; i < 4; i++) imgdata.color.pre_mul[i] = 1.0; strcpy(imgdata.idata.cdesc, "RGBG"); ID.input_internal = 1; SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); return LIBRAW_SUCCESS; } #ifdef USE_ZLIB inline unsigned int __DNG_HalfToFloat(ushort halfValue) { int sign = (halfValue >> 15) & 0x00000001; int exponent = (halfValue >> 10) & 0x0000001f; int mantissa = halfValue & 0x000003ff; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00000400)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00000400; } } else if (exponent == 31) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x1eL + 127 - 15) << 23) | (0x3ffL << 13)); } else { return 0; } } exponent += (127 - 15); mantissa <<= 13; return (unsigned int)((sign << 31) | (exponent << 23) | mantissa); } inline unsigned int __DNG_FP24ToFloat(const unsigned char *input) { int sign = (input[0] >> 7) & 0x01; int exponent = (input[0]) & 0x7F; int mantissa = (((int)input[1]) << 8) | input[2]; if (exponent == 0) { if (mantissa == 0) { return (unsigned int)(sign << 31); } else { while (!(mantissa & 0x00010000)) { mantissa <<= 1; exponent -= 1; } exponent += 1; mantissa &= ~0x00010000; } } else if (exponent == 127) { if (mantissa == 0) { return (unsigned int)((sign << 31) | ((0x7eL + 128 - 64) << 23) | (0xffffL << 7)); } else { // Nan -- Just set to zero. return 0; } } exponent += (128 - 64); mantissa <<= 7; return (uint32_t)((sign << 31) | (exponent << 23) | mantissa); } inline void DecodeDeltaBytes(unsigned char *bytePtr, int cols, int channels) { if (channels == 1) { unsigned char b0 = bytePtr[0]; bytePtr += 1; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; bytePtr[0] = b0; bytePtr += 1; } } else if (channels == 3) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; bytePtr += 3; for (int col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr += 3; } } else if (channels == 4) { unsigned char b0 = bytePtr[0]; unsigned char b1 = bytePtr[1]; unsigned char b2 = bytePtr[2]; unsigned char b3 = bytePtr[3]; bytePtr += 4; for (uint32_t col = 1; col < cols; ++col) { b0 += bytePtr[0]; b1 += bytePtr[1]; b2 += bytePtr[2]; b3 += bytePtr[3]; bytePtr[0] = b0; bytePtr[1] = b1; bytePtr[2] = b2; bytePtr[3] = b3; bytePtr += 4; } } else { for (int col = 1; col < cols; ++col) { for (int chan = 0; chan < channels; ++chan) { bytePtr[chan + channels] += bytePtr[chan]; } bytePtr += channels; } } } static void DecodeFPDelta(unsigned char *input, unsigned char *output, int cols, int channels, int bytesPerSample) { DecodeDeltaBytes(input, cols * bytesPerSample, channels); int32_t rowIncrement = cols * channels; if (bytesPerSample == 2) { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; #else const unsigned char *input1 = input; const unsigned char *input0 = input + rowIncrement; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output += 2; } } else if (bytesPerSample == 3) { const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output += 3; } } else { #if LibRawBigEndian const unsigned char *input0 = input; const unsigned char *input1 = input + rowIncrement; const unsigned char *input2 = input + rowIncrement * 2; const unsigned char *input3 = input + rowIncrement * 3; #else const unsigned char *input3 = input; const unsigned char *input2 = input + rowIncrement; const unsigned char *input1 = input + rowIncrement * 2; const unsigned char *input0 = input + rowIncrement * 3; #endif for (int col = 0; col < rowIncrement; ++col) { output[0] = input0[col]; output[1] = input1[col]; output[2] = input2[col]; output[3] = input3[col]; output += 4; } } } static float expandFloats(unsigned char *dst, int tileWidth, int bytesps) { float max = 0.f; if (bytesps == 2) { uint16_t *dst16 = (ushort *)dst; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index) { dst32[index] = __DNG_HalfToFloat(dst16[index]); max = MAX(max, f32[index]); } } else if (bytesps == 3) { uint8_t *dst8 = ((unsigned char *)dst) + (tileWidth - 1) * 3; uint32_t *dst32 = (unsigned int *)dst; float *f32 = (float *)dst; for (int index = tileWidth - 1; index >= 0; --index, dst8 -= 3) { dst32[index] = __DNG_FP24ToFloat(dst8); max = MAX(max, f32[index]); } } else if (bytesps == 4) { float *f32 = (float *)dst; for (int index = 0; index < tileWidth; index++) max = MAX(max, f32[index]); } return max; } void LibRaw::deflate_dng_load_raw() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) { throw LIBRAW_EXCEPTION_DECODE_RAW; } float *float_raw_image = 0; float max = 0.f; if (ifd->samples != 1 && ifd->samples != 3 && ifd->samples != 4) throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported if (libraw_internal_data.unpacker_data.tiff_samples != ifd->samples) throw LIBRAW_EXCEPTION_DECODE_RAW; // Wrong IFD size_t tilesH = (imgdata.sizes.raw_width + libraw_internal_data.unpacker_data.tile_width - 1) / libraw_internal_data.unpacker_data.tile_width; size_t tilesV = (imgdata.sizes.raw_height + libraw_internal_data.unpacker_data.tile_length - 1) / libraw_internal_data.unpacker_data.tile_length; size_t tileCnt = tilesH * tilesV; if (ifd->sample_format == 3) { // Floating point data float_raw_image = (float *)calloc(tileCnt * libraw_internal_data.unpacker_data.tile_length * libraw_internal_data.unpacker_data.tile_width * ifd->samples, sizeof(float)); // imgdata.color.maximum = 65535; // imgdata.color.black = 0; // memset(imgdata.color.cblack,0,sizeof(imgdata.color.cblack)); } else throw LIBRAW_EXCEPTION_DECODE_RAW; // Only float deflated supported int xFactor; switch (ifd->predictor) { case 3: default: xFactor = 1; break; case 34894: xFactor = 2; break; case 34895: xFactor = 4; break; } if (libraw_internal_data.unpacker_data.tile_length < INT_MAX) { if (tileCnt < 1 || tileCnt > 1000000) throw LIBRAW_EXCEPTION_DECODE_RAW; size_t *tOffsets = (size_t *)malloc(tileCnt * sizeof(size_t)); for (int t = 0; t < tileCnt; ++t) tOffsets[t] = get4(); size_t *tBytes = (size_t *)malloc(tileCnt * sizeof(size_t)); unsigned long maxBytesInTile = 0; if (tileCnt == 1) tBytes[0] = maxBytesInTile = ifd->bytes; else { libraw_internal_data.internal_data.input->seek(ifd->bytes, SEEK_SET); for (size_t t = 0; t < tileCnt; ++t) { tBytes[t] = get4(); maxBytesInTile = MAX(maxBytesInTile, tBytes[t]); } } unsigned tilePixels = libraw_internal_data.unpacker_data.tile_width * libraw_internal_data.unpacker_data.tile_length; unsigned pixelSize = sizeof(float) * ifd->samples; unsigned tileBytes = tilePixels * pixelSize; unsigned tileRowBytes = libraw_internal_data.unpacker_data.tile_width * pixelSize; unsigned char *cBuffer = (unsigned char *)malloc(maxBytesInTile); unsigned char *uBuffer = (unsigned char *)malloc(tileBytes + tileRowBytes); // extra row for decoding for (size_t y = 0, t = 0; y < imgdata.sizes.raw_height; y += libraw_internal_data.unpacker_data.tile_length) { for (size_t x = 0; x < imgdata.sizes.raw_width; x += libraw_internal_data.unpacker_data.tile_width, ++t) { libraw_internal_data.internal_data.input->seek(tOffsets[t], SEEK_SET); libraw_internal_data.internal_data.input->read(cBuffer, 1, tBytes[t]); unsigned long dstLen = tileBytes; int err = uncompress(uBuffer + tileRowBytes, &dstLen, cBuffer, tBytes[t]); if (err != Z_OK) { free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); throw LIBRAW_EXCEPTION_DECODE_RAW; return; } else { int bytesps = ifd->bps >> 3; size_t rowsInTile = y + libraw_internal_data.unpacker_data.tile_length > imgdata.sizes.raw_height ? imgdata.sizes.raw_height - y : libraw_internal_data.unpacker_data.tile_length; size_t colsInTile = x + libraw_internal_data.unpacker_data.tile_width > imgdata.sizes.raw_width ? imgdata.sizes.raw_width - x : libraw_internal_data.unpacker_data.tile_width; for (size_t row = 0; row < rowsInTile; ++row) // do not process full tile if not needed { unsigned char *dst = uBuffer + row * libraw_internal_data.unpacker_data.tile_width * bytesps * ifd->samples; unsigned char *src = dst + tileRowBytes; DecodeFPDelta(src, dst, libraw_internal_data.unpacker_data.tile_width / xFactor, ifd->samples * xFactor, bytesps); float lmax = expandFloats(dst, libraw_internal_data.unpacker_data.tile_width * ifd->samples, bytesps); max = MAX(max, lmax); unsigned char *dst2 = (unsigned char *)&float_raw_image[((y + row) * imgdata.sizes.raw_width + x) * ifd->samples]; memmove(dst2, dst, colsInTile * ifd->samples * sizeof(float)); } } } } free(tOffsets); free(tBytes); free(cBuffer); free(uBuffer); } imgdata.color.fmaximum = max; // Set fields according to data format imgdata.rawdata.raw_alloc = float_raw_image; if (ifd->samples == 1) { imgdata.rawdata.float_image = float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 4; } else if (ifd->samples == 3) { imgdata.rawdata.float3_image = (float(*)[3])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 12; } else if (ifd->samples == 4) { imgdata.rawdata.float4_image = (float(*)[4])float_raw_image; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 16; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_CONVERTFLOAT_TO_INT) convertFloatToInt(); // with default settings } #else void LibRaw::deflate_dng_load_raw() { throw LIBRAW_EXCEPTION_DECODE_RAW; } #endif int LibRaw::is_floating_point() { struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) return 0; return ifd->sample_format == 3; } int LibRaw::have_fpdata() { return imgdata.rawdata.float_image || imgdata.rawdata.float3_image || imgdata.rawdata.float4_image; } void LibRaw::convertFloatToInt(float dmin /* =4096.f */, float dmax /* =32767.f */, float dtarget /*= 16383.f */) { int samples = 0; float *data = 0; if (imgdata.rawdata.float_image) { samples = 1; data = imgdata.rawdata.float_image; } else if (imgdata.rawdata.float3_image) { samples = 3; data = (float *)imgdata.rawdata.float3_image; } else if (imgdata.rawdata.float4_image) { samples = 4; data = (float *)imgdata.rawdata.float4_image; } else return; ushort *raw_alloc = (ushort *)malloc(imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples * sizeof(ushort)); float tmax = MAX(imgdata.color.maximum, 1); float datamax = imgdata.color.fmaximum; tmax = MAX(tmax, datamax); tmax = MAX(tmax, 1.f); float multip = 1.f; if (tmax < dmin || tmax > dmax) { imgdata.rawdata.color.fnorm = imgdata.color.fnorm = multip = dtarget / tmax; imgdata.rawdata.color.maximum = imgdata.color.maximum = dtarget; imgdata.rawdata.color.black = imgdata.color.black = (float)imgdata.color.black * multip; for (int i = 0; i < sizeof(imgdata.color.cblack) / sizeof(imgdata.color.cblack[0]); i++) if (i != 4 && i != 5) imgdata.rawdata.color.cblack[i] = imgdata.color.cblack[i] = (float)imgdata.color.cblack[i] * multip; } else imgdata.rawdata.color.fnorm = imgdata.color.fnorm = 0.f; for (size_t i = 0; i < imgdata.sizes.raw_height * imgdata.sizes.raw_width * libraw_internal_data.unpacker_data.tiff_samples; ++i) { float val = MAX(data[i], 0.f); raw_alloc[i] = (ushort)(val * multip); } if (samples == 1) { imgdata.rawdata.raw_alloc = imgdata.rawdata.raw_image = raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 2; } else if (samples == 3) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color3_image = (ushort(*)[3])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; } else if (samples == 4) { imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = (ushort(*)[4])raw_alloc; imgdata.rawdata.sizes.raw_pitch = imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; } free(data); // remove old allocation imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; imgdata.rawdata.float4_image = 0; } void LibRaw::sony_arq_load_raw() { int row, col; read_shorts(imgdata.rawdata.raw_image, imgdata.sizes.raw_width * imgdata.sizes.raw_height * 4); for (row = 0; row < imgdata.sizes.raw_height; row++) { unsigned short(*rowp)[4] = (unsigned short(*)[4]) & imgdata.rawdata.raw_image[row * imgdata.sizes.raw_width * 4]; for (col = 0; col < imgdata.sizes.raw_width; col++) { unsigned short g2 = rowp[col][2]; rowp[col][2] = rowp[col][3]; rowp[col][3] = g2; if (((unsigned)(row - imgdata.sizes.top_margin) < imgdata.sizes.height) && ((unsigned)(col - imgdata.sizes.left_margin) < imgdata.sizes.width) && (MAX(MAX(rowp[col][0], rowp[col][1]), MAX(rowp[col][2], rowp[col][3])) > imgdata.color.maximum)) derror(); } } } void LibRaw::pentax_4shot_load_raw() { ushort *plane = (ushort *)malloc(imgdata.sizes.raw_width * imgdata.sizes.raw_height * sizeof(ushort)); int alloc_sz = imgdata.sizes.raw_width * (imgdata.sizes.raw_height + 16) * 4 * sizeof(ushort); ushort(*result)[4] = (ushort(*)[4])malloc(alloc_sz); struct movement_t { int row, col; } _move[4] = { {1, 1}, {0, 1}, {0, 0}, {1, 0}, }; int tidx = 0; for (int i = 0; i < 4; i++) { int move_row, move_col; if (imgdata.params.p4shot_order[i] >= '0' && imgdata.params.p4shot_order[i] <= '3') { move_row = (imgdata.params.p4shot_order[i] - '0' & 2) ? 1 : 0; move_col = (imgdata.params.p4shot_order[i] - '0' & 1) ? 1 : 0; } else { move_row = _move[i].row; move_col = _move[i].col; } for (; tidx < 16; tidx++) if (tiff_ifd[tidx].t_width == imgdata.sizes.raw_width && tiff_ifd[tidx].t_height == imgdata.sizes.raw_height && tiff_ifd[tidx].bps > 8 && tiff_ifd[tidx].samples == 1) break; if (tidx >= 16) break; imgdata.rawdata.raw_image = plane; ID.input->seek(tiff_ifd[tidx].offset, SEEK_SET); imgdata.idata.filters = 0xb4b4b4b4; libraw_internal_data.unpacker_data.data_offset = tiff_ifd[tidx].offset; (this->*pentax_component_load_raw)(); for (int row = 0; row < imgdata.sizes.raw_height - move_row; row++) { int colors[2]; for (int c = 0; c < 2; c++) colors[c] = COLOR(row, c); ushort *srcrow = &plane[imgdata.sizes.raw_width * row]; ushort(*dstrow)[4] = &result[(imgdata.sizes.raw_width) * (row + move_row) + move_col]; for (int col = 0; col < imgdata.sizes.raw_width - move_col; col++) dstrow[col][colors[col % 2]] = srcrow[col]; } tidx++; } // assign things back: imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 8; imgdata.idata.filters = 0; imgdata.rawdata.raw_alloc = imgdata.rawdata.color4_image = result; free(plane); imgdata.rawdata.raw_image = 0; } void LibRaw::hasselblad_full_load_raw() { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) { read_shorts(&imgdata.image[row * S.width + col][2], 1); // B read_shorts(&imgdata.image[row * S.width + col][1], 1); // G read_shorts(&imgdata.image[row * S.width + col][0], 1); // R } } static inline void unpack7bytesto4x16(unsigned char *src, unsigned short *dest) { dest[0] = (src[0] << 6) | (src[1] >> 2); dest[1] = ((src[1] & 0x3) << 12) | (src[2] << 4) | (src[3] >> 4); dest[2] = (src[3] & 0xf) << 10 | (src[4] << 2) | (src[5] >> 6); dest[3] = ((src[5] & 0x3f) << 8) | src[6]; } static inline void unpack28bytesto16x16ns(unsigned char *src, unsigned short *dest) { dest[0] = (src[3] << 6) | (src[2] >> 2); dest[1] = ((src[2] & 0x3) << 12) | (src[1] << 4) | (src[0] >> 4); dest[2] = (src[0] & 0xf) << 10 | (src[7] << 2) | (src[6] >> 6); dest[3] = ((src[6] & 0x3f) << 8) | src[5]; dest[4] = (src[4] << 6) | (src[11] >> 2); dest[5] = ((src[11] & 0x3) << 12) | (src[10] << 4) | (src[9] >> 4); dest[6] = (src[9] & 0xf) << 10 | (src[8] << 2) | (src[15] >> 6); dest[7] = ((src[15] & 0x3f) << 8) | src[14]; dest[8] = (src[13] << 6) | (src[12] >> 2); dest[9] = ((src[12] & 0x3) << 12) | (src[19] << 4) | (src[18] >> 4); dest[10] = (src[18] & 0xf) << 10 | (src[17] << 2) | (src[16] >> 6); dest[11] = ((src[16] & 0x3f) << 8) | src[23]; dest[12] = (src[22] << 6) | (src[21] >> 2); dest[13] = ((src[21] & 0x3) << 12) | (src[20] << 4) | (src[27] >> 4); dest[14] = (src[27] & 0xf) << 10 | (src[26] << 2) | (src[25] >> 6); dest[15] = ((src[25] & 0x3f) << 8) | src[24]; } #define swab32(x) \ ((unsigned int)((((unsigned int)(x) & (unsigned int)0x000000ffUL) << 24) | \ (((unsigned int)(x) & (unsigned int)0x0000ff00UL) << 8) | \ (((unsigned int)(x) & (unsigned int)0x00ff0000UL) >> 8) | \ (((unsigned int)(x) & (unsigned int)0xff000000UL) >> 24))) static inline void swab32arr(unsigned *arr, unsigned len) { for (unsigned i = 0; i < len; i++) arr[i] = swab32(arr[i]); } #undef swab32 void LibRaw::fuji_14bit_load_raw() { const unsigned linelen = S.raw_width * 7 / 4; const unsigned pitch = S.raw_pitch ? S.raw_pitch / 2 : S.raw_width; unsigned char *buf = (unsigned char *)malloc(linelen); merror(buf, "fuji_14bit_load_raw()"); for (int row = 0; row < S.raw_height; row++) { unsigned bytesread = libraw_internal_data.internal_data.input->read(buf, 1, linelen); unsigned short *dest = &imgdata.rawdata.raw_image[pitch * row]; if (bytesread % 28) { swab32arr((unsigned *)buf, bytesread / 4); for (int sp = 0, dp = 0; dp < pitch - 3 && sp < linelen - 6 && sp < bytesread - 6; sp += 7, dp += 4) unpack7bytesto4x16(buf + sp, dest + dp); } else for (int sp = 0, dp = 0; dp < pitch - 15 && sp < linelen - 27 && sp < bytesread - 27; sp += 28, dp += 16) unpack28bytesto16x16ns(buf + sp, dest + dp); } free(buf); } void LibRaw::nikon_load_striped_packed_raw() { int vbits = 0, bwide, rbits, bite, row, col, val, i; UINT64 bitbuf = 0; unsigned load_flags = 24; // libraw_internal_data.unpacker_data.load_flags; unsigned tiff_bps = libraw_internal_data.unpacker_data.tiff_bps; int tiff_compress = libraw_internal_data.unpacker_data.tiff_compress; struct tiff_ifd_t *ifd = &tiff_ifd[0]; while (ifd < &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds] && ifd->offset != libraw_internal_data.unpacker_data.data_offset) ++ifd; if (ifd == &tiff_ifd[libraw_internal_data.identify_data.tiff_nifds]) throw LIBRAW_EXCEPTION_DECODE_RAW; if (!ifd->rows_per_strip || !ifd->strip_offsets_count) return; // not unpacked int stripcnt = 0; bwide = S.raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - S.raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); for (row = 0; row < S.raw_height; row++) { checkCancel(); if (!(row % ifd->rows_per_strip)) { if (stripcnt >= ifd->strip_offsets_count) return; // run out of data libraw_internal_data.internal_data.input->seek(ifd->strip_offsets[stripcnt], SEEK_SET); stripcnt++; } for (col = 0; col < S.raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(libraw_internal_data.internal_data.input->get_char() << i); } imgdata.rawdata.raw_image[(row)*S.raw_width + (col)] = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); } vbits -= rbits; } } struct foveon_data_t { const char *make; const char *model; const int raw_width, raw_height; const int white; const int left_margin, top_margin; const int width, height; } foveon_data[] = { {"Sigma", "SD9", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD9", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD10", 2304, 1531, 12000, 20, 8, 2266, 1510}, {"Sigma", "SD10", 1152, 763, 12000, 10, 2, 1132, 755}, {"Sigma", "SD14", 2688, 1792, 14000, 18, 12, 2651, 1767}, {"Sigma", "SD14", 2688, 896, 14000, 18, 6, 2651, 883}, // 2/3 {"Sigma", "SD14", 1344, 896, 14000, 9, 6, 1326, 883}, // 1/2 {"Sigma", "SD15", 2688, 1792, 2900, 18, 12, 2651, 1767}, {"Sigma", "SD15", 2688, 896, 2900, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "SD15", 1344, 896, 2900, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1", 2688, 1792, 2100, 18, 12, 2651, 1767}, {"Sigma", "DP1", 2688, 896, 2100, 18, 6, 2651, 883}, // 2/3 ? {"Sigma", "DP1", 1344, 896, 2100, 9, 6, 1326, 883}, // 1/2 ? {"Sigma", "DP1S", 2688, 1792, 2200, 18, 12, 2651, 1767}, {"Sigma", "DP1S", 2688, 896, 2200, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1S", 1344, 896, 2200, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP1X", 2688, 1792, 3560, 18, 12, 2651, 1767}, {"Sigma", "DP1X", 2688, 896, 3560, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP1X", 1344, 896, 3560, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2", 2688, 1792, 2326, 13, 16, 2651, 1767}, {"Sigma", "DP2", 2688, 896, 2326, 13, 8, 2651, 883}, // 2/3 ?? {"Sigma", "DP2", 1344, 896, 2326, 7, 8, 1325, 883}, // 1/2 ?? {"Sigma", "DP2S", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2S", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2S", 1344, 896, 2300, 9, 6, 1326, 883}, // 1/2 {"Sigma", "DP2X", 2688, 1792, 2300, 18, 12, 2651, 1767}, {"Sigma", "DP2X", 2688, 896, 2300, 18, 6, 2651, 883}, // 2/3 {"Sigma", "DP2X", 1344, 896, 2300, 9, 6, 1325, 883}, // 1/2 {"Sigma", "SD1", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "SD1 Merrill", 4928, 3264, 3900, 12, 52, 4807, 3205}, // Full size {"Sigma", "SD1 Merrill", 4928, 1632, 3900, 12, 26, 4807, 1603}, // 2/3 size {"Sigma", "SD1 Merrill", 2464, 1632, 3900, 6, 26, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP1 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP1 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP2 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP2 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP2 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Sigma", "DP3 Merrill", 4928, 3264, 3900, 12, 0, 4807, 3205}, {"Sigma", "DP3 Merrill", 2464, 1632, 3900, 12, 0, 2403, 1603}, // 1/2 size {"Sigma", "DP3 Merrill", 4928, 1632, 3900, 12, 0, 4807, 1603}, // 2/3 size {"Polaroid", "x530", 1440, 1088, 2700, 10, 13, 1419, 1059}, // dp2 Q {"Sigma", "dp3 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp3 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp2 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp2 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp1 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp1 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size {"Sigma", "dp0 Quattro", 5888, 3672, 16383, 204, 24, 5446, 3624}, // full size {"Sigma", "dp0 Quattro", 2944, 1836, 16383, 102, 12, 2723, 1812}, // half size // Sigma sd Quattro {"Sigma", "sd Quattro", 5888, 3776, 16383, 204, 76, 5446, 3624}, // full size {"Sigma", "sd Quattro", 2944, 1888, 16383, 102, 38, 2723, 1812}, // half size // Sd Quattro H {"Sigma", "sd Quattro H", 6656, 4480, 16383, 224, 160, 6208, 4160}, // full size {"Sigma", "sd Quattro H", 3328, 2240, 16383, 112, 80, 3104, 2080}, // half size {"Sigma", "sd Quattro H", 5504, 3680, 16383, 0, 4, 5496, 3668}, // full size {"Sigma", "sd Quattro H", 2752, 1840, 16383, 0, 2, 2748, 1834}, // half size }; const int foveon_count = sizeof(foveon_data) / sizeof(foveon_data[0]); int LibRaw::open_datastream(LibRaw_abstract_datastream *stream) { if (!stream) return ENOENT; if (!stream->valid()) return LIBRAW_IO_ERROR; recycle(); if(callbacks.pre_identify_cb) { int r = (callbacks.pre_identify_cb)(this); if(r == 1) goto final; } try { ID.input = stream; SET_PROC_FLAG(LIBRAW_PROGRESS_OPEN); identify(); if(callbacks.post_identify_cb) (callbacks.post_identify_cb)(this); #if 0 if(!strcasecmp(imgdata.idata.make, "Sony") && imgdata.color.maximum > 0 && imgdata.color.linear_max[0] > imgdata.color.maximum*3 && imgdata.color.linear_max[0] <= imgdata.color.maximum*4) for(int c = 0; c<4; c++) imgdata.color.linear_max[c] /= 4; #endif if (!strcasecmp(imgdata.idata.make, "Canon") && (load_raw == &LibRaw::canon_sraw_load_raw) && imgdata.sizes.raw_width > 0) { float ratio = float(imgdata.sizes.raw_height) / float(imgdata.sizes.raw_width); if ((ratio < 0.57 || ratio > 0.75) && imgdata.makernotes.canon.SensorHeight > 1 && imgdata.makernotes.canon.SensorWidth > 1) { imgdata.sizes.raw_width = imgdata.makernotes.canon.SensorWidth; imgdata.sizes.left_margin = imgdata.makernotes.canon.SensorLeftBorder; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.makernotes.canon.SensorRightBorder - imgdata.makernotes.canon.SensorLeftBorder + 1; imgdata.sizes.raw_height = imgdata.makernotes.canon.SensorHeight; imgdata.sizes.top_margin = imgdata.makernotes.canon.SensorTopBorder; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.makernotes.canon.SensorBottomBorder - imgdata.makernotes.canon.SensorTopBorder + 1; libraw_internal_data.unpacker_data.load_flags |= 256; // reset width/height in canon_sraw_load_raw() imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } else if (imgdata.sizes.raw_width == 4032 && imgdata.sizes.raw_height == 3402 && !strcasecmp(imgdata.idata.model, "EOS 80D")) // 80D hardcoded { imgdata.sizes.raw_width = 4536; imgdata.sizes.left_margin = 28; imgdata.sizes.iwidth = imgdata.sizes.width = imgdata.sizes.raw_width - imgdata.sizes.left_margin; imgdata.sizes.raw_height = 3024; imgdata.sizes.top_margin = 8; imgdata.sizes.iheight = imgdata.sizes.height = imgdata.sizes.raw_height - imgdata.sizes.top_margin; libraw_internal_data.unpacker_data.load_flags |= 256; imgdata.sizes.raw_pitch = 8 * imgdata.sizes.raw_width; } } // XTrans Compressed? if (!imgdata.idata.dng_version && !strcasecmp(imgdata.idata.make, "Fujifilm") && (load_raw == &LibRaw::unpacked_load_raw)) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 2 != libraw_internal_data.unpacker_data.data_size) { if (imgdata.sizes.raw_width * imgdata.sizes.raw_height * 7 / 4 == libraw_internal_data.unpacker_data.data_size) load_raw = &LibRaw::fuji_14bit_load_raw; else parse_fuji_compressed_header(); } if (imgdata.idata.filters == 9) { // Adjust top/left margins for X-Trans int newtm = imgdata.sizes.top_margin % 6 ? (imgdata.sizes.top_margin / 6 + 1) * 6 : imgdata.sizes.top_margin; int newlm = imgdata.sizes.left_margin % 6 ? (imgdata.sizes.left_margin / 6 + 1) * 6 : imgdata.sizes.left_margin; if (newtm != imgdata.sizes.top_margin || newlm != imgdata.sizes.left_margin) { imgdata.sizes.height -= (newtm - imgdata.sizes.top_margin); imgdata.sizes.top_margin = newtm; imgdata.sizes.width -= (newlm - imgdata.sizes.left_margin); imgdata.sizes.left_margin = newlm; for (int c1 = 0; c1 < 6; c1++) for (int c2 = 0; c2 < 6; c2++) imgdata.idata.xtrans[c1][c2] = imgdata.idata.xtrans_abs[c1][c2]; } } } // Fix DNG white balance if needed if (imgdata.idata.dng_version && (imgdata.idata.filters == 0) && imgdata.idata.colors > 1 && imgdata.idata.colors < 5) { float delta[4] = {0.f, 0.f, 0.f, 0.f}; int black[4]; for (int c = 0; c < 4; c++) black[c] = imgdata.color.dng_levels.dng_black + imgdata.color.dng_levels.dng_cblack[c]; for (int c = 0; c < imgdata.idata.colors; c++) delta[c] = imgdata.color.dng_levels.dng_whitelevel[c] - black[c]; float mindelta = delta[0], maxdelta = delta[0]; for (int c = 1; c < imgdata.idata.colors; c++) { if (mindelta > delta[c]) mindelta = delta[c]; if (maxdelta < delta[c]) maxdelta = delta[c]; } if (mindelta > 1 && maxdelta < (mindelta * 20)) // safety { for (int c = 0; c < imgdata.idata.colors; c++) { imgdata.color.cam_mul[c] /= (delta[c] / maxdelta); imgdata.color.pre_mul[c] /= (delta[c] / maxdelta); } imgdata.color.maximum = imgdata.color.cblack[0] + maxdelta; } } if (imgdata.idata.dng_version && ((!strcasecmp(imgdata.idata.make, "Leica") && !strcasecmp(imgdata.idata.model, "D-LUX (Typ 109)")) || (!strcasecmp(imgdata.idata.make, "Panasonic") && !strcasecmp(imgdata.idata.model, "LX100")))) imgdata.sizes.width = 4288; if (!strncasecmp(imgdata.idata.make, "Sony", 4) && imgdata.idata.dng_version && !(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP)) { if (S.raw_width == 3984) S.width = 3925; else if (S.raw_width == 4288) S.width = S.raw_width - 32; else if (S.raw_width == 4928 && S.height < 3280) S.width = S.raw_width - 8; else if (S.raw_width == 5504) S.width = S.raw_width - (S.height > 3664 ? 8 : 32); } if (!strcasecmp(imgdata.idata.make, "Pentax") && /*!strcasecmp(imgdata.idata.model,"K-3 II") &&*/ imgdata.idata.raw_count == 4 && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_PENTAX_PS_ALLFRAMES)) { imgdata.idata.raw_count = 1; imgdata.idata.filters = 0; imgdata.idata.colors = 4; IO.mix_green = 1; pentax_component_load_raw = load_raw; load_raw = &LibRaw::pentax_4shot_load_raw; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Leaf") && !strcmp(imgdata.idata.model, "Credo 50")) { imgdata.color.pre_mul[0] = 1.f / 0.3984f; imgdata.color.pre_mul[2] = 1.f / 0.7666f; imgdata.color.pre_mul[1] = imgdata.color.pre_mul[3] = 1.0; } // S3Pro DNG patch if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S3Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && !strcmp(imgdata.idata.model, "S5Pro") && imgdata.sizes.raw_width == 4288) { imgdata.sizes.left_margin++; imgdata.sizes.width--; } if (!imgdata.idata.dng_version && !strcmp(imgdata.idata.make, "Fujifilm") && (!strncmp(imgdata.idata.model, "S20Pro", 6) || !strncmp(imgdata.idata.model, "F700", 4))) { imgdata.sizes.raw_width /= 2; load_raw = &LibRaw::unpacked_load_raw_fuji_f700s20; } if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Nikon") && !libraw_internal_data.unpacker_data.load_flags && (!strncasecmp(imgdata.idata.model, "D810", 4) || !strcasecmp(imgdata.idata.model, "D4S")) && libraw_internal_data.unpacker_data.data_size * 2 == imgdata.sizes.raw_height * imgdata.sizes.raw_width * 3) { libraw_internal_data.unpacker_data.load_flags = 80; } // Adjust BL for Sony A900/A850 if (load_raw == &LibRaw::packed_load_raw && !strcasecmp(imgdata.idata.make, "Sony")) // 12 bit sony, but metadata may be for 14-bit range { if (C.maximum > 4095) C.maximum = 4095; if (C.black > 256 || C.cblack[0] > 256) { C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } } if (load_raw == &LibRaw::nikon_yuv_load_raw) // Is it Nikon sRAW? { load_raw = &LibRaw::nikon_load_sraw; C.black = 0; memset(C.cblack, 0, sizeof(C.cblack)); imgdata.idata.filters = 0; libraw_internal_data.unpacker_data.tiff_samples = 3; imgdata.idata.colors = 3; double beta_1 = -5.79342238397656E-02; double beta_2 = 3.28163551282665; double beta_3 = -8.43136004842678; double beta_4 = 1.03533181861023E+01; for (int i = 0; i <= 3072; i++) { double x = (double)i / 3072.; double y = (1. - exp(-beta_1 * x - beta_2 * x * x - beta_3 * x * x * x - beta_4 * x * x * x * x)); if (y < 0.) y = 0.; imgdata.color.curve[i] = (y * 16383.); } for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) imgdata.color.rgb_cam[i][j] = float(i == j); } // Adjust BL for Nikon 12bit if ((load_raw == &LibRaw::nikon_load_raw || load_raw == &LibRaw::packed_load_raw) && !strcasecmp(imgdata.idata.make, "Nikon") && strncmp(imgdata.idata.model, "COOLPIX", 7) // && strncmp(imgdata.idata.model,"1 ",2) && libraw_internal_data.unpacker_data.tiff_bps == 12) { C.maximum = 4095; C.black /= 4; for (int c = 0; c < 4; c++) C.cblack[c] /= 4; for (int c = 0; c < C.cblack[4] * C.cblack[5]; c++) C.cblack[6 + c] /= 4; } // Adjust Highlight Linearity limit if (C.linear_max[0] < 0) { if (imgdata.idata.dng_version) { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c + 6]; } else { for (int c = 0; c < 4; c++) C.linear_max[c] = -1 * C.linear_max[c] + imgdata.color.cblack[c]; } } if (!strcasecmp(imgdata.idata.make, "Nikon") && (!C.linear_max[0]) && (C.maximum > 1024) && (load_raw != &LibRaw::nikon_load_sraw)) { C.linear_max[0] = C.linear_max[1] = C.linear_max[2] = C.linear_max[3] = (long)((float)(C.maximum) / 1.07f); } // Correct WB for Samsung GX20 if (!strcasecmp(imgdata.idata.make, "Samsung") && !strcasecmp(imgdata.idata.model, "GX20")) { C.WB_Coeffs[LIBRAW_WBI_Daylight][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Daylight][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Shade][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Shade][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Cloudy][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Tungsten][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_D][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_D][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_N][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_N][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_FL_W][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_FL_W][2]) * 2.56f); C.WB_Coeffs[LIBRAW_WBI_Flash][2] = (int)((float)(C.WB_Coeffs[LIBRAW_WBI_Flash][2]) * 2.56f); for (int c = 0; c < 64; c++) { if (imgdata.color.WBCT_Coeffs[c][0] > 0.0f) { imgdata.color.WBCT_Coeffs[c][3] *= 2.56f; } } } // Adjust BL for Panasonic if (load_raw == &LibRaw::panasonic_load_raw && (!strcasecmp(imgdata.idata.make, "Panasonic") || !strcasecmp(imgdata.idata.make, "Leica") || !strcasecmp(imgdata.idata.make, "YUNEEC")) && ID.pana_black[0] && ID.pana_black[1] && ID.pana_black[2]) { if(libraw_internal_data.unpacker_data.pana_encoding == 5) P1.raw_count = 0; // Disable for new decoder C.black = 0; int add = libraw_internal_data.unpacker_data.pana_encoding == 4?15:0; C.cblack[0] = ID.pana_black[0]+add; C.cblack[1] = C.cblack[3] = ID.pana_black[1]+add; C.cblack[2] = ID.pana_black[2]+add; int i = C.cblack[3]; for (int c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (int c = 0; c < 4; c++) C.cblack[c] -= i; C.black = i; } // Adjust sizes for X3F processing if (load_raw == &LibRaw::x3f_load_raw) { for (int i = 0; i < foveon_count; i++) if (!strcasecmp(imgdata.idata.make, foveon_data[i].make) && !strcasecmp(imgdata.idata.model, foveon_data[i].model) && imgdata.sizes.raw_width == foveon_data[i].raw_width && imgdata.sizes.raw_height == foveon_data[i].raw_height) { imgdata.sizes.top_margin = foveon_data[i].top_margin; imgdata.sizes.left_margin = foveon_data[i].left_margin; imgdata.sizes.width = imgdata.sizes.iwidth = foveon_data[i].width; imgdata.sizes.height = imgdata.sizes.iheight = foveon_data[i].height; C.maximum = foveon_data[i].white; break; } } #if 0 size_t bytes = ID.input->size()-libraw_internal_data.unpacker_data.data_offset; float bpp = float(bytes)/float(S.raw_width)/float(S.raw_height); float bpp2 = float(bytes)/float(S.width)/float(S.height); printf("RawSize: %dx%d data offset: %d data size:%d bpp: %g bpp2: %g\n",S.raw_width,S.raw_height,libraw_internal_data.unpacker_data.data_offset,bytes,bpp,bpp2); if(!strcasecmp(imgdata.idata.make,"Hasselblad") && bpp == 6.0f) { load_raw = &LibRaw::hasselblad_full_load_raw; S.width = S.raw_width; S.height = S.raw_height; P1.filters = 0; P1.colors=3; P1.raw_count=1; C.maximum=0xffff; printf("3 channel hassy found\n"); } #endif if (C.profile_length) { if (C.profile) free(C.profile); C.profile = malloc(C.profile_length); merror(C.profile, "LibRaw::open_file()"); ID.input->seek(ID.profile_offset, SEEK_SET); ID.input->read(C.profile, C.profile_length, 1); } SET_PROC_FLAG(LIBRAW_PROGRESS_IDENTIFY); } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } final:; if (P1.raw_count < 1) return LIBRAW_FILE_UNSUPPORTED; write_fun = &LibRaw::write_ppm_tiff; if (load_raw == &LibRaw::kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); if (IO.shrink && P1.filters >= 1000) { S.width &= 65534; S.height &= 65534; } S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_SIZE_ADJUST); return LIBRAW_SUCCESS; } #ifdef USE_RAWSPEED void LibRaw::fix_after_rawspeed(int bl) { if (load_raw == &LibRaw::lossy_dng_load_raw) C.maximum = 0xffff; else if (load_raw == &LibRaw::sony_load_raw) C.maximum = 0x3ff0; } #else void LibRaw::fix_after_rawspeed(int) {} #endif void LibRaw::clearCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 0); #else __sync_fetch_and_and(&_exitflag, 0); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->resumeProcessing(); } #endif } void LibRaw::setCancelFlag() { #ifdef WIN32 InterlockedExchange(&_exitflag, 1); #else __sync_fetch_and_add(&_exitflag, 1); #endif #ifdef RAWSPEED_FASTEXIT if (_rawspeed_decoder) { RawDecoder *d = static_cast<RawDecoder *>(_rawspeed_decoder); d->cancelProcessing(); } #endif } void LibRaw::checkCancel() { #ifdef WIN32 if (InterlockedExchange(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #else if (__sync_fetch_and_and(&_exitflag, 0)) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } int LibRaw::try_rawspeed() { #ifdef USE_RAWSPEED int ret = LIBRAW_SUCCESS; int rawspeed_ignore_errors = 0; if (imgdata.idata.dng_version && imgdata.idata.colors == 3 && !strcasecmp(imgdata.idata.software, "Adobe Photoshop Lightroom 6.1.1 (Windows)")) rawspeed_ignore_errors = 1; // RawSpeed Supported, INT64 spos = ID.input->tell(); void *_rawspeed_buffer = 0; try { // printf("Using rawspeed\n"); ID.input->seek(0, SEEK_SET); INT64 _rawspeed_buffer_sz = ID.input->size() + 32; _rawspeed_buffer = malloc(_rawspeed_buffer_sz); if (!_rawspeed_buffer) throw LIBRAW_EXCEPTION_ALLOC; ID.input->read(_rawspeed_buffer, _rawspeed_buffer_sz, 1); FileMap map((uchar8 *)_rawspeed_buffer, _rawspeed_buffer_sz); RawParser t(&map); RawDecoder *d = 0; CameraMetaDataLR *meta = static_cast<CameraMetaDataLR *>(_rawspeed_camerameta); d = t.getDecoder(); if (!d) throw "Unable to find decoder"; try { d->checkSupport(meta); } catch (const RawDecoderException &e) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_UNSUPPORTED; throw e; } d->interpolateBadPixels = FALSE; d->applyStage1DngOpcodes = FALSE; _rawspeed_decoder = static_cast<void *>(d); d->decodeRaw(); d->decodeMetaData(meta); RawImage r = d->mRaw; if (r->errors.size() > 0 && !rawspeed_ignore_errors) { delete d; _rawspeed_decoder = 0; throw 1; } if (r->isCFA) { imgdata.rawdata.raw_image = (ushort *)r->getDataUncropped(0, 0); } else if (r->getCpp() == 4) { imgdata.rawdata.color4_image = (ushort(*)[4])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else if (r->getCpp() == 3) { imgdata.rawdata.color3_image = (ushort(*)[3])r->getDataUncropped(0, 0); if (r->whitePoint > 0 && r->whitePoint < 65536) C.maximum = r->whitePoint; } else { delete d; _rawspeed_decoder = 0; ret = LIBRAW_UNSPECIFIED_ERROR; } if (_rawspeed_decoder) { // set sizes iPoint2D rsdim = r->getUncroppedDim(); S.raw_pitch = r->pitch; S.raw_width = rsdim.x; S.raw_height = rsdim.y; // C.maximum = r->whitePoint; fix_after_rawspeed(r->blackLevel); } free(_rawspeed_buffer); _rawspeed_buffer = 0; imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROCESSED; } catch (const RawDecoderException &RDE) { imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } const char *p = RDE.what(); if (!strncmp(RDE.what(), "Decoder canceled", strlen("Decoder canceled"))) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; ret = LIBRAW_UNSPECIFIED_ERROR; } catch (...) { // We may get here due to cancellation flag imgdata.process_warnings |= LIBRAW_WARN_RAWSPEED_PROBLEM; if (_rawspeed_buffer) { free(_rawspeed_buffer); _rawspeed_buffer = 0; } ret = LIBRAW_UNSPECIFIED_ERROR; } ID.input->seek(spos, SEEK_SET); return ret; #else return LIBRAW_NOT_IMPLEMENTED; #endif } int LibRaw::valid_for_dngsdk() { #ifndef USE_DNGSDK return 0; #else if (!imgdata.idata.dng_version) return 0; if (!imgdata.params.use_dngsdk) return 0; if (load_raw == &LibRaw::lossy_dng_load_raw) return 0; if (is_floating_point() && (imgdata.params.use_dngsdk & LIBRAW_DNG_FLOAT)) return 1; if (!imgdata.idata.filters && (imgdata.params.use_dngsdk & LIBRAW_DNG_LINEAR)) return 1; if (libraw_internal_data.unpacker_data.tiff_bps == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_8BIT)) return 1; if (libraw_internal_data.unpacker_data.tiff_compress == 8 && (imgdata.params.use_dngsdk & LIBRAW_DNG_DEFLATE)) return 1; if (libraw_internal_data.unpacker_data.tiff_samples == 2) return 0; // Always deny 2-samples (old fuji superccd) if (imgdata.idata.filters == 9 && (imgdata.params.use_dngsdk & LIBRAW_DNG_XTRANS)) return 1; if (is_fuji_rotated()) return 0; // refuse if (imgdata.params.use_dngsdk & LIBRAW_DNG_OTHER) return 1; return 0; #endif } int LibRaw::is_curve_linear() { for (int i = 0; i < 0x10000; i++) if (imgdata.color.curve[i] != i) return 0; return 1; } int LibRaw::try_dngsdk() { #ifdef USE_DNGSDK if (!dnghost) return LIBRAW_UNSPECIFIED_ERROR; dng_host *host = static_cast<dng_host *>(dnghost); try { libraw_dng_stream stream(libraw_internal_data.internal_data.input); AutoPtr<dng_negative> negative; negative.Reset(host->Make_dng_negative()); dng_info info; info.Parse(*host, stream); info.PostParse(*host); if (!info.IsValidDNG()) { return LIBRAW_DATA_ERROR; } negative->Parse(*host, stream, info); negative->PostParse(*host, stream, info); negative->ReadStage1Image(*host, stream, info); dng_simple_image *stage2 = (dng_simple_image *)negative->Stage1Image(); if (stage2->Bounds().W() != S.raw_width || stage2->Bounds().H() != S.raw_height) { return LIBRAW_DATA_ERROR; } int pplanes = stage2->Planes(); int ptype = stage2->PixelType(); dng_pixel_buffer buffer; stage2->GetPixelBuffer(buffer); int pixels = stage2->Bounds().H() * stage2->Bounds().W() * pplanes; if (ptype == ttByte) imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ttShort)); else imgdata.rawdata.raw_alloc = malloc(pixels * TagTypeSize(ptype)); if (ptype == ttShort && !is_curve_linear()) { ushort *src = (ushort *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } else if (ptype == ttByte) { unsigned char *src = (unsigned char *)buffer.fData; ushort *dst = (ushort *)imgdata.rawdata.raw_alloc; if (is_curve_linear()) { for (int i = 0; i < pixels; i++) dst[i] = src[i]; } else { for (int i = 0; i < pixels; i++) dst[i] = imgdata.color.curve[src[i]]; } S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ttShort); } else { memmove(imgdata.rawdata.raw_alloc, buffer.fData, pixels * TagTypeSize(ptype)); S.raw_pitch = S.raw_width * pplanes * TagTypeSize(ptype); } switch (ptype) { case ttFloat: if (pplanes == 1) imgdata.rawdata.float_image = (float *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.float3_image = (float(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.float4_image = (float(*)[4])imgdata.rawdata.raw_alloc; break; case ttByte: case ttShort: if (pplanes == 1) imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; else if (pplanes == 3) imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; else if (pplanes == 4) imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; break; default: /* do nothing */ break; } } catch (...) { return LIBRAW_UNSPECIFIED_ERROR; } return imgdata.rawdata.raw_alloc ? LIBRAW_SUCCESS : LIBRAW_UNSPECIFIED_ERROR; #else return LIBRAW_UNSPECIFIED_ERROR; #endif } void LibRaw::set_dng_host(void *p) { #ifdef USE_DNGSDK dnghost = p; #endif } int LibRaw::unpack(void) { CHECK_ORDER_HIGH(LIBRAW_PROGRESS_LOAD_RAW); CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 0, 2); if (O.shot_select >= P1.raw_count) return LIBRAW_REQUEST_FOR_NONEXISTENT_IMAGE; if (!load_raw) return LIBRAW_UNSPECIFIED_ERROR; // already allocated ? if (imgdata.image) { free(imgdata.image); imgdata.image = 0; } if (imgdata.rawdata.raw_alloc) { free(imgdata.rawdata.raw_alloc); imgdata.rawdata.raw_alloc = 0; } if (libraw_internal_data.unpacker_data.meta_length) { libraw_internal_data.internal_data.meta_data = (char *)malloc(libraw_internal_data.unpacker_data.meta_length); merror(libraw_internal_data.internal_data.meta_data, "LibRaw::unpack()"); } libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); int save_iwidth = S.iwidth, save_iheight = S.iheight, save_shrink = IO.shrink; int rwidth = S.raw_width, rheight = S.raw_height; if (!IO.fuji_width) { // adjust non-Fuji allocation if (rwidth < S.width + S.left_margin) rwidth = S.width + S.left_margin; if (rheight < S.height + S.top_margin) rheight = S.height + S.top_margin; } if (rwidth > 65535 || rheight > 65535) // No way to make image larger than 64k pix throw LIBRAW_EXCEPTION_IO_CORRUPT; imgdata.rawdata.raw_image = 0; imgdata.rawdata.color4_image = 0; imgdata.rawdata.color3_image = 0; imgdata.rawdata.float_image = 0; imgdata.rawdata.float3_image = 0; #ifdef USE_DNGSDK if (imgdata.idata.dng_version && dnghost && imgdata.idata.raw_count == 1 && valid_for_dngsdk() && load_raw != &LibRaw::pentax_4shot_load_raw) { int rr = try_dngsdk(); } #endif #ifdef USE_RAWSPEED if (!raw_was_read()) { int rawspeed_enabled = 1; if (imgdata.idata.dng_version && libraw_internal_data.unpacker_data.tiff_samples == 2) rawspeed_enabled = 0; if (imgdata.idata.raw_count > 1) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.software, "Magic", 5)) rawspeed_enabled = 0; // Disable rawspeed for double-sized Oly files if (!strncasecmp(imgdata.idata.make, "Olympus", 7) && ((imgdata.sizes.raw_width > 6000) || !strncasecmp(imgdata.idata.model, "SH-2", 4) || !strncasecmp(imgdata.idata.model, "SH-3", 4) || !strncasecmp(imgdata.idata.model, "TG-4", 4) || !strncasecmp(imgdata.idata.model, "TG-5", 4))) rawspeed_enabled = 0; if (!strncasecmp(imgdata.idata.make, "Canon", 5) && !strcasecmp(imgdata.idata.model, "EOS 6D Mark II")) rawspeed_enabled = 0; if (imgdata.idata.dng_version && imgdata.idata.filters == 0 && libraw_internal_data.unpacker_data.tiff_bps == 8) // Disable for 8 bit rawspeed_enabled = 0; if (load_raw == &LibRaw::packed_load_raw && !strncasecmp(imgdata.idata.make, "Nikon", 5) && (!strncasecmp(imgdata.idata.model, "E", 1) || !strncasecmp(imgdata.idata.model, "COOLPIX B", 9))) rawspeed_enabled = 0; // RawSpeed Supported, if (O.use_rawspeed && rawspeed_enabled && !(is_sraw() && (O.raw_processing_options & (LIBRAW_PROCESSING_SRAW_NO_RGB | LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE))) && (decoder_info.decoder_flags & LIBRAW_DECODER_TRYRAWSPEED) && _rawspeed_camerameta) { int rr = try_rawspeed(); } } #endif if (!raw_was_read()) // RawSpeed failed or not run { // Not allocated on RawSpeed call, try call LibRaow int zero_rawimage = 0; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder and DNG float // Do nothing! Decoder will allocate data internally } if (decoder_info.decoder_flags & LIBRAW_DECODER_3CHANNEL) { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3 > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) * 3); imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 6; } else if (imgdata.idata.filters || P1.colors == 1) // Bayer image or single color -> decode to raw_image { if (INT64(rwidth) * INT64(rheight + 8) * sizeof(imgdata.rawdata.raw_image[0]) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = malloc(rwidth * (rheight + 8) * sizeof(imgdata.rawdata.raw_image[0])); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; if (!S.raw_pitch) S.raw_pitch = S.raw_width * 2; // Bayer case, not set before } else // NO LEGACY FLAG if (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) { S.raw_pitch = S.raw_width * 8; } else { S.iwidth = S.width; S.iheight = S.height; IO.shrink = 0; if (!S.raw_pitch) S.raw_pitch = (decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS) ? S.raw_width * 8 : S.width * 8; } // sRAW and old Foveon decoders only, so extra buffer size is just 1/4 // allocate image as temporary buffer, size if (INT64(MAX(S.width, S.raw_width)) * INT64(MAX(S.height, S.raw_height)) * sizeof(*imgdata.image) > LIBRAW_MAX_ALLOC_MB * INT64(1024 * 1024)) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.raw_alloc = 0; imgdata.image = (ushort(*)[4])calloc( unsigned(MAX(S.width, S.raw_width)) * unsigned(MAX(S.height, S.raw_height)), sizeof(*imgdata.image)); if (!(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL)) { imgdata.rawdata.raw_image = (ushort *)imgdata.image; zero_rawimage = 1; } } ID.input->seek(libraw_internal_data.unpacker_data.data_offset, SEEK_SET); unsigned m_save = C.maximum; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = 65535; (this->*load_raw)(); if (zero_rawimage) imgdata.rawdata.raw_image = 0; if (load_raw == &LibRaw::unpacked_load_raw && !strcasecmp(imgdata.idata.make, "Nikon")) C.maximum = m_save; if (decoder_info.decoder_flags & LIBRAW_DECODER_OWNALLOC) { // x3f foveon decoder only: do nothing } else if (!(imgdata.idata.filters || P1.colors == 1)) // legacy decoder, ownalloc handled above { // successfully decoded legacy image, attach image to raw_alloc imgdata.rawdata.raw_alloc = imgdata.image; imgdata.rawdata.color4_image = (ushort(*)[4])imgdata.rawdata.raw_alloc; imgdata.image = 0; // Restore saved values. Note: Foveon have masked frame // Other 4-color legacy data: no borders if (!(libraw_internal_data.unpacker_data.load_flags & 256) && !(decoder_info.decoder_flags & LIBRAW_DECODER_ADOBECOPYPIXEL) && !(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY_WITH_MARGINS)) { S.raw_width = S.width; S.left_margin = 0; S.raw_height = S.height; S.top_margin = 0; } } } if (imgdata.rawdata.raw_image) crop_masked_pixels(); // calculate black levels // recover image sizes S.iwidth = save_iwidth; S.iheight = save_iheight; IO.shrink = save_shrink; // adjust black to possible maximum unsigned int i = C.cblack[3]; unsigned int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; C.black += i; // Save color,sizes and internal data into raw_image fields memmove(&imgdata.rawdata.color, &imgdata.color, sizeof(imgdata.color)); memmove(&imgdata.rawdata.sizes, &imgdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.rawdata.iparams, &imgdata.idata, sizeof(imgdata.idata)); memmove(&imgdata.rawdata.ioparams, &libraw_internal_data.internal_output_params, sizeof(libraw_internal_data.internal_output_params)); SET_PROC_FLAG(LIBRAW_PROGRESS_LOAD_RAW); RUN_CALLBACK(LIBRAW_PROGRESS_LOAD_RAW, 1, 2); return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } catch (std::exception ee) { EXCEPTION_HANDLER(LIBRAW_EXCEPTION_IO_CORRUPT); } } void LibRaw::unpacked_load_raw_fuji_f700s20() { int base_offset = 0; int row_size = imgdata.sizes.raw_width * 2; // in bytes if (imgdata.idata.raw_count == 2 && imgdata.params.shot_select) { libraw_internal_data.internal_data.input->seek(-row_size, SEEK_CUR); base_offset = row_size; // in bytes } unsigned char *buffer = (unsigned char *)malloc(row_size * 2); for (int row = 0; row < imgdata.sizes.raw_height; row++) { read_shorts((ushort *)buffer, imgdata.sizes.raw_width * 2); memmove(&imgdata.rawdata.raw_image[row * imgdata.sizes.raw_pitch / 2], buffer + base_offset, row_size); } free(buffer); } void LibRaw::nikon_load_sraw() { // We're already seeked to data! unsigned char *rd = (unsigned char *)malloc(3 * (imgdata.sizes.raw_width + 2)); if (!rd) throw LIBRAW_EXCEPTION_ALLOC; try { int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); libraw_internal_data.internal_data.input->read(rd, 3, imgdata.sizes.raw_width); for (col = 0; col < imgdata.sizes.raw_width - 1; col += 2) { int bi = col * 3; ushort bits1 = (rd[bi + 1] & 0xf) << 8 | rd[bi]; // 3,0,1 ushort bits2 = rd[bi + 2] << 4 | ((rd[bi + 1] >> 4) & 0xf); // 452 ushort bits3 = ((rd[bi + 4] & 0xf) << 8) | rd[bi + 3]; // 967 ushort bits4 = rd[bi + 5] << 4 | ((rd[bi + 4] >> 4) & 0xf); // ab8 imgdata.image[row * imgdata.sizes.raw_width + col][0] = bits1; imgdata.image[row * imgdata.sizes.raw_width + col][1] = bits3; imgdata.image[row * imgdata.sizes.raw_width + col][2] = bits4; imgdata.image[row * imgdata.sizes.raw_width + col + 1][0] = bits2; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = 2048; imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = 2048; } } } catch (...) { free(rd); throw; } free(rd); C.maximum = 0xfff; // 12 bit? if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { return; // no CbCr interpolation } // Interpolate CC channels int row, col; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col += 2) { int col2 = col < imgdata.sizes.raw_width - 2 ? col + 2 : col; imgdata.image[row * imgdata.sizes.raw_width + col + 1][1] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][1] + imgdata.image[row * imgdata.sizes.raw_width + col2][1]) / 2); imgdata.image[row * imgdata.sizes.raw_width + col + 1][2] = (unsigned short)(int(imgdata.image[row * imgdata.sizes.raw_width + col][2] + imgdata.image[row * imgdata.sizes.raw_width + col2][2]) / 2); } } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) return; for (row = 0; row < imgdata.sizes.raw_height; row++) { checkCancel(); // will throw out for (col = 0; col < imgdata.sizes.raw_width; col++) { float Y = float(imgdata.image[row * imgdata.sizes.raw_width + col][0]) / 2549.f; float Ch2 = float(imgdata.image[row * imgdata.sizes.raw_width + col][1] - 1280) / 1536.f; float Ch3 = float(imgdata.image[row * imgdata.sizes.raw_width + col][2] - 1280) / 1536.f; if (Y > 1.f) Y = 1.f; if (Y > 0.803f) Ch2 = Ch3 = 0.5f; float r = Y + 1.40200f * (Ch3 - 0.5f); if (r < 0.f) r = 0.f; if (r > 1.f) r = 1.f; float g = Y - 0.34414f * (Ch2 - 0.5f) - 0.71414 * (Ch3 - 0.5f); if (g > 1.f) g = 1.f; if (g < 0.f) g = 0.f; float b = Y + 1.77200 * (Ch2 - 0.5f); if (b > 1.f) b = 1.f; if (b < 0.f) b = 0.f; imgdata.image[row * imgdata.sizes.raw_width + col][0] = imgdata.color.curve[int(r * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][1] = imgdata.color.curve[int(g * 3072.f)]; imgdata.image[row * imgdata.sizes.raw_width + col][2] = imgdata.color.curve[int(b * 3072.f)]; } } C.maximum = 16383; } void LibRaw::free_image(void) { if (imgdata.image) { free(imgdata.image); imgdata.image = 0; imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; } } void LibRaw::raw2image_start() { // restore color,sizes and internal data into raw_image fields memmove(&imgdata.color, &imgdata.rawdata.color, sizeof(imgdata.color)); memmove(&imgdata.sizes, &imgdata.rawdata.sizes, sizeof(imgdata.sizes)); memmove(&imgdata.idata, &imgdata.rawdata.iparams, sizeof(imgdata.idata)); memmove(&libraw_internal_data.internal_output_params, &imgdata.rawdata.ioparams, sizeof(libraw_internal_data.internal_output_params)); if (O.user_flip >= 0) S.flip = O.user_flip; switch ((S.flip + 3600) % 360) { case 270: S.flip = 5; break; case 180: S.flip = 3; break; case 90: S.flip = 6; break; } // adjust for half mode! IO.shrink = P1.filters && (O.half_size || ((O.threshold || O.aber[0] != 1 || O.aber[2] != 1))); S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; } int LibRaw::is_phaseone_compressed() { return (load_raw == &LibRaw::phase_one_load_raw_c || load_raw == &LibRaw::phase_one_load_raw); } int LibRaw::is_canon_600() { return load_raw == &LibRaw::canon_600_load_raw; } int LibRaw::raw2image(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // free and re-allocate image bitmap if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, S.iheight * S.iwidth * sizeof(*imgdata.image)); memset(imgdata.image, 0, S.iheight * S.iwidth * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { unsigned r, c; int row, col; for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][FC(r, c)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } } else { int row, col; for (row = 0; row < S.height; row++) for (col = 0; col < S.width; col++) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][fcol(row, col)] = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.width * 8 == S.raw_pitch) memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); else { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } // hack - clear later flags! if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } void LibRaw::phase_one_allocate_tempbuffer() { // Allocate temp raw_image buffer imgdata.rawdata.raw_image = (ushort *)malloc(S.raw_pitch * S.raw_height); merror(imgdata.rawdata.raw_image, "phase_one_prepare_to_correct()"); } void LibRaw::phase_one_free_tempbuffer() { free(imgdata.rawdata.raw_image); imgdata.rawdata.raw_image = (ushort *)imgdata.rawdata.raw_alloc; } int LibRaw::phase_one_subtract_black(ushort *src, ushort *dest) { try { if (O.user_black < 0 && O.user_cblack[0] <= -1000000 && O.user_cblack[1] <= -1000000 && O.user_cblack[2] <= -1000000 && O.user_cblack[3] <= -1000000) { if (!imgdata.rawdata.ph1_cblack || !imgdata.rawdata.ph1_rblack) { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl; dest[idx] = val > 0 ? val : 0; } } } else { register int bl = imgdata.color.phase_one_data.t_black; for (int row = 0; row < S.raw_height; row++) { checkCancel(); for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; int val = int(src[idx]) - bl + imgdata.rawdata.ph1_cblack[row][col >= imgdata.rawdata.color.phase_one_data.split_col] + imgdata.rawdata.ph1_rblack[col][row >= imgdata.rawdata.color.phase_one_data.split_row]; dest[idx] = val > 0 ? val : 0; } } } } else // black set by user interaction { // Black level in cblack! for (int row = 0; row < S.raw_height; row++) { checkCancel(); unsigned short cblk[16]; for (int cc = 0; cc < 16; cc++) cblk[cc] = C.cblack[fcol(row, cc)]; for (int col = 0; col < S.raw_width; col++) { int idx = row * S.raw_width + col; ushort val = src[idx]; ushort bl = cblk[col & 0xf]; dest[idx] = val > bl ? val - bl : 0; } } } return 0; } catch (LibRaw_exceptions err) { return LIBRAW_CANCELLED_BY_CALLBACK; } } void LibRaw::copy_fuji_uncropped(unsigned short cblack[4], unsigned short *dmaxp) { int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.raw_height - S.top_margin * 2; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < IO.fuji_width << !libraw_internal_data.unpacker_data.fuji_layout; col++) { unsigned r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < S.height && c < S.width) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FC(r, c); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * S.iwidth + ((c) >> IO.shrink)][cc] = val; } } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } void LibRaw::copy_bayer(unsigned short cblack[4], unsigned short *dmaxp) { // Both cropped and uncropped int row; #if defined(LIBRAW_USE_OPENMP) #pragma omp parallel for default(shared) #endif for (row = 0; row < S.height; row++) { int col; unsigned short ldmax = 0; for (col = 0; col < S.width; col++) { unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = fcol(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (val > ldmax) ldmax = val; } else val = 0; imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][cc] = val; } #if defined(LIBRAW_USE_OPENMP) #pragma omp critical(dataupdate) #endif { if (*dmaxp < ldmax) *dmaxp = ldmax; } } } int LibRaw::raw2image_ex(int do_subtract_black) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); try { raw2image_start(); // Compressed P1 files with bl data! if (is_phaseone_compressed()) { phase_one_allocate_tempbuffer(); int rc = phase_one_subtract_black((ushort *)imgdata.rawdata.raw_alloc, imgdata.rawdata.raw_image); if (rc == 0) rc = phase_one_correct(); if (rc != 0) { phase_one_free_tempbuffer(); return rc; } } // process cropping int do_crop = 0; unsigned save_width = S.width; if (~O.cropbox[2] && ~O.cropbox[3]) { int crop[4], c, filt; for (int c = 0; c < 4; c++) { crop[c] = O.cropbox[c]; if (crop[c] < 0) crop[c] = 0; } if (IO.fuji_width && imgdata.idata.filters >= 1000) { crop[0] = (crop[0] / 4) * 4; crop[1] = (crop[1] / 4) * 4; if (!libraw_internal_data.unpacker_data.fuji_layout) { crop[2] *= sqrt(2.0); crop[3] /= sqrt(2.0); } crop[2] = (crop[2] / 4 + 1) * 4; crop[3] = (crop[3] / 4 + 1) * 4; } else if (imgdata.idata.filters == 1) { crop[0] = (crop[0] / 16) * 16; crop[1] = (crop[1] / 16) * 16; } else if (imgdata.idata.filters == LIBRAW_XTRANS) { crop[0] = (crop[0] / 6) * 6; crop[1] = (crop[1] / 6) * 6; } do_crop = 1; crop[2] = MIN(crop[2], (signed)S.width - crop[0]); crop[3] = MIN(crop[3], (signed)S.height - crop[1]); if (crop[2] <= 0 || crop[3] <= 0) throw LIBRAW_EXCEPTION_BAD_CROP; // adjust sizes! S.left_margin += crop[0]; S.top_margin += crop[1]; S.width = crop[2]; S.height = crop[3]; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; if (!IO.fuji_width && imgdata.idata.filters && imgdata.idata.filters >= 1000) { for (filt = c = 0; c < 16; c++) filt |= FC((c >> 1) + (crop[1]), (c & 1) + (crop[0])) << c * 2; imgdata.idata.filters = filt; } } int alloc_width = S.iwidth; int alloc_height = S.iheight; if (IO.fuji_width && do_crop) { int IO_fw = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int t_alloc_width = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO_fw; int t_alloc_height = t_alloc_width - 1; alloc_height = (t_alloc_height + IO.shrink) >> IO.shrink; alloc_width = (t_alloc_width + IO.shrink) >> IO.shrink; } int alloc_sz = alloc_width * alloc_height; if (imgdata.image) { imgdata.image = (ushort(*)[4])realloc(imgdata.image, alloc_sz * sizeof(*imgdata.image)); memset(imgdata.image, 0, alloc_sz * sizeof(*imgdata.image)); } else imgdata.image = (ushort(*)[4])calloc(alloc_sz, sizeof(*imgdata.image)); merror(imgdata.image, "raw2image_ex()"); libraw_decoder_info_t decoder_info; get_decoder_info(&decoder_info); // Adjust black levels unsigned short cblack[4] = {0, 0, 0, 0}; unsigned short dmax = 0; if (do_subtract_black) { adjust_bl(); for (int i = 0; i < 4; i++) cblack[i] = (unsigned short)C.cblack[i]; } // Move saved bitmap to imgdata.image if (imgdata.idata.filters || P1.colors == 1) { if (IO.fuji_width) { if (do_crop) { IO.fuji_width = S.width >> !libraw_internal_data.unpacker_data.fuji_layout; int IO_fwidth = (S.height >> libraw_internal_data.unpacker_data.fuji_layout) + IO.fuji_width; int IO_fheight = IO_fwidth - 1; int row, col; for (row = 0; row < S.height; row++) { for (col = 0; col < S.width; col++) { int r, c; if (libraw_internal_data.unpacker_data.fuji_layout) { r = IO.fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = IO.fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } unsigned short val = imgdata.rawdata.raw_image[(row + S.top_margin) * S.raw_pitch / 2 + (col + S.left_margin)]; int cc = FCF(row, col); if (val > cblack[cc]) { val -= cblack[cc]; if (dmax < val) dmax = val; } else val = 0; imgdata.image[((r) >> IO.shrink) * alloc_width + ((c) >> IO.shrink)][cc] = val; } } S.height = IO_fheight; S.width = IO_fwidth; S.iheight = (S.height + IO.shrink) >> IO.shrink; S.iwidth = (S.width + IO.shrink) >> IO.shrink; S.raw_height -= 2 * S.top_margin; } else { copy_fuji_uncropped(cblack, &dmax); } } // end Fuji else { copy_bayer(cblack, &dmax); } } else // if(decoder_info.decoder_flags & LIBRAW_DECODER_LEGACY) { if (imgdata.rawdata.color4_image) { if (S.raw_pitch != S.width * 8) { for (int row = 0; row < S.height; row++) memmove(&imgdata.image[row * S.width], &imgdata.rawdata.color4_image[(row + S.top_margin) * S.raw_pitch / 8 + S.left_margin], S.width * sizeof(*imgdata.image)); } else { // legacy is always 4channel and not shrinked! memmove(imgdata.image, imgdata.rawdata.color4_image, S.width * S.height * sizeof(*imgdata.image)); } } else if (imgdata.rawdata.color3_image) { unsigned char *c3image = (unsigned char *)imgdata.rawdata.color3_image; for (int row = 0; row < S.height; row++) { ushort(*srcrow)[3] = (ushort(*)[3]) & c3image[(row + S.top_margin) * S.raw_pitch]; ushort(*dstrow)[4] = (ushort(*)[4]) & imgdata.image[row * S.width]; for (int col = 0; col < S.width; col++) { for (int c = 0; c < 3; c++) dstrow[col][c] = srcrow[S.left_margin + col][c]; dstrow[col][3] = 0; } } } else { // legacy decoder, but no data? throw LIBRAW_EXCEPTION_DECODE_RAW; } } // Free PhaseOne separate copy allocated at function start if (is_phaseone_compressed()) { phase_one_free_tempbuffer(); } if (load_raw == &CLASS canon_600_load_raw && S.width < S.raw_width) { canon_600_correct(); } if (do_subtract_black) { C.data_maximum = (int)dmax; C.maximum -= C.black; // ZERO(C.cblack); C.cblack[0] = C.cblack[1] = C.cblack[2] = C.cblack[3] = 0; C.black = 0; } // hack - clear later flags! imgdata.progress_flags = LIBRAW_PROGRESS_START | LIBRAW_PROGRESS_OPEN | LIBRAW_PROGRESS_RAW2_IMAGE | LIBRAW_PROGRESS_IDENTIFY | LIBRAW_PROGRESS_SIZE_ADJUST | LIBRAW_PROGRESS_LOAD_RAW; return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #if 1 libraw_processed_image_t *LibRaw::dcraw_make_mem_thumb(int *errcode) { if (!T.thumb) { if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { if (errcode) *errcode = LIBRAW_NO_THUMBNAIL; } else { if (errcode) *errcode = LIBRAW_OUT_OF_ORDER_CALL; } return NULL; } if (T.tformat == LIBRAW_THUMBNAIL_BITMAP) { libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + T.tlength); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_BITMAP; ret->height = T.theight; ret->width = T.twidth; ret->colors = 3; ret->bits = 8; ret->data_size = T.tlength; memmove(ret->data, T.thumb, T.tlength); if (errcode) *errcode = 0; return ret; } else if (T.tformat == LIBRAW_THUMBNAIL_JPEG) { ushort exif[5]; int mk_exif = 0; if (strcmp(T.thumb + 6, "Exif")) mk_exif = 1; int dsize = T.tlength + mk_exif * (sizeof(exif) + sizeof(tiff_hdr)); libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + dsize); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); ret->type = LIBRAW_IMAGE_JPEG; ret->data_size = dsize; ret->data[0] = 0xff; ret->data[1] = 0xd8; if (mk_exif) { struct tiff_hdr th; memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); memmove(ret->data + 2, exif, sizeof(exif)); tiff_head(&th, 0); memmove(ret->data + (2 + sizeof(exif)), &th, sizeof(th)); memmove(ret->data + (2 + sizeof(exif) + sizeof(th)), T.thumb + 2, T.tlength - 2); } else { memmove(ret->data + 2, T.thumb + 2, T.tlength - 2); } if (errcode) *errcode = 0; return ret; } else { if (errcode) *errcode = LIBRAW_UNSUPPORTED_THUMBNAIL; return NULL; } } // jlb // macros for copying pixels to either BGR or RGB formats #define FORBGR for (c = P1.colors - 1; c >= 0; c--) #define FORRGB for (c = 0; c < P1.colors; c++) void LibRaw::get_mem_image_format(int *width, int *height, int *colors, int *bps) const { if (S.flip & 4) { *width = S.height; *height = S.width; } else { *width = S.width; *height = S.height; } *colors = P1.colors; *bps = O.output_bps; } int LibRaw::copy_mem_image(void *scan0, int stride, int bgr) { // the image memory pointed to by scan0 is assumed to be in the format returned by get_mem_image_format if ((imgdata.progress_flags & LIBRAW_PROGRESS_THUMB_MASK) < LIBRAW_PROGRESS_PRE_INTERPOLATE) return LIBRAW_OUT_OF_ORDER_CALL; if (libraw_internal_data.output_data.histogram) { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * O.auto_bright_thr; if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } int s_iheight = S.iheight; int s_iwidth = S.iwidth; int s_width = S.width; int s_hwight = S.height; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, S.width); for (row = 0; row < S.height; row++, soff += rstep) { uchar *bufp = ((uchar *)scan0) + row * stride; ppm2 = (ushort *)(ppm = bufp); // keep trivial decisions in the outer loop for speed if (bgr) { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORBGR *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } else { if (O.output_bps == 8) { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm++ = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } else { for (col = 0; col < S.width; col++, soff += cstep) FORRGB *ppm2++ = imgdata.color.curve[imgdata.image[soff][c]]; } } // bufp += stride; // go to the next line } S.iheight = s_iheight; S.iwidth = s_iwidth; S.width = s_width; S.height = s_hwight; return 0; } #undef FORBGR #undef FORRGB libraw_processed_image_t *LibRaw::dcraw_make_mem_image(int *errcode) { int width, height, colors, bps; get_mem_image_format(&width, &height, &colors, &bps); int stride = width * (bps / 8) * colors; unsigned ds = height * stride; libraw_processed_image_t *ret = (libraw_processed_image_t *)::malloc(sizeof(libraw_processed_image_t) + ds); if (!ret) { if (errcode) *errcode = ENOMEM; return NULL; } memset(ret, 0, sizeof(libraw_processed_image_t)); // metadata init ret->type = LIBRAW_IMAGE_BITMAP; ret->height = height; ret->width = width; ret->colors = colors; ret->bits = bps; ret->data_size = ds; copy_mem_image(ret->data, stride, 0); return ret; } #undef FORC #undef FORCC #undef SWAP #endif int LibRaw::dcraw_ppm_tiff_writer(const char *filename) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); if (!imgdata.image) return LIBRAW_OUT_OF_ORDER_CALL; if (!filename) return ENOENT; FILE *f = fopen(filename, "wb"); if (!f) return errno; try { if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_ppm_tiff_writer()"); } libraw_internal_data.internal_data.output = f; write_ppm_tiff(); SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); libraw_internal_data.internal_data.output = NULL; fclose(f); return 0; } catch (LibRaw_exceptions err) { fclose(f); EXCEPTION_HANDLER(err); } } #define THUMB_READ_BEYOND 16384 void LibRaw::kodak_thumb_loader() { INT64 est_datasize = T.theight * T.twidth / 3; // is 0.3 bytes per pixel good estimate? if (ID.toffset < 0) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (ID.toffset + est_datasize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; // some kodak cameras ushort s_height = S.height, s_width = S.width, s_iwidth = S.iwidth, s_iheight = S.iheight; ushort s_flags = libraw_internal_data.unpacker_data.load_flags; libraw_internal_data.unpacker_data.load_flags = 12; int s_colors = P1.colors; unsigned s_filters = P1.filters; ushort(*s_image)[4] = imgdata.image; S.height = T.theight; S.width = T.twidth; P1.filters = 0; if (thumb_load_raw == &CLASS kodak_ycbcr_load_raw) { S.height += S.height & 1; S.width += S.width & 1; } imgdata.image = (ushort(*)[4])calloc(S.iheight * S.iwidth, sizeof(*imgdata.image)); merror(imgdata.image, "LibRaw::kodak_thumb_loader()"); ID.input->seek(ID.toffset, SEEK_SET); // read kodak thumbnail into T.image[] try { (this->*thumb_load_raw)(); } catch (...) { free(imgdata.image); imgdata.image = s_image; T.twidth = 0; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = 0; S.height = s_height; T.tcolors = 0; P1.colors = s_colors; P1.filters = s_filters; T.tlength = 0; libraw_internal_data.unpacker_data.load_flags = s_flags; return; } // copy-n-paste from image pipe #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #ifndef CLIP #define CLIP(x) LIM(x, 0, 65535) #endif #define SWAP(a, b) \ { \ a ^= b; \ a ^= (b ^= a); \ } // from scale_colors { double dmax; float scale_mul[4]; int c, val; for (dmax = DBL_MAX, c = 0; c < 3; c++) if (dmax > C.pre_mul[c]) dmax = C.pre_mul[c]; for (c = 0; c < 3; c++) scale_mul[c] = (C.pre_mul[c] / dmax) * 65535.0 / C.maximum; scale_mul[3] = scale_mul[1]; size_t size = S.height * S.width; for (unsigned i = 0; i < size * 4; i++) { val = imgdata.image[0][i]; if (!val) continue; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } // from convert_to_rgb ushort *img; int row, col; int(*t_hist)[LIBRAW_HISTOGRAM_SIZE] = (int(*)[LIBRAW_HISTOGRAM_SIZE])calloc(sizeof(*t_hist), 4); merror(t_hist, "LibRaw::kodak_thumb_loader()"); float out[3], out_cam[3][4] = {{2.81761312, -1.98369181, 0.166078627, 0}, {-0.111855984, 1.73688626, -0.625030339, 0}, {-0.0379119813, -0.891268849, 1.92918086, 0}}; for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { out[0] = out[1] = out[2] = 0; int c; for (c = 0; c < 3; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); for (c = 0; c < P1.colors; c++) t_hist[c][img[c] >> 3]++; } // from gamma_lut int(*save_hist)[LIBRAW_HISTOGRAM_SIZE] = libraw_internal_data.output_data.histogram; libraw_internal_data.output_data.histogram = t_hist; // make curve output curve! ushort(*t_curve) = (ushort *)calloc(sizeof(C.curve), 1); merror(t_curve, "LibRaw::kodak_thumb_loader()"); memmove(t_curve, C.curve, sizeof(C.curve)); memset(C.curve, 0, sizeof(C.curve)); { int perc, val, total, t_white = 0x2000, c; perc = S.width * S.height * 0.01; /* 99th percentile white level */ if (IO.fuji_width) perc /= 2; if (!((O.highlight & ~2) || O.no_auto_bright)) for (t_white = c = 0; c < P1.colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += libraw_internal_data.output_data.histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(O.gamm[0], O.gamm[1], 2, (t_white << 3) / O.bright); } libraw_internal_data.output_data.histogram = save_hist; free(t_hist); // from write_ppm_tiff - copy pixels into bitmap int s_flip = imgdata.sizes.flip; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = 0; S.iheight = S.height; S.iwidth = S.width; if (S.flip & 4) SWAP(S.height, S.width); if (T.thumb) free(T.thumb); T.thumb = (char *)calloc(S.width * S.height, P1.colors); merror(T.thumb, "LibRaw::kodak_thumb_loader()"); T.tlength = S.width * S.height * P1.colors; // from write_tiff_ppm { int soff = flip_index(0, 0); int cstep = flip_index(0, 1) - soff; int rstep = flip_index(1, 0) - flip_index(0, S.width); for (int row = 0; row < S.height; row++, soff += rstep) { char *ppm = T.thumb + row * S.width * P1.colors; for (int col = 0; col < S.width; col++, soff += cstep) for (int c = 0; c < P1.colors; c++) ppm[col * P1.colors + c] = imgdata.color.curve[imgdata.image[soff][c]] >> 8; } } memmove(C.curve, t_curve, sizeof(C.curve)); free(t_curve); // restore variables free(imgdata.image); imgdata.image = s_image; if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_NO_ROTATE_FOR_KODAK_THUMBNAILS) imgdata.sizes.flip = s_flip; T.twidth = S.width; S.width = s_width; S.iwidth = s_iwidth; S.iheight = s_iheight; T.theight = S.height; S.height = s_height; T.tcolors = P1.colors; P1.colors = s_colors; P1.filters = s_filters; libraw_internal_data.unpacker_data.load_flags = s_flags; } #undef MIN #undef MAX #undef LIM #undef CLIP #undef SWAP // ������� thumbnail �� �����, ������ thumb_format � ������������ � �������� int LibRaw::thumbOK(INT64 maxsz) { if (!ID.input) return 0; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) return 0; INT64 fsize = ID.input->size(); if (fsize > 0x7fffffffU) return 0; // No thumb for raw > 2Gb int tsize = 0; int tcol = (T.tcolors > 0 && T.tcolors < 4) ? T.tcolors : 3; if (write_thumb == &LibRaw::jpeg_thumb) tsize = T.tlength; else if (write_thumb == &LibRaw::ppm_thumb) tsize = tcol * T.twidth * T.theight; else if (write_thumb == &LibRaw::ppm16_thumb) tsize = tcol * T.twidth * T.theight * ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1); else if (write_thumb == &LibRaw::x3f_thumb_loader) { tsize = x3f_thumb_size(); } else // Kodak => no check tsize = 1; if (tsize < 0) return 0; if (maxsz > 0 && tsize > maxsz) return 0; return (tsize + ID.toffset <= fsize) ? 1 : 0; } #ifndef NO_JPEG struct jpegErrorManager { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; longjmp(myerr->setjmp_buffer, 1); } #endif int LibRaw::unpack_thumb(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); CHECK_ORDER_BIT(LIBRAW_PROGRESS_THUMB_LOAD); try { if (!libraw_internal_data.internal_data.input) return LIBRAW_INPUT_CLOSED; int t_colors = libraw_internal_data.unpacker_data.thumb_misc >> 5 & 7; int t_bytesps = (libraw_internal_data.unpacker_data.thumb_misc & 31) / 8; if (!ID.toffset && !(imgdata.thumbnail.tlength > 0 && load_raw == &LibRaw::broadcom_load_raw) // RPi ) { return LIBRAW_NO_THUMBNAIL; } else if (thumb_load_raw) { kodak_thumb_loader(); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { if (write_thumb == &LibRaw::x3f_thumb_loader) { INT64 tsize = x3f_thumb_size(); if (tsize < 2048 || INT64(ID.toffset) + tsize < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + tsize > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } else { if (INT64(ID.toffset) + INT64(T.tlength) < 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; if (INT64(ID.toffset) + INT64(T.tlength) > ID.input->size() + THUMB_READ_BEYOND) throw LIBRAW_EXCEPTION_IO_EOF; } ID.input->seek(ID.toffset, SEEK_SET); if (write_thumb == &LibRaw::jpeg_thumb) { if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "jpeg_thumb()"); ID.input->read(T.thumb, 1, T.tlength); unsigned char *tthumb = (unsigned char *)T.thumb; tthumb[0] = 0xff; tthumb[1] = 0xd8; #ifdef NO_JPEG T.tcolors = 3; #else { jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; if (setjmp(jerr.setjmp_buffer)) { err2: jpeg_destroy_decompress(&cinfo); T.tcolors = 3; } jpeg_create_decompress(&cinfo); jpeg_mem_src(&cinfo, (unsigned char *)T.thumb, T.tlength); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) goto err2; T.tcolors = (cinfo.num_components > 0 && cinfo.num_components <= 3) ? cinfo.num_components : 3; jpeg_destroy_decompress(&cinfo); } #endif T.tformat = LIBRAW_THUMBNAIL_JPEG; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm_thumb) { if (t_bytesps > 1) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 8-bit thumb, but parsed for more bits int t_length = T.twidth * T.theight * t_colors; if (T.tlength && T.tlength < t_length) // try to find tiff ifd with needed offset { int pifd = -1; for (int ii = 0; ii < libraw_internal_data.identify_data.tiff_nifds && ii < LIBRAW_IFD_MAXCOUNT; ii++) if (tiff_ifd[ii].offset == libraw_internal_data.internal_data.toffset) // found { pifd = ii; break; } if (pifd >= 0 && tiff_ifd[pifd].strip_offsets_count && tiff_ifd[pifd].strip_byte_counts_count) { // We found it, calculate final size unsigned total_size = 0; for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count; i++) total_size += tiff_ifd[pifd].strip_byte_counts[i]; if (total_size != t_length) // recalculate colors { if (total_size == T.twidth * T.tlength * 3) T.tcolors = 3; else if (total_size == T.twidth * T.tlength) T.tcolors = 1; } T.tlength = total_size; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); merror(T.thumb, "ppm_thumb()"); char *dest = T.thumb; INT64 pos = ID.input->tell(); for (int i = 0; i < tiff_ifd[pifd].strip_byte_counts_count && i < tiff_ifd[pifd].strip_offsets_count; i++) { int remain = T.tlength; int sz = tiff_ifd[pifd].strip_byte_counts[i]; int off = tiff_ifd[pifd].strip_offsets[i]; if (off >= 0 && off + sz <= ID.input->size() && sz <= remain) { ID.input->seek(off, SEEK_SET); ID.input->read(dest, sz, 1); remain -= sz; dest += sz; } } ID.input->seek(pos, SEEK_SET); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } } if (!T.tlength) T.tlength = t_length; if (T.thumb) free(T.thumb); T.thumb = (char *)malloc(T.tlength); if (!T.tcolors) T.tcolors = t_colors; merror(T.thumb, "ppm_thumb()"); ID.input->read(T.thumb, 1, T.tlength); T.tformat = LIBRAW_THUMBNAIL_BITMAP; SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::ppm16_thumb) { if (t_bytesps > 2) throw LIBRAW_EXCEPTION_IO_CORRUPT; // 16-bit thumb, but parsed for more bits int o_bps = (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS) ? 2 : 1; int o_length = T.twidth * T.theight * t_colors * o_bps; int i_length = T.twidth * T.theight * t_colors * 2; if (!T.tlength) T.tlength = o_length; ushort *t_thumb = (ushort *)calloc(i_length, 1); ID.input->read(t_thumb, 1, i_length); if ((libraw_internal_data.unpacker_data.order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)t_thumb, (char *)t_thumb, i_length); if (T.thumb) free(T.thumb); if ((imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_PPM16_THUMBS)) { T.thumb = (char *)t_thumb; T.tformat = LIBRAW_THUMBNAIL_BITMAP16; } else { T.thumb = (char *)malloc(o_length); merror(T.thumb, "ppm_thumb()"); for (int i = 0; i < o_length; i++) T.thumb[i] = t_thumb[i] >> 8; free(t_thumb); T.tformat = LIBRAW_THUMBNAIL_BITMAP; } SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else if (write_thumb == &LibRaw::x3f_thumb_loader) { x3f_thumb_loader(); SET_PROC_FLAG(LIBRAW_PROGRESS_THUMB_LOAD); return 0; } else { return LIBRAW_UNSUPPORTED_THUMBNAIL; } } // last resort return LIBRAW_UNSUPPORTED_THUMBNAIL; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } int LibRaw::dcraw_thumb_writer(const char *fname) { // CHECK_ORDER_LOW(LIBRAW_PROGRESS_THUMB_LOAD); if (!fname) return ENOENT; FILE *tfp = fopen(fname, "wb"); if (!tfp) return errno; if (!T.thumb) { fclose(tfp); return LIBRAW_OUT_OF_ORDER_CALL; } try { switch (T.tformat) { case LIBRAW_THUMBNAIL_JPEG: jpeg_thumb_writer(tfp, T.thumb, T.tlength); break; case LIBRAW_THUMBNAIL_BITMAP: fprintf(tfp, "P6\n%d %d\n255\n", T.twidth, T.theight); fwrite(T.thumb, 1, T.tlength, tfp); break; default: fclose(tfp); return LIBRAW_UNSUPPORTED_THUMBNAIL; } fclose(tfp); return 0; } catch (LibRaw_exceptions err) { fclose(tfp); EXCEPTION_HANDLER(err); } } int LibRaw::adjust_sizes_info_only(void) { CHECK_ORDER_LOW(LIBRAW_PROGRESS_IDENTIFY); raw2image_start(); if (O.use_fuji_rotate) { if (IO.fuji_width) { IO.fuji_width = (IO.fuji_width - 1 + IO.shrink) >> IO.shrink; S.iwidth = (ushort)(IO.fuji_width / sqrt(0.5)); S.iheight = (ushort)((S.iheight - IO.fuji_width) / sqrt(0.5)); } else { if (S.pixel_aspect < 0.995) S.iheight = (ushort)(S.iheight / S.pixel_aspect + 0.5); if (S.pixel_aspect > 1.005) S.iwidth = (ushort)(S.iwidth * S.pixel_aspect + 0.5); } } SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); if (S.flip & 4) { unsigned short t = S.iheight; S.iheight = S.iwidth; S.iwidth = t; SET_PROC_FLAG(LIBRAW_PROGRESS_FLIP); } return 0; } int LibRaw::subtract_black() { adjust_bl(); return subtract_black_internal(); } int LibRaw::subtract_black_internal() { CHECK_ORDER_LOW(LIBRAW_PROGRESS_RAW2_IMAGE); try { if (!is_phaseone_compressed() && (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3] || (C.cblack[4] && C.cblack[5]))) { #define BAYERC(row, col, c) imgdata.image[((row) >> IO.shrink) * S.iwidth + ((col) >> IO.shrink)][c] int cblk[4], i; for (i = 0; i < 4; i++) cblk[i] = C.cblack[i]; int size = S.iheight * S.iwidth; #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define CLIP(x) LIM(x, 0, 65535) int dmax = 0; if (C.cblack[4] && C.cblack[5]) { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } else { for (i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val -= cblk[i & 3]; imgdata.image[0][i] = CLIP(val); if (dmax < val) dmax = val; } } C.data_maximum = dmax & 0xffff; #undef MIN #undef MAX #undef LIM #undef CLIP C.maximum -= C.black; ZERO(C.cblack); // Yeah, we used cblack[6+] values too! C.black = 0; #undef BAYERC } else { // Nothing to Do, maximum is already calculated, black level is 0, so no change // only calculate channel maximum; int idx; ushort *p = (ushort *)imgdata.image; int dmax = 0; for (idx = 0; idx < S.iheight * S.iwidth * 4; idx++) if (dmax < p[idx]) dmax = p[idx]; C.data_maximum = dmax; } return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } #define TBLN 65535 void LibRaw::exp_bef(float shift, float smooth) { // params limits if (shift > 8) shift = 8; if (shift < 0.25) shift = 0.25; if (smooth < 0.0) smooth = 0.0; if (smooth > 1.0) smooth = 1.0; unsigned short *lut = (ushort *)malloc((TBLN + 1) * sizeof(unsigned short)); if (shift <= 1.0) { for (int i = 0; i <= TBLN; i++) lut[i] = (unsigned short)((float)i * shift); } else { float x1, x2, y1, y2; float cstops = log(shift) / log(2.0f); float room = cstops * 2; float roomlin = powf(2.0f, room); x2 = (float)TBLN; x1 = (x2 + 1) / roomlin - 1; y1 = x1 * shift; y2 = x2 * (1 + (1 - smooth) * (shift - 1)); float sq3x = powf(x1 * x1 * x2, 1.0f / 3.0f); float B = (y2 - y1 + shift * (3 * x1 - 3.0f * sq3x)) / (x2 + 2.0f * x1 - 3.0f * sq3x); float A = (shift - B) * 3.0f * powf(x1 * x1, 1.0f / 3.0f); float CC = y2 - A * powf(x2, 1.0f / 3.0f) - B * x2; for (int i = 0; i <= TBLN; i++) { float X = (float)i; float Y = A * powf(X, 1.0f / 3.0f) + B * X + CC; if (i < x1) lut[i] = (unsigned short)((float)i * shift); else lut[i] = Y < 0 ? 0 : (Y > TBLN ? TBLN : (unsigned short)(Y)); } } for (int i = 0; i < S.height * S.width; i++) { imgdata.image[i][0] = lut[imgdata.image[i][0]]; imgdata.image[i][1] = lut[imgdata.image[i][1]]; imgdata.image[i][2] = lut[imgdata.image[i][2]]; imgdata.image[i][3] = lut[imgdata.image[i][3]]; } if (C.data_maximum <= TBLN) C.data_maximum = lut[C.data_maximum]; if (C.maximum <= TBLN) C.maximum = lut[C.maximum]; free(lut); } #define MIN(a, b) ((a) < (b) ? (a) : (b)) #define MAX(a, b) ((a) > (b) ? (a) : (b)) #define LIM(x, min, max) MAX(min, MIN(x, max)) #define ULIM(x, y, z) ((y) < (z) ? LIM(x, y, z) : LIM(x, z, y)) #define CLIP(x) LIM(x, 0, 65535) void LibRaw::convert_to_rgb_loop(float out_cam[3][4]) { int row, col, c; float out[3]; ushort *img; memset(libraw_internal_data.output_data.histogram, 0, sizeof(int) * LIBRAW_HISTOGRAM_SIZE * 4); for (img = imgdata.image[0], row = 0; row < S.height; row++) for (col = 0; col < S.width; col++, img += 4) { if (!libraw_internal_data.internal_output_params.raw_color) { out[0] = out[1] = out[2] = 0; for (c = 0; c < imgdata.idata.colors; c++) { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } for (c = 0; c < 3; c++) img[c] = CLIP((int)out[c]); } for (c = 0; c < imgdata.idata.colors; c++) libraw_internal_data.output_data.histogram[c][img[c] >> 3]++; } } void LibRaw::scale_colors_loop(float scale_mul[4]) { unsigned size = S.iheight * S.iwidth; if (C.cblack[4] && C.cblack[5]) { int val; for (unsigned i = 0; i < size * 4; i++) { if (!(val = imgdata.image[0][i])) continue; val -= C.cblack[6 + i / 4 / S.iwidth % C.cblack[4] * C.cblack[5] + i / 4 % S.iwidth % C.cblack[5]]; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else if (C.cblack[0] || C.cblack[1] || C.cblack[2] || C.cblack[3]) { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; if (!val) continue; val -= C.cblack[i & 3]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } else // BL is zero { for (unsigned i = 0; i < size * 4; i++) { int val = imgdata.image[0][i]; val *= scale_mul[i & 3]; imgdata.image[0][i] = CLIP(val); } } } void LibRaw::adjust_bl() { int clear_repeat = 0; if (O.user_black >= 0) { C.black = O.user_black; clear_repeat = 1; } for (int i = 0; i < 4; i++) if (O.user_cblack[i] > -1000000) { C.cblack[i] = O.user_cblack[i]; clear_repeat = 1; } if (clear_repeat) C.cblack[4] = C.cblack[5] = 0; // Add common part to cblack[] early if (imgdata.idata.filters > 1000 && (C.cblack[4] + 1) / 2 == 1 && (C.cblack[5] + 1) / 2 == 1) { int clrs[4]; int lastg = -1, gcnt = 0; for (int c = 0; c < 4; c++) { clrs[c] = FC(c / 2, c % 2); if (clrs[c] == 1) { gcnt++; lastg = c; } } if (gcnt > 1 && lastg >= 0) clrs[lastg] = 3; for (int c = 0; c < 4; c++) C.cblack[clrs[c]] += C.cblack[6 + c / 2 % C.cblack[4] * C.cblack[5] + c % 2 % C.cblack[5]]; C.cblack[4] = C.cblack[5] = 0; // imgdata.idata.filters = sfilters; } else if (imgdata.idata.filters <= 1000 && C.cblack[4] == 1 && C.cblack[5] == 1) // Fuji RAF dng { for (int c = 0; c < 4; c++) C.cblack[c] += C.cblack[6]; C.cblack[4] = C.cblack[5] = 0; } // remove common part from C.cblack[] int i = C.cblack[3]; int c; for (c = 0; c < 3; c++) if (i > C.cblack[c]) i = C.cblack[c]; for (c = 0; c < 4; c++) C.cblack[c] -= i; // remove common part C.black += i; // Now calculate common part for cblack[6+] part and move it to C.black if (C.cblack[4] && C.cblack[5]) { i = C.cblack[6]; for (c = 1; c < C.cblack[4] * C.cblack[5]; c++) if (i > C.cblack[6 + c]) i = C.cblack[6 + c]; // Remove i from cblack[6+] int nonz = 0; for (c = 0; c < C.cblack[4] * C.cblack[5]; c++) { C.cblack[6 + c] -= i; if (C.cblack[6 + c]) nonz++; } C.black += i; if (!nonz) C.cblack[4] = C.cblack[5] = 0; } for (c = 0; c < 4; c++) C.cblack[c] += C.black; } int LibRaw::dcraw_process(void) { int quality, i; int iterations = -1, dcb_enhance = 1, noiserd = 0; int eeci_refine_fl = 0, es_med_passes_fl = 0; float cared = 0, cablue = 0; float linenoise = 0; float lclean = 0, cclean = 0; float thresh = 0; float preser = 0; float expos = 1.0; CHECK_ORDER_LOW(LIBRAW_PROGRESS_LOAD_RAW); // CHECK_ORDER_HIGH(LIBRAW_PROGRESS_PRE_INTERPOLATE); try { int no_crop = 1; if (~O.cropbox[2] && ~O.cropbox[3]) no_crop = 0; libraw_decoder_info_t di; get_decoder_info(&di); bool is_bayer = (imgdata.idata.filters || P1.colors == 1); int subtract_inline = !O.bad_pixels && !O.dark_frame && is_bayer && !IO.zero_is_bad; raw2image_ex(subtract_inline); // allocate imgdata.image and copy data! // Adjust sizes int save_4color = O.four_color_rgb; if (IO.zero_is_bad) { remove_zeroes(); SET_PROC_FLAG(LIBRAW_PROGRESS_REMOVE_ZEROES); } if (O.bad_pixels && no_crop) { bad_pixels(O.bad_pixels); SET_PROC_FLAG(LIBRAW_PROGRESS_BAD_PIXELS); } if (O.dark_frame && no_crop) { subtract(O.dark_frame); SET_PROC_FLAG(LIBRAW_PROGRESS_DARK_FRAME); } /* pre subtract black callback: check for it above to disable subtract inline */ if(callbacks.pre_subtractblack_cb) (callbacks.pre_subtractblack_cb)(this); quality = 2 + !IO.fuji_width; if (O.user_qual >= 0) quality = O.user_qual; if (!subtract_inline || !C.data_maximum) { adjust_bl(); subtract_black_internal(); } if (!(di.decoder_flags & LIBRAW_DECODER_FIXEDMAXC)) adjust_maximum(); if (O.user_sat > 0) C.maximum = O.user_sat; if (P1.is_foveon) { if (load_raw == &LibRaw::x3f_load_raw) { // Filter out zeroes for (int i = 0; i < S.height * S.width * 4; i++) if ((short)imgdata.image[0][i] < 0) imgdata.image[0][i] = 0; } SET_PROC_FLAG(LIBRAW_PROGRESS_FOVEON_INTERPOLATE); } if (O.green_matching && !O.half_size) { green_matching(); } if(callbacks.pre_scalecolors_cb) (callbacks.pre_scalecolors_cb)(this); if (!O.no_auto_scale) { scale_colors(); SET_PROC_FLAG(LIBRAW_PROGRESS_SCALE_COLORS); } if(callbacks.pre_preinterpolate_cb) (callbacks.pre_preinterpolate_cb)(this); pre_interpolate(); SET_PROC_FLAG(LIBRAW_PROGRESS_PRE_INTERPOLATE); if (O.dcb_iterations >= 0) iterations = O.dcb_iterations; if (O.dcb_enhance_fl >= 0) dcb_enhance = O.dcb_enhance_fl; if (O.fbdd_noiserd >= 0) noiserd = O.fbdd_noiserd; /* pre-exposure correction callback */ if (O.exp_correc > 0) { expos = O.exp_shift; preser = O.exp_preser; exp_bef(expos, preser); } if(callbacks.pre_interpolate_cb) (callbacks.pre_interpolate_cb)(this); /* post-exposure correction fallback */ if (P1.filters && !O.no_interpolation) { if (noiserd > 0 && P1.colors == 3 && P1.filters) fbdd(noiserd); if (P1.filters > 1000 && callbacks.interpolate_bayer_cb) (callbacks.interpolate_bayer_cb)(this); else if (P1.filters == 9 && callbacks.interpolate_xtrans_cb) (callbacks.interpolate_xtrans_cb)(this); else if (quality == 0) lin_interpolate(); else if (quality == 1 || P1.colors > 3) vng_interpolate(); else if (quality == 2 && P1.filters > 1000) ppg_interpolate(); else if (P1.filters == LIBRAW_XTRANS) { // Fuji X-Trans xtrans_interpolate(quality > 2 ? 3 : 1); } else if (quality == 3) ahd_interpolate(); // really don't need it here due to fallback op else if (quality == 4) dcb(iterations, dcb_enhance); else if (quality == 11) dht_interpolate(); else if (quality == 12) aahd_interpolate(); // fallback to AHD else { ahd_interpolate(); imgdata.process_warnings |= LIBRAW_WARN_FALLBACK_TO_AHD; } SET_PROC_FLAG(LIBRAW_PROGRESS_INTERPOLATE); } if (IO.mix_green) { for (P1.colors = 3, i = 0; i < S.height * S.width; i++) imgdata.image[i][1] = (imgdata.image[i][1] + imgdata.image[i][3]) >> 1; SET_PROC_FLAG(LIBRAW_PROGRESS_MIX_GREEN); } if(callbacks.post_interpolate_cb) (callbacks.post_interpolate_cb)(this); if (!P1.is_foveon) { if (P1.colors == 3) { /* median filter callback, if not set use own */ median_filter(); SET_PROC_FLAG(LIBRAW_PROGRESS_MEDIAN_FILTER); } } if (O.highlight == 2) { blend_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.highlight > 2) { recover_highlights(); SET_PROC_FLAG(LIBRAW_PROGRESS_HIGHLIGHTS); } if (O.use_fuji_rotate) { fuji_rotate(); SET_PROC_FLAG(LIBRAW_PROGRESS_FUJI_ROTATE); } if (!libraw_internal_data.output_data.histogram) { libraw_internal_data.output_data.histogram = (int(*)[LIBRAW_HISTOGRAM_SIZE])malloc(sizeof(*libraw_internal_data.output_data.histogram) * 4); merror(libraw_internal_data.output_data.histogram, "LibRaw::dcraw_process()"); } #ifndef NO_LCMS if (O.camera_profile) { apply_profile(O.camera_profile, O.output_profile); SET_PROC_FLAG(LIBRAW_PROGRESS_APPLY_PROFILE); } #endif if(callbacks.pre_converttorgb_cb) (callbacks.pre_converttorgb_cb)(this); convert_to_rgb(); SET_PROC_FLAG(LIBRAW_PROGRESS_CONVERT_RGB); if(callbacks.post_converttorgb_cb) (callbacks.post_converttorgb_cb)(this); if (O.use_fuji_rotate) { stretch(); SET_PROC_FLAG(LIBRAW_PROGRESS_STRETCH); } O.four_color_rgb = save_4color; // also, restore return 0; } catch (LibRaw_exceptions err) { EXCEPTION_HANDLER(err); } } // clang-format off // Supported cameras: static const char *static_camera_list[] = { "Adobe Digital Negative (DNG)", "AgfaPhoto DC-833m", "Alcatel 5035D", "Apple iPad Pro", "Apple iPhone SE", "Apple iPhone 6s", "Apple iPhone 6 plus", "Apple iPhone 7", "Apple iPhone 7 plus", "Apple iPhone 8", "Apple iPhone 8 plus", "Apple iPhone X", "Apple QuickTake 100", "Apple QuickTake 150", "Apple QuickTake 200", "ARRIRAW format", "AVT F-080C", "AVT F-145C", "AVT F-201C", "AVT F-510C", "AVT F-810C", "Baumer TXG14", "BlackMagic Cinema Camera", "BlackMagic Micro Cinema Camera", "BlackMagic Pocket Cinema Camera", "BlackMagic Production Camera 4k", "BlackMagic URSA", "BlackMagic URSA Mini 4k", "BlackMagic URSA Mini 4.6k", "BlackMagic URSA Mini Pro 4.6k", "Canon PowerShot 600", "Canon PowerShot A5", "Canon PowerShot A5 Zoom", "Canon PowerShot A50", "Canon PowerShot A410 (CHDK hack)", "Canon PowerShot A460 (CHDK hack)", "Canon PowerShot A470 (CHDK hack)", "Canon PowerShot A530 (CHDK hack)", "Canon PowerShot A540 (CHDK hack)", "Canon PowerShot A550 (CHDK hack)", "Canon PowerShot A570 (CHDK hack)", "Canon PowerShot A590 (CHDK hack)", "Canon PowerShot A610 (CHDK hack)", "Canon PowerShot A620 (CHDK hack)", "Canon PowerShot A630 (CHDK hack)", "Canon PowerShot A640 (CHDK hack)", "Canon PowerShot A650 (CHDK hack)", "Canon PowerShot A710 IS (CHDK hack)", "Canon PowerShot A720 IS (CHDK hack)", "Canon PowerShot A3300 IS (CHDK hack)", "Canon PowerShot D10 (CHDK hack)", "Canon PowerShot ELPH 130 IS (CHDK hack)", "Canon PowerShot ELPH 160 IS (CHDK hack)", "Canon PowerShot Pro70", "Canon PowerShot Pro90 IS", "Canon PowerShot Pro1", "Canon PowerShot G1", "Canon PowerShot G1 X", "Canon PowerShot G1 X Mark II", "Canon PowerShot G1 X Mark III", "Canon PowerShot G2", "Canon PowerShot G3", "Canon PowerShot G3 X", "Canon PowerShot G5", "Canon PowerShot G5 X", "Canon PowerShot G6", "Canon PowerShot G7 (CHDK hack)", "Canon PowerShot G7 X", "Canon PowerShot G7 X Mark II", "Canon PowerShot G9", "Canon PowerShot G9 X", "Canon PowerShot G9 X Mark II", "Canon PowerShot G10", "Canon PowerShot G11", "Canon PowerShot G12", "Canon PowerShot G15", "Canon PowerShot G16", "Canon PowerShot S2 IS (CHDK hack)", "Canon PowerShot S3 IS (CHDK hack)", "Canon PowerShot S5 IS (CHDK hack)", "Canon PowerShot SD300 (CHDK hack)", "Canon PowerShot SD750 (CHDK hack)", "Canon PowerShot SD950 (CHDK hack)", "Canon PowerShot S30", "Canon PowerShot S40", "Canon PowerShot S45", "Canon PowerShot S50", "Canon PowerShot S60", "Canon PowerShot S70", "Canon PowerShot S90", "Canon PowerShot S95", "Canon PowerShot S100", "Canon PowerShot S110", "Canon PowerShot S120", "Canon PowerShot SX1 IS", "Canon PowerShot SX50 HS", "Canon PowerShot SX60 HS", "Canon PowerShot SX100 IS (CHDK hack)", "Canon PowerShot SX110 IS (CHDK hack)", "Canon PowerShot SX120 IS (CHDK hack)", "Canon PowerShot SX130 IS (CHDK hack)", "Canon PowerShot SX160 IS (CHDK hack)", "Canon PowerShot SX220 HS (CHDK hack)", "Canon PowerShot SX510 HS (CHDK hack)", "Canon PowerShot SX10 IS (CHDK hack)", "Canon PowerShot SX20 IS (CHDK hack)", "Canon PowerShot SX30 IS (CHDK hack)", "Canon PowerShot IXUS 160 (CHDK hack)", "Canon PowerShot IXUS 900Ti (CHDK hack)", "Canon EOS D30", "Canon EOS D60", "Canon EOS 5D", "Canon EOS 5DS", "Canon EOS 5DS R", "Canon EOS 5D Mark II", "Canon EOS 5D Mark III", "Canon EOS 5D Mark IV", "Canon EOS 6D", "Canon EOS 6D Mark II", "Canon EOS 7D", "Canon EOS 7D Mark II", "Canon EOS 10D", "Canon EOS 20D", "Canon EOS 20Da", "Canon EOS 30D", "Canon EOS 40D", "Canon EOS 50D", "Canon EOS 60D", "Canon EOS 60Da", "Canon EOS 70D", "Canon EOS 77D", "Canon EOS 80D", "Canon EOS 200D", "Canon EOS 300D / Digital Rebel / Kiss Digital", "Canon EOS 350D / Digital Rebel XT / Kiss Digital N", "Canon EOS 400D / Digital Rebel XTi / Kiss Digital X", "Canon EOS 450D / Digital Rebel XSi / Kiss Digital X2", "Canon EOS 500D / Digital Rebel T1i / Kiss Digital X3", "Canon EOS 550D / Digital Rebel T2i / Kiss Digital X4", "Canon EOS 600D / Digital Rebel T3i / Kiss Digital X5", "Canon EOS 650D / Digital Rebel T4i / Kiss Digital X6i", "Canon EOS 700D / Digital Rebel T5i", "Canon EOS 750D / Digital Rebel T6i", "Canon EOS 760D / Digital Rebel T6S", "Canon EOS 800D", "Canon EOS 100D / Digital Rebel SL1", "Canon EOS 1000D / Digital Rebel XS / Kiss Digital F", "Canon EOS 1100D / Digital Rebel T3 / Kiss Digital X50", "Canon EOS 1200D", "Canon EOS 1300D", "Canon EOS C500", "Canon EOS D2000C", "Canon EOS M", "Canon EOS M2", "Canon EOS M3", "Canon EOS M5", "Canon EOS M6", "Canon EOS M10", "Canon EOS M100", "Canon EOS-1D", "Canon EOS-1DS", "Canon EOS-1D C", "Canon EOS-1D X", "Canon EOS-1D Mark II", "Canon EOS-1D Mark II N", "Canon EOS-1D Mark III", "Canon EOS-1D Mark IV", "Canon EOS-1Ds Mark II", "Canon EOS-1Ds Mark III", "Canon EOS-1D X Mark II", "Casio QV-2000UX", "Casio QV-3000EX", "Casio QV-3500EX", "Casio QV-4000", "Casio QV-5700", "Casio QV-R41", "Casio QV-R51", "Casio QV-R61", "Casio EX-F1", "Casio EX-FC300S", "Casio EX-FC400S", "Casio EX-FH20", "Casio EX-FH25", "Casio EX-FH100", "Casio EX-P600", "Casio EX-S20", "Casio EX-S100", "Casio EX-Z4", "Casio EX-Z50", "Casio EX-Z500", "Casio EX-Z55", "Casio EX-Z60", "Casio EX-Z75", "Casio EX-Z750", "Casio EX-Z8", "Casio EX-Z850", "Casio EX-Z1050", "Casio EX-ZR100", "Casio EX-Z1080", "Casio EX-ZR700", "Casio EX-ZR710", "Casio EX-ZR750", "Casio EX-ZR800", "Casio EX-ZR850", "Casio EX-ZR1000", "Casio EX-ZR1100", "Casio EX-ZR1200", "Casio EX-ZR1300", "Casio EX-ZR1500", "Casio EX-ZR3000", "Casio EX-ZR4000/5000", "Casio EX-ZR4100/5100", "Casio EX-100", "Casio EX-100F", "Casio EX-10", "Casio Exlim Pro 505", "Casio Exlim Pro 600", "Casio Exlim Pro 700", "Contax N Digital", "Creative PC-CAM 600", "Digital Bolex D16", "Digital Bolex D16M", "DJI 4384x3288", "DJI Phantom4 Pro/Pro+", "DJI Zenmuse X5", "DJI Zenmuse X5R", "DXO One", "Epson R-D1", "Epson R-D1s", "Epson R-D1x", "Foculus 531C", "FujiFilm E505", "FujiFilm E550", "FujiFilm E900", "FujiFilm F700", "FujiFilm F710", "FujiFilm F800", "FujiFilm F810", "FujiFilm S2Pro", "FujiFilm S3Pro", "FujiFilm S5Pro", "FujiFilm S20Pro", "FujiFilm S1", "FujiFilm S100FS", "FujiFilm S5000", "FujiFilm S5100/S5500", "FujiFilm S5200/S5600", "FujiFilm S6000fd", "FujiFilm S6500fd", "FujiFilm S7000", "FujiFilm S9000/S9500", "FujiFilm S9100/S9600", "FujiFilm S200EXR", "FujiFilm S205EXR", "FujiFilm SL1000", "FujiFilm HS10/HS11", "FujiFilm HS20EXR", "FujiFilm HS22EXR", "FujiFilm HS30EXR", "FujiFilm HS33EXR", "FujiFilm HS35EXR", "FujiFilm HS50EXR", "FujiFilm F505EXR", "FujiFilm F550EXR", "FujiFilm F600EXR", "FujiFilm F605EXR", "FujiFilm F770EXR", "FujiFilm F775EXR", "FujiFilm F800EXR", "FujiFilm F900EXR", "FujiFilm GFX 50S", "FujiFilm X-Pro1", "FujiFilm X-Pro2", "FujiFilm X-S1", "FujiFilm XQ1", "FujiFilm XQ2", "FujiFilm X100", "FujiFilm X100f", "FujiFilm X100S", "FujiFilm X100T", "FujiFilm X10", "FujiFilm X20", "FujiFilm X30", "FujiFilm X70", "FujiFilm X-A1", "FujiFilm X-A2", "FujiFilm X-A3", "FujiFilm X-A5", "FujiFilm X-A10", "FujiFilm X-A20", "FujiFilm X-E1", "FujiFilm X-E2", "FujiFilm X-E2S", "FujiFilm X-E3", "FujiFilm X-M1", "FujiFilm XF1", "FujiFilm X-H1", "FujiFilm X-T1", "FujiFilm X-T1 Graphite Silver", "FujiFilm X-T2", "FujiFilm X-T10", "FujiFilm X-T20", "FujiFilm IS-1", "Gione E7", "GITUP GIT2", "GITUP GIT2P", "Google Pixel", "Google Pixel XL", "Hasselblad H2D-22", "Hasselblad H2D-39", "Hasselblad H3DII-22", "Hasselblad H3DII-31", "Hasselblad H3DII-39", "Hasselblad H3DII-50", "Hasselblad H3D-22", "Hasselblad H3D-31", "Hasselblad H3D-39", "Hasselblad H4D-60", "Hasselblad H4D-50", "Hasselblad H4D-40", "Hasselblad H4D-31", "Hasselblad H5D-60", "Hasselblad H5D-50", "Hasselblad H5D-50c", "Hasselblad H5D-40", "Hasselblad H6D-100c", "Hasselblad A6D-100c", // Aerial camera "Hasselblad CFV", "Hasselblad CFV-50", "Hasselblad CFH", "Hasselblad CF-22", "Hasselblad CF-31", "Hasselblad CF-39", "Hasselblad V96C", "Hasselblad Lusso", "Hasselblad Lunar", "Hasselblad True Zoom", "Hasselblad Stellar", "Hasselblad Stellar II", "Hasselblad HV", "Hasselblad X1D", "HTC UltraPixel", "HTC MyTouch 4G", "HTC One (A9)", "HTC One (M9)", "HTC 10", "Huawei P9 (EVA-L09/AL00)", "Huawei Honor6a", "Huawei Honor9", "Huawei Mate10 (BLA-L29)", "Imacon Ixpress 96, 96C", "Imacon Ixpress 384, 384C (single shot only)", "Imacon Ixpress 132C", "Imacon Ixpress 528C (single shot only)", "ISG 2020x1520", "Ikonoskop A-Cam dII Panchromatic", "Ikonoskop A-Cam dII", "Kinefinity KineMINI", "Kinefinity KineRAW Mini", "Kinefinity KineRAW S35", "Kodak DC20", "Kodak DC25", "Kodak DC40", "Kodak DC50", "Kodak DC120", "Kodak DCS200", "Kodak DCS315C", "Kodak DCS330C", "Kodak DCS420", "Kodak DCS460", "Kodak DCS460A", "Kodak DCS460D", "Kodak DCS520C", "Kodak DCS560C", "Kodak DCS620C", "Kodak DCS620X", "Kodak DCS660C", "Kodak DCS660M", "Kodak DCS720X", "Kodak DCS760C", "Kodak DCS760M", "Kodak EOSDCS1", "Kodak EOSDCS3B", "Kodak NC2000F", "Kodak ProBack", "Kodak PB645C", "Kodak PB645H", "Kodak PB645M", "Kodak DCS Pro 14n", "Kodak DCS Pro 14nx", "Kodak DCS Pro SLR/c", "Kodak DCS Pro SLR/n", "Kodak C330", "Kodak C603", "Kodak P850", "Kodak P880", "Kodak S-1", "Kodak Z980", "Kodak Z981", "Kodak Z990", "Kodak Z1015", "Kodak KAI-0340", "Konica KD-400Z", "Konica KD-510Z", "Leaf AFi 5", "Leaf AFi 6", "Leaf AFi 7", "Leaf AFi-II 6", "Leaf AFi-II 7", "Leaf AFi-II 10", "Leaf AFi-II 10R", "Leaf Aptus-II 5", "Leaf Aptus-II 6", "Leaf Aptus-II 7", "Leaf Aptus-II 8", "Leaf Aptus-II 10", "Leaf Aptus-II 12", "Leaf Aptus-II 12R", "Leaf Aptus 17", "Leaf Aptus 22", "Leaf Aptus 54S", "Leaf Aptus 65", "Leaf Aptus 65S", "Leaf Aptus 75", "Leaf Aptus 75S", "Leaf Cantare", "Leaf Cantare XY", "Leaf CatchLight", "Leaf CMost", "Leaf Credo 40", "Leaf Credo 50", "Leaf Credo 60", "Leaf Credo 80 (low compression mode only)", "Leaf DCB-II", "Leaf Valeo 6", "Leaf Valeo 11", "Leaf Valeo 17", "Leaf Valeo 17wi", "Leaf Valeo 22", "Leaf Valeo 22wi", "Leaf Volare", "Lenovo a820", "Leica C (Typ 112)", "Leica CL", "Leica Digilux 2", "Leica Digilux 3", "Leica Digital-Modul-R", "Leica D-LUX2", "Leica D-LUX3", "Leica D-LUX4", "Leica D-LUX5", "Leica D-LUX6", "Leica D-Lux (Typ 109)", "Leica M8", "Leica M8.2", "Leica M9", "Leica M10", "Leica M (Typ 240)", "Leica M (Typ 262)", "Leica Monochrom (Typ 240)", "Leica Monochrom (Typ 246)", "Leica M-D (Typ 262)", "Leica M-E", "Leica M-P", "Leica R8", "Leica Q (Typ 116)", "Leica S", "Leica S2", "Leica S (Typ 007)", "Leica SL (Typ 601)", "Leica T (Typ 701)", "Leica TL", "Leica TL2", "Leica X1", "Leica X (Typ 113)", "Leica X2", "Leica X-E (Typ 102)", "Leica X-U (Typ 113)", "Leica V-LUX1", "Leica V-LUX2", "Leica V-LUX3", "Leica V-LUX4", "Leica V-Lux (Typ 114)", "Leica X VARIO (Typ 107)", "LG G3", "LG G4", "LG V20 (F800K)", "LG VS995", "Logitech Fotoman Pixtura", "Mamiya ZD", "Matrix 4608x3288", "Meizy MX4", "Micron 2010", "Minolta RD175", "Minolta DiMAGE 5", "Minolta DiMAGE 7", "Minolta DiMAGE 7i", "Minolta DiMAGE 7Hi", "Minolta DiMAGE A1", "Minolta DiMAGE A2", "Minolta DiMAGE A200", "Minolta DiMAGE G400", "Minolta DiMAGE G500", "Minolta DiMAGE G530", "Minolta DiMAGE G600", "Minolta DiMAGE Z2", "Minolta Alpha/Dynax/Maxxum 5D", "Minolta Alpha/Dynax/Maxxum 7D", "Motorola PIXL", "Nikon D1", "Nikon D1H", "Nikon D1X", "Nikon D2H", "Nikon D2Hs", "Nikon D2X", "Nikon D2Xs", "Nikon D3", "Nikon D3s", "Nikon D3X", "Nikon D4", "Nikon D4s", "Nikon D40", "Nikon D40X", "Nikon D5", "Nikon D50", "Nikon D60", "Nikon D70", "Nikon D70s", "Nikon D80", "Nikon D90", "Nikon D100", "Nikon D200", "Nikon D300", "Nikon D300s", "Nikon D500", "Nikon D600", "Nikon D610", "Nikon D700", "Nikon D750", "Nikon D800", "Nikon D800E", "Nikon D810", "Nikon D810A", "Nikon D850", "Nikon D3000", "Nikon D3100", "Nikon D3200", "Nikon D3300", "Nikon D3400", "Nikon D5000", "Nikon D5100", "Nikon D5200", "Nikon D5300", "Nikon D5500", "Nikon D5600", "Nikon D7000", "Nikon D7100", "Nikon D7200", "Nikon D7500", "Nikon Df", "Nikon 1 AW1", "Nikon 1 J1", "Nikon 1 J2", "Nikon 1 J3", "Nikon 1 J4", "Nikon 1 J5", "Nikon 1 S1", "Nikon 1 S2", "Nikon 1 V1", "Nikon 1 V2", "Nikon 1 V3", "Nikon E700 (\"DIAG RAW\" hack)", "Nikon E800 (\"DIAG RAW\" hack)", "Nikon E880 (\"DIAG RAW\" hack)", "Nikon E900 (\"DIAG RAW\" hack)", "Nikon E950 (\"DIAG RAW\" hack)", "Nikon E990 (\"DIAG RAW\" hack)", "Nikon E995 (\"DIAG RAW\" hack)", "Nikon E2100 (\"DIAG RAW\" hack)", "Nikon E2500 (\"DIAG RAW\" hack)", "Nikon E3200 (\"DIAG RAW\" hack)", "Nikon E3700 (\"DIAG RAW\" hack)", "Nikon E4300 (\"DIAG RAW\" hack)", "Nikon E4500 (\"DIAG RAW\" hack)", "Nikon E5000", "Nikon E5400", "Nikon E5700", "Nikon E8400", "Nikon E8700", "Nikon E8800", "Nikon Coolpix A", "Nikon Coolpix B700", "Nikon Coolpix P330", "Nikon Coolpix P340", "Nikon Coolpix P6000", "Nikon Coolpix P7000", "Nikon Coolpix P7100", "Nikon Coolpix P7700", "Nikon Coolpix P7800", "Nikon Coolpix S6 (\"DIAG RAW\" hack)", "Nikon Coolscan NEF", "Nokia N95", "Nokia X2", "Nokia 1200x1600", "Nokia Lumia 950 XL", "Nokia Lumia 1020", "Nokia Lumia 1520", "Olympus AIR A01", "Olympus C3030Z", "Olympus C5050Z", "Olympus C5060Z", "Olympus C7070WZ", "Olympus C70Z,C7000Z", "Olympus C740UZ", "Olympus C770UZ", "Olympus C8080WZ", "Olympus X200,D560Z,C350Z", "Olympus E-1", "Olympus E-3", "Olympus E-5", "Olympus E-10", "Olympus E-20", "Olympus E-30", "Olympus E-300", "Olympus E-330", "Olympus E-400", "Olympus E-410", "Olympus E-420", "Olympus E-450", "Olympus E-500", "Olympus E-510", "Olympus E-520", "Olympus E-600", "Olympus E-620", "Olympus E-P1", "Olympus E-P2", "Olympus E-P3", "Olympus E-P5", "Olympus E-PL1", "Olympus E-PL1s", "Olympus E-PL2", "Olympus E-PL3", "Olympus E-PL5", "Olympus E-PL6", "Olympus E-PL7", "Olympus E-PL8", "Olympus E-PL9", "Olympus E-PM1", "Olympus E-PM2", "Olympus E-M1", "Olympus E-M1 Mark II", "Olympus E-M10", "Olympus E-M10 Mark II", "Olympus E-M10 Mark III", "Olympus E-M5", "Olympus E-M5 Mark II", "Olympus Pen F", "Olympus SP310", "Olympus SP320", "Olympus SP350", "Olympus SP500UZ", "Olympus SP510UZ", "Olympus SP550UZ", "Olympus SP560UZ", "Olympus SP565UZ", "Olympus SP570UZ", "Olympus STYLUS1", "Olympus STYLUS1s", "Olympus SH-2", "Olympus SH-3", "Olympus TG-4", "Olympus TG-5", "Olympus XZ-1", "Olympus XZ-2", "Olympus XZ-10", "OmniVision 4688", "OmniVision OV5647", "OmniVision OV5648", "OmniVision OV8850", "OmniVision 13860", "OnePlus One", "OnePlus A3303", "OnePlus A5000", "Panasonic DMC-CM1", "Panasonic DMC-FZ8", "Panasonic DMC-FZ18", "Panasonic DMC-FZ28", "Panasonic DMC-FZ30", "Panasonic DMC-FZ35/FZ38", "Panasonic DMC-FZ40", "Panasonic DMC-FZ45", "Panasonic DMC-FZ50", "Panasonic DMC-FZ7", "Panasonic DMC-FZ70", "Panasonic DMC-FZ72", "Panasonic DC-FZ80/82", "Panasonic DMC-FZ100", "Panasonic DMC-FZ150", "Panasonic DMC-FZ200", "Panasonic DMC-FZ300/330", "Panasonic DMC-FZ1000", "Panasonic DMC-FZ2000/2500/FZH1", "Panasonic DMC-FX150", "Panasonic DMC-G1", "Panasonic DMC-G10", "Panasonic DMC-G2", "Panasonic DMC-G3", "Panasonic DMC-G5", "Panasonic DMC-G6", "Panasonic DMC-G7/G70", "Panasonic DMC-G8/80/81/85", "Panasonic DC-G9", "Panasonic DMC-GF1", "Panasonic DMC-GF2", "Panasonic DMC-GF3", "Panasonic DMC-GF5", "Panasonic DMC-GF6", "Panasonic DMC-GF7", "Panasonic DC-GF10/GF90", "Panasonic DMC-GH1", "Panasonic DMC-GH2", "Panasonic DMC-GH3", "Panasonic DMC-GH4", "Panasonic AG-GH4", "Panasonic DC-GH5", "Panasonic DMC-GM1", "Panasonic DMC-GM1s", "Panasonic DMC-GM5", "Panasonic DMC-GX1", "Panasonic DMC-GX7", "Panasonic DMC-GX8", "Panasonic DC-GX9", "Panasonic DMC-GX80/85", "Panasonic DC-GX800/850/GF9", "Panasonic DMC-L1", "Panasonic DMC-L10", "Panasonic DMC-LC1", "Panasonic DMC-LF1", "Panasonic DMC-LX1", "Panasonic DMC-LX2", "Panasonic DMC-LX3", "Panasonic DMC-LX5", "Panasonic DMC-LX7", "Panasonic DMC-LX9/10/15", "Panasonic DMC-LX100", "Panasonic DMC-TZ60/61/SZ40", "Panasonic DMC-TZ70/71/ZS50", "Panasonic DMC-TZ80/81/85/ZS60", "Panasonic DC-ZS70 (DC-TZ90/91/92, DC-T93)", "Panasonic DC-TZ100/101/ZS100", "Panasonic DC-TZ200/ZS200", "PARROT Bebop 2", "PARROT Bebop Drone", "Pentax *ist D", "Pentax *ist DL", "Pentax *ist DL2", "Pentax *ist DS", "Pentax *ist DS2", "Pentax GR", "Pentax K10D", "Pentax K20D", "Pentax K100D", "Pentax K100D Super", "Pentax K110D", "Pentax K200D", "Pentax K2000/K-m", "Pentax KP", "Pentax K-x", "Pentax K-r", "Pentax K-01", "Pentax K-1", "Pentax K-3", "Pentax K-3 II", "Pentax K-30", "Pentax K-5", "Pentax K-5 II", "Pentax K-5 IIs", "Pentax K-50", "Pentax K-500", "Pentax K-7", "Pentax K-70", "Pentax K-S1", "Pentax K-S2", "Pentax MX-1", "Pentax Q", "Pentax Q7", "Pentax Q10", "Pentax QS-1", "Pentax Optio S", "Pentax Optio S4", "Pentax Optio 33WR", "Pentax Optio 750Z", "Pentax 645D", "Pentax 645Z", "PhaseOne IQ140", "PhaseOne IQ150", "PhaseOne IQ160", "PhaseOne IQ180", "PhaseOne IQ180 IR", "PhaseOne IQ250", "PhaseOne IQ260", "PhaseOne IQ260 Achromatic", "PhaseOne IQ280", "PhaseOne IQ3 50MP", "PhaseOne IQ3 60MP", "PhaseOne IQ3 80MP", "PhaseOne IQ3 100MP", "PhaseOne IQ3 100MP Trichromatic", "PhaseOne LightPhase", "PhaseOne Achromatic+", "PhaseOne H 10", "PhaseOne H 20", "PhaseOne H 25", "PhaseOne P 20", "PhaseOne P 20+", "PhaseOne P 21", "PhaseOne P 25", "PhaseOne P 25+", "PhaseOne P 30", "PhaseOne P 30+", "PhaseOne P 40+", "PhaseOne P 45", "PhaseOne P 45+", "PhaseOne P 65", "PhaseOne P 65+", "Photron BC2-HD", "Pixelink A782", "Polaroid x530", "RaspberryPi Camera", "RaspberryPi Camera V2", "Ricoh GR", "Ricoh GR Digital", "Ricoh GR Digital II", "Ricoh GR Digital III", "Ricoh GR Digital IV", "Ricoh GR II", "Ricoh GX100", "Ricoh GX200", "Ricoh GXR MOUNT A12", "Ricoh GXR MOUNT A16 24-85mm F3.5-5.5", "Ricoh GXR, S10 24-72mm F2.5-4.4 VC", "Ricoh GXR, GR A12 50mm F2.5 MACRO", "Ricoh GXR, GR LENS A12 28mm F2.5", "Ricoh GXR, GXR P10", #ifndef NO_JASPER "Redcode R3D format", #endif "Rollei d530flex", "RoverShot 3320af", "Samsung EX1", "Samsung EX2F", "Samsung GX-1L", "Samsung GX-1S", "Samsung GX10", "Samsung GX20", "Samsung Galaxy Nexus", "Samsung Galaxy NX (EK-GN120)", "Samsung Galaxy S3", "Samsung Galaxy S6 (SM-G920F)", "Samsung Galaxy S7", "Samsung Galaxy S7 Edge", "Samsung Galaxy S8 (SM-G950U)", "Samsung NX1", "Samsung NX5", "Samsung NX10", "Samsung NX11", "Samsung NX100", "Samsung NX1000", "Samsung NX1100", "Samsung NX20", "Samsung NX200", "Samsung NX210", "Samsung NX2000", "Samsung NX30", "Samsung NX300", "Samsung NX300M", "Samsung NX3000", "Samsung NX500", "Samsung NX mini", "Samsung Pro815", "Samsung WB550", "Samsung WB2000", "Samsung S85 (hacked)", "Samsung S850 (hacked)", "Sarnoff 4096x5440", "Seitz 6x17", "Seitz Roundshot D3", "Seitz Roundshot D2X", "Seitz Roundshot D2Xs", "Sigma SD9 (raw decode only)", "Sigma SD10 (raw decode only)", "Sigma SD14 (raw decode only)", "Sigma SD15 (raw decode only)", "Sigma SD1", "Sigma SD1 Merill", "Sigma DP1", "Sigma DP1 Merill", "Sigma DP1S", "Sigma DP1X", "Sigma DP2", "Sigma DP2 Merill", "Sigma DP2S", "Sigma DP2X", "Sigma DP3 Merill", "Sigma dp0 Quattro", "Sigma dp1 Quattro", "Sigma dp2 Quattro", "Sigma dp3 Quattro", "Sigma sd Quattro", "Sigma sd Quattro H", "Sinar eMotion 22", "Sinar eMotion 54", "Sinar eSpirit 65", "Sinar eMotion 75", "Sinar eVolution 75", "Sinar 3072x2048", "Sinar 4080x4080", "Sinar 4080x5440", "Sinar STI format", "Sinar Sinarback 54", "SMaL Ultra-Pocket 3", "SMaL Ultra-Pocket 4", "SMaL Ultra-Pocket 5", "Sony A7", "Sony A7 II", "Sony A7R", "Sony A7R II", "Sony A7R III", "Sony A7S", "Sony A7S II", "Sony A9", "Sony ILCA-68 (A68)", "Sony ILCA-77M2 (A77-II)", "Sony ILCA-99M2 (A99-II)", "Sony ILCE-3000", "Sony ILCE-5000", "Sony ILCE-5100", "Sony ILCE-6000", "Sony ILCE-6300", "Sony ILCE-6500", "Sony ILCE-QX1", "Sony DSC-F828", "Sony DSC-R1", "Sony DSC-RX0", "Sony DSC-RX1", "Sony DSC-RX1R", "Sony DSC-RX1R II", "Sony DSC-RX10", "Sony DSC-RX10II", "Sony DSC-RX10III", "Sony DSC-RX10IV", "Sony DSC-RX100", "Sony DSC-RX100II", "Sony DSC-RX100III", "Sony DSC-RX100IV", "Sony DSC-RX100V", "Sony DSC-V3", "Sony DSLR-A100", "Sony DSLR-A200", "Sony DSLR-A230", "Sony DSLR-A290", "Sony DSLR-A300", "Sony DSLR-A330", "Sony DSLR-A350", "Sony DSLR-A380", "Sony DSLR-A390", "Sony DSLR-A450", "Sony DSLR-A500", "Sony DSLR-A550", "Sony DSLR-A560", "Sony DSLR-A580", "Sony DSLR-A700", "Sony DSLR-A850", "Sony DSLR-A900", "Sony NEX-3", "Sony NEX-3N", "Sony NEX-5", "Sony NEX-5N", "Sony NEX-5R", "Sony NEX-5T", "Sony NEX-6", "Sony NEX-7", "Sony NEX-C3", "Sony NEX-F3", "Sony NEX-VG20", "Sony NEX-VG30", "Sony NEX-VG900", "Sony SLT-A33", "Sony SLT-A35", "Sony SLT-A37", "Sony SLT-A55V", "Sony SLT-A57", "Sony SLT-A58", "Sony SLT-A65V", "Sony SLT-A77V", "Sony SLT-A99V", "Sony XCD-SX910CR", "Sony IMX135-mipi 13mp", "Sony IMX135-QCOM", "Sony IMX072-mipi", "Sony IMX214", "Sony IMX219", "Sony IMX230", "Sony IMX298-mipi 16mp", "Sony IMX219-mipi 8mp", "Sony Xperia L", "STV680 VGA", "PtGrey GRAS-50S5C", "JaiPulnix BB-500CL", "JaiPulnix BB-500GE", "SVS SVS625CL", "Yi M1", "YUNEEC CGO3", "YUNEEC CGO3P", "YUNEEC CGO4", "Xiaomi MI3", "Xiaomi RedMi Note3 Pro", "Xiaoyi YIAC3 (YI 4k)", NULL }; // clang-format on const char **LibRaw::cameraList() { return static_camera_list; } int LibRaw::cameraCount() { return (sizeof(static_camera_list) / sizeof(static_camera_list[0])) - 1; } const char *LibRaw::strprogress(enum LibRaw_progress p) { switch (p) { case LIBRAW_PROGRESS_START: return "Starting"; case LIBRAW_PROGRESS_OPEN: return "Opening file"; case LIBRAW_PROGRESS_IDENTIFY: return "Reading metadata"; case LIBRAW_PROGRESS_SIZE_ADJUST: return "Adjusting size"; case LIBRAW_PROGRESS_LOAD_RAW: return "Reading RAW data"; case LIBRAW_PROGRESS_REMOVE_ZEROES: return "Clearing zero values"; case LIBRAW_PROGRESS_BAD_PIXELS: return "Removing dead pixels"; case LIBRAW_PROGRESS_DARK_FRAME: return "Subtracting dark frame data"; case LIBRAW_PROGRESS_FOVEON_INTERPOLATE: return "Interpolating Foveon sensor data"; case LIBRAW_PROGRESS_SCALE_COLORS: return "Scaling colors"; case LIBRAW_PROGRESS_PRE_INTERPOLATE: return "Pre-interpolating"; case LIBRAW_PROGRESS_INTERPOLATE: return "Interpolating"; case LIBRAW_PROGRESS_MIX_GREEN: return "Mixing green channels"; case LIBRAW_PROGRESS_MEDIAN_FILTER: return "Median filter"; case LIBRAW_PROGRESS_HIGHLIGHTS: return "Highlight recovery"; case LIBRAW_PROGRESS_FUJI_ROTATE: return "Rotating Fuji diagonal data"; case LIBRAW_PROGRESS_FLIP: return "Flipping image"; case LIBRAW_PROGRESS_APPLY_PROFILE: return "ICC conversion"; case LIBRAW_PROGRESS_CONVERT_RGB: return "Converting to RGB"; case LIBRAW_PROGRESS_STRETCH: return "Stretching image"; case LIBRAW_PROGRESS_THUMB_LOAD: return "Loading thumbnail"; default: return "Some strange things"; } } #undef ID #include "../internal/libraw_x3f.cpp" void x3f_clear(void *p) { x3f_delete((x3f_t *)p); } static char *utf2char(utf16_t *str, char *buffer) { char *b = buffer; while (*str != 0x00) { char *chr = (char *)str; *b++ = *chr; str++; } *b = 0; return buffer; } static void *lr_memmem(const void *l, size_t l_len, const void *s, size_t s_len) { register char *cur, *last; const char *cl = (const char *)l; const char *cs = (const char *)s; /* we need something to compare */ if (l_len == 0 || s_len == 0) return NULL; /* "s" must be smaller or equal to "l" */ if (l_len < s_len) return NULL; /* special case where s_len == 1 */ if (s_len == 1) return (void *)memchr(l, (int)*cs, l_len); /* the last position where its possible to find "s" in "l" */ last = (char *)cl + l_len - s_len; for (cur = (char *)cl; cur <= last; cur++) if (cur[0] == cs[0] && memcmp(cur, cs, s_len) == 0) return cur; return NULL; } void LibRaw::parse_x3f() { x3f_t *x3f = x3f_new_from_file(libraw_internal_data.internal_data.input); if (!x3f) return; _x3f_data = x3f; x3f_header_t *H = NULL; x3f_directory_section_t *DS = NULL; H = &x3f->header; // Parse RAW size from RAW section x3f_directory_entry_t *DE = x3f_get_raw(x3f); if (!DE) return; imgdata.sizes.flip = H->rotation; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.sizes.raw_width = ID->columns; imgdata.sizes.raw_height = ID->rows; // Parse other params from property section DE = x3f_get_prop(x3f); if ((x3f_load_data(x3f, DE) == X3F_OK)) { // Parse property list DEH = &DE->header; x3f_property_list_t *PL = &DEH->data_subsection.property_list; if (PL->property_table.size != 0) { int i; x3f_property_t *P = PL->property_table.element; for (i = 0; i < PL->num_properties; i++) { char name[100], value[100]; utf2char(P[i].name, name); utf2char(P[i].value, value); if (!strcmp(name, "ISO")) imgdata.other.iso_speed = atoi(value); if (!strcmp(name, "CAMMANUF")) strcpy(imgdata.idata.make, value); if (!strcmp(name, "CAMMODEL")) strcpy(imgdata.idata.model, value); if (!strcmp(name, "CAMSERIAL")) strcpy(imgdata.shootinginfo.BodySerial, value); if (!strcmp(name, "WB_DESC")) strcpy(imgdata.color.model2, value); if (!strcmp(name, "TIME")) imgdata.other.timestamp = atoi(value); if (!strcmp(name, "SHUTTER")) imgdata.other.shutter = atof(value); if (!strcmp(name, "APERTURE")) imgdata.other.aperture = atof(value); if (!strcmp(name, "FLENGTH")) imgdata.other.focal_len = atof(value); if (!strcmp(name, "FLEQ35MM")) imgdata.lens.makernotes.FocalLengthIn35mmFormat = atof(value); if (!strcmp(name, "IMAGERTEMP")) imgdata.other.SensorTemperature = atof(value); if (!strcmp(name, "LENSARANGE")) { char *sp; imgdata.lens.makernotes.MaxAp4CurFocal = imgdata.lens.makernotes.MinAp4CurFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MinAp4CurFocal = atof(sp); if (imgdata.lens.makernotes.MaxAp4CurFocal > imgdata.lens.makernotes.MinAp4CurFocal) my_swap(float, imgdata.lens.makernotes.MaxAp4CurFocal, imgdata.lens.makernotes.MinAp4CurFocal); } } if (!strcmp(name, "LENSFRANGE")) { char *sp; imgdata.lens.makernotes.MinFocal = imgdata.lens.makernotes.MaxFocal = atof(value); sp = strrchr(value, ' '); if (sp) { imgdata.lens.makernotes.MaxFocal = atof(sp); if ((imgdata.lens.makernotes.MaxFocal + 0.17f) < imgdata.lens.makernotes.MinFocal) my_swap(float, imgdata.lens.makernotes.MaxFocal, imgdata.lens.makernotes.MinFocal); } } if (!strcmp(name, "LENSMODEL")) { char *sp; imgdata.lens.makernotes.LensID = strtol(value, &sp, 16); // atoi(value); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = Sigma_X3F; } } imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff imgdata.color.maximum = 0x3fff; // To be reset by color table libraw_internal_data.unpacker_data.order = 0x4949; } } else { // No property list if (imgdata.sizes.raw_width == 5888 || imgdata.sizes.raw_width == 2944 || imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328 || imgdata.sizes.raw_width == 5504 || imgdata.sizes.raw_width == 2752) // Quattro { imgdata.idata.raw_count = 1; load_raw = &LibRaw::x3f_load_raw; imgdata.sizes.raw_pitch = imgdata.sizes.raw_width * 6; imgdata.idata.is_foveon = 1; libraw_internal_data.internal_output_params.raw_color = 1; // Force adobe coeff libraw_internal_data.unpacker_data.order = 0x4949; strcpy(imgdata.idata.make, "SIGMA"); #if 1 // Try to find model number in first 2048 bytes; int pos = libraw_internal_data.internal_data.input->tell(); libraw_internal_data.internal_data.input->seek(0, SEEK_SET); unsigned char buf[2048]; libraw_internal_data.internal_data.input->read(buf, 2048, 1); libraw_internal_data.internal_data.input->seek(pos, SEEK_SET); unsigned char *fnd = (unsigned char *)lr_memmem(buf, 2048, "SIGMA dp", 8); unsigned char *fndsd = (unsigned char *)lr_memmem(buf, 2048, "sd Quatt", 8); if (fnd) { unsigned char *nm = fnd + 8; snprintf(imgdata.idata.model, 64, "dp%c Quattro", *nm <= '9' && *nm >= '0' ? *nm : '2'); } else if (fndsd) { snprintf(imgdata.idata.model, 64, "%s", fndsd); } else #endif if (imgdata.sizes.raw_width == 6656 || imgdata.sizes.raw_width == 3328) strcpy(imgdata.idata.model, "sd Quattro H"); else strcpy(imgdata.idata.model, "dp2 Quattro"); } // else } // Try to get thumbnail data LibRaw_thumbnail_formats format = LIBRAW_THUMBNAIL_UNKNOWN; if ((DE = x3f_get_thumb_jpeg(x3f))) { format = LIBRAW_THUMBNAIL_JPEG; } else if ((DE = x3f_get_thumb_plain(x3f))) { format = LIBRAW_THUMBNAIL_BITMAP; } if (DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; imgdata.thumbnail.tformat = format; libraw_internal_data.internal_data.toffset = DE->input.offset; write_thumb = &LibRaw::x3f_thumb_loader; } } INT64 LibRaw::x3f_thumb_size() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return -1; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return -1; int64_t p = x3f_load_data_size(x3f, DE); if (p < 0 || p > 0xffffffff) return -1; return p; } catch (...) { return -1; } } void LibRaw::x3f_thumb_loader() { try { x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set x3f_directory_entry_t *DE = x3f_get_thumb_jpeg(x3f); if (!DE) DE = x3f_get_thumb_plain(x3f); if (!DE) return; if (X3F_OK != x3f_load_data(x3f, DE)) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; imgdata.thumbnail.twidth = ID->columns; imgdata.thumbnail.theight = ID->rows; imgdata.thumbnail.tcolors = 3; if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_JPEG) { imgdata.thumbnail.thumb = (char *)malloc(ID->data_size); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); memmove(imgdata.thumbnail.thumb, ID->data, ID->data_size); imgdata.thumbnail.tlength = ID->data_size; } else if (imgdata.thumbnail.tformat == LIBRAW_THUMBNAIL_BITMAP) { imgdata.thumbnail.tlength = ID->columns * ID->rows * 3; imgdata.thumbnail.thumb = (char *)malloc(ID->columns * ID->rows * 3); merror(imgdata.thumbnail.thumb, "LibRaw::x3f_thumb_loader()"); char *src0 = (char *)ID->data; for (int row = 0; row < ID->rows; row++) { int offset = row * ID->row_stride; if (offset + ID->columns * 3 > ID->data_size) break; char *dest = &imgdata.thumbnail.thumb[row * ID->columns * 3]; char *src = &src0[offset]; memmove(dest, src, ID->columns * 3); } } } catch (...) { // do nothing } } static inline uint32_t _clampbits(int x, uint32_t n) { uint32_t _y_temp; if ((_y_temp = x >> n)) x = ~_y_temp >> (32 - n); return x; } void LibRaw::x3f_dpq_interpolate_rg() { int w = imgdata.sizes.raw_width / 2; int h = imgdata.sizes.raw_height / 2; unsigned short *image = (ushort *)imgdata.rawdata.color3_image; for (int color = 0; color < 2; color++) { for (int y = 2; y < (h - 2); y++) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * (y * 2) + color]; // dst[1] uint16_t row0_3 = row0[3]; uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y * 2 + 1) + color]; // dst1[1] uint16_t row1_3 = row1[3]; for (int x = 2; x < (w - 2); x++) { row1[0] = row1[3] = row0[3] = row0[0]; row0 += 6; row1 += 6; } } } } #define _ABS(a) ((a) < 0 ? -(a) : (a)) #undef CLIP #define CLIP(value, high) ((value) > (high) ? (high) : (value)) void LibRaw::x3f_dpq_interpolate_af(int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = 0; y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { if (y < imgdata.rawdata.sizes.top_margin) continue; if (y < scale) continue; if (y > imgdata.rawdata.sizes.raw_height - scale) break; uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже for (int x = 0; x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { if (x < imgdata.rawdata.sizes.left_margin) continue; if (x < scale) continue; if (x > imgdata.rawdata.sizes.raw_width - scale) break; uint16_t *pixel0 = &row0[x * 3]; uint16_t *pixel_top = &row_minus[x * 3]; uint16_t *pixel_bottom = &row_plus[x * 3]; uint16_t *pixel_left = &row0[(x - scale) * 3]; uint16_t *pixel_right = &row0[(x + scale) * 3]; uint16_t *pixf = pixel_top; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_bottom[2] - pixel0[2])) pixf = pixel_bottom; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_left[2] - pixel0[2])) pixf = pixel_left; if (_ABS(pixf[2] - pixel0[2]) > _ABS(pixel_right[2] - pixel0[2])) pixf = pixel_right; int blocal = pixel0[2], bnear = pixf[2]; if (blocal < imgdata.color.black + 16 || bnear < imgdata.color.black + 16) { if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; pixel0[0] = CLIP((pixel0[0] - imgdata.color.black) * 4 + imgdata.color.black, 16383); pixel0[1] = CLIP((pixel0[1] - imgdata.color.black) * 4 + imgdata.color.black, 16383); } else { float multip = float(bnear - imgdata.color.black) / float(blocal - imgdata.color.black); if (pixel0[0] < imgdata.color.black) pixel0[0] = imgdata.color.black; if (pixel0[1] < imgdata.color.black) pixel0[1] = imgdata.color.black; float pixf0 = pixf[0]; if (pixf0 < imgdata.color.black) pixf0 = imgdata.color.black; float pixf1 = pixf[1]; if (pixf1 < imgdata.color.black) pixf1 = imgdata.color.black; pixel0[0] = CLIP(((float(pixf0 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[0] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); pixel0[1] = CLIP(((float(pixf1 - imgdata.color.black) * multip + imgdata.color.black) + ((pixel0[1] - imgdata.color.black) * 3.75 + imgdata.color.black)) / 2, 16383); // pixel0[1] = float(pixf[1]-imgdata.color.black)*multip + imgdata.color.black; } } } } void LibRaw::x3f_dpq_interpolate_af_sd(int xstart, int ystart, int xend, int yend, int xstep, int ystep, int scale) { unsigned short *image = (ushort *)imgdata.rawdata.color3_image; unsigned int rowpitch = imgdata.rawdata.sizes.raw_pitch / 2; // in 16-bit words // Interpolate single pixel for (int y = ystart; y < yend && y < imgdata.rawdata.sizes.height + imgdata.rawdata.sizes.top_margin; y += ystep) { uint16_t *row0 = &image[imgdata.sizes.raw_width * 3 * y]; // Наша строка uint16_t *row1 = &image[imgdata.sizes.raw_width * 3 * (y + 1)]; // Следующая строка uint16_t *row_minus = &image[imgdata.sizes.raw_width * 3 * (y - scale)]; // Строка выше uint16_t *row_plus = &image[imgdata.sizes.raw_width * 3 * (y + scale)]; // Строка ниже AF-point (scale=2 -> ниже row1 uint16_t *row_minus1 = &image[imgdata.sizes.raw_width * 3 * (y - 1)]; for (int x = xstart; x < xend && x < imgdata.rawdata.sizes.width + imgdata.rawdata.sizes.left_margin; x += xstep) { uint16_t *pixel00 = &row0[x * 3]; // Current pixel float sumR = 0.f, sumG = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumR += row_minus[(x + xx) * 3]; sumR += row_plus[(x + xx) * 3]; sumG += row_minus[(x + xx) * 3 + 1]; sumG += row_plus[(x + xx) * 3 + 1]; cnt += 1.f; if (xx) { cnt += 1.f; sumR += row0[(x + xx) * 3]; sumG += row0[(x + xx) * 3 + 1]; } } pixel00[0] = sumR / 8.f; pixel00[1] = sumG / 8.f; if (scale == 2) { uint16_t *pixel0B = &row0[x * 3 + 3]; // right pixel uint16_t *pixel1B = &row1[x * 3 + 3]; // right pixel float sumG0 = 0, sumG1 = 0.f; float cnt = 0.f; for (int xx = -scale; xx <= scale; xx += scale) { sumG0 += row_minus1[(x + xx) * 3 + 2]; sumG1 += row_plus[(x + xx) * 3 + 2]; cnt += 1.f; if (xx) { sumG0 += row0[(x + xx) * 3 + 2]; sumG1 += row1[(x + xx) * 3 + 2]; cnt += 1.f; } } pixel0B[2] = sumG0 / cnt; pixel1B[2] = sumG1 / cnt; } // uint16_t* pixel10 = &row1[x*3]; // Pixel below current // uint16_t* pixel_bottom = &row_plus[x*3]; } } } void LibRaw::x3f_load_raw() { // already in try/catch int raise_error = 0; x3f_t *x3f = (x3f_t *)_x3f_data; if (!x3f) return; // No data pointer set if (X3F_OK == x3f_load_data(x3f, x3f_get_raw(x3f))) { x3f_directory_entry_t *DE = x3f_get_raw(x3f); x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID) throw LIBRAW_EXCEPTION_IO_CORRUPT; x3f_quattro_t *Q = ID->quattro; x3f_huffman_t *HUF = ID->huffman; x3f_true_t *TRU = ID->tru; uint16_t *data = NULL; if (ID->rows != S.raw_height || ID->columns != S.raw_width) { raise_error = 1; goto end; } if (HUF != NULL) data = HUF->x3rgb16.data; if (TRU != NULL) data = TRU->x3rgb16.data; if (data == NULL) { raise_error = 1; goto end; } size_t datasize = S.raw_height * S.raw_width * 3 * sizeof(unsigned short); S.raw_pitch = S.raw_width * 3 * sizeof(unsigned short); if (!(imgdata.rawdata.raw_alloc = malloc(datasize))) throw LIBRAW_EXCEPTION_ALLOC; imgdata.rawdata.color3_image = (ushort(*)[3])imgdata.rawdata.raw_alloc; if (HUF) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && (!Q || !Q->quattro_layout)) memmove(imgdata.rawdata.raw_alloc, data, datasize); else if (TRU && Q) { // Move quattro data in place // R/B plane for (int prow = 0; prow < TRU->x3rgb16.rows && prow < S.raw_height / 2; prow++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[prow * 2 * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow)[3] = (unsigned short(*)[3]) & data[prow * TRU->x3rgb16.row_stride]; for (int pcol = 0; pcol < TRU->x3rgb16.columns && pcol < S.raw_width / 2; pcol++) { destrow[pcol * 2][0] = srcrow[pcol][0]; destrow[pcol * 2][1] = srcrow[pcol][1]; } } for (int row = 0; row < Q->top16.rows && row < S.raw_height; row++) { ushort(*destrow)[3] = (unsigned short(*)[3]) & imgdata.rawdata.color3_image[row * S.raw_pitch / 3 / sizeof(ushort)][0]; ushort(*srcrow) = (unsigned short *)&Q->top16.data[row * Q->top16.columns]; for (int col = 0; col < Q->top16.columns && col < S.raw_width; col++) destrow[col][2] = srcrow[col]; } } #if 1 if (TRU && Q && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATEAF)) { if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3672) // dpN Quattro normal { x3f_dpq_interpolate_af(32, 8, 2); } else if (imgdata.sizes.raw_width == 5888 && imgdata.sizes.raw_height == 3776) // sd Quattro normal raw { x3f_dpq_interpolate_af_sd(216, 464, imgdata.sizes.raw_width - 1, 3312, 16, 32, 2); } else if (imgdata.sizes.raw_width == 6656 && imgdata.sizes.raw_height == 4480) // sd Quattro H normal raw { x3f_dpq_interpolate_af_sd(232, 592, imgdata.sizes.raw_width - 1, 3920, 16, 32, 2); } else if (imgdata.sizes.raw_width == 3328 && imgdata.sizes.raw_height == 2240) // sd Quattro H half size { x3f_dpq_interpolate_af_sd(116, 296, imgdata.sizes.raw_width - 1, 2200, 8, 16, 1); } else if (imgdata.sizes.raw_width == 5504 && imgdata.sizes.raw_height == 3680) // sd Quattro H APS-C raw { x3f_dpq_interpolate_af_sd(8, 192, imgdata.sizes.raw_width - 1, 3185, 16, 32, 2); } else if (imgdata.sizes.raw_width == 2752 && imgdata.sizes.raw_height == 1840) // sd Quattro H APS-C half size { x3f_dpq_interpolate_af_sd(4, 96, imgdata.sizes.raw_width - 1, 1800, 8, 16, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1836) // dpN Quattro small raw { x3f_dpq_interpolate_af(16, 4, 1); } else if (imgdata.sizes.raw_width == 2944 && imgdata.sizes.raw_height == 1888) // sd Quattro small { x3f_dpq_interpolate_af_sd(108, 232, imgdata.sizes.raw_width - 1, 1656, 8, 16, 1); } } #endif if (TRU && Q && Q->quattro_layout && (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_DP2Q_INTERPOLATERG)) x3f_dpq_interpolate_rg(); } else raise_error = 1; end: if (raise_error) throw LIBRAW_EXCEPTION_IO_CORRUPT; }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_93_0
crossvul-cpp_data_bad_1183_0
// This file is part of The New Aspell // Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. //#include <stdio.h> //#define DEBUG {fprintf(stderr,"File: %s(%i)\n",__FILE__,__LINE__);} #include <string.h> #include <stdlib.h> #include "ndebug.hpp" #include <assert.h> #include "dirs.h" #include "settings.h" #ifdef USE_LOCALE # include <locale.h> #endif #ifdef HAVE_LANGINFO_CODESET # include <langinfo.h> #endif #include "cache.hpp" #include "asc_ctype.hpp" #include "config.hpp" #include "errors.hpp" #include "file_util.hpp" #include "fstream.hpp" #include "getdata.hpp" #include "itemize.hpp" #include "mutable_container.hpp" #include "posib_err.hpp" #include "string_map.hpp" #include "stack_ptr.hpp" #include "char_vector.hpp" #include "convert.hpp" #include "vararray.hpp" #include "string_list.hpp" #include "gettext.h" #include "iostream.hpp" #define DEFAULT_LANG "en_US" // NOTE: All filter options are now stored with he "f-" prefix. However // during lookup, the non prefix version is also recognized. // The "place_holder" field in Entry and the "Vector<int>" parameter of // commit_all are there to deal with the fact than when spacing // options on the command line such as "--key what" it can not be // determined if "what" should be a the value of "key" or if it should // be treated as an independent arg. This is because "key" may // be a filter option. Filter options KeyInfo are not loaded until // after a commit which is not done at the time the options are being // read in from the command line. (If the command line arguments are // read in after the other settings are read in and committed than any // options setting any of the config files will be ignored. Thus the // command line must be parsed and options must be added in an // uncommitted state). So the solution is to assume it is an // independent arg until told otherwise, the position in the arg array // is stored along with the value in the "place_holder" field. When // the config class is finally committed and it is determined that // "what" is really a value for key the stored arg position is pushed // onto the Vector<int> so it can be removed from the arg array. In // the case of a "lset-*" this will happen in multiple config // "Entry"s, so care is taken to only add the arg position once. namespace acommon { const char * const keyinfo_type_name[4] = { N_("string"), N_("integer"), N_("boolean"), N_("list") }; const int Config::num_parms_[9] = {1, 1, 0, 0, 0, 1, 1, 1, 0}; typedef Notifier * NotifierPtr; Config::Config(ParmStr name, const KeyInfo * mainbegin, const KeyInfo * mainend) : name_(name) , first_(0), insert_point_(&first_), others_(0) , committed_(true), attached_(false) , md_info_list_index(-1) , settings_read_in_(false) , load_filter_hook(0) , filter_mode_notifier(0) { keyinfo_begin = mainbegin; keyinfo_end = mainend; extra_begin = 0; extra_end = 0; } Config::~Config() { del(); } Config::Config(const Config & other) { copy(other); } Config & Config::operator= (const Config & other) { del(); copy(other); return *this; } Config * Config::clone() const { return new Config(*this); } void Config::assign(const Config * other) { *this = *(const Config *)(other); } void Config::copy(const Config & other) { assert(other.others_ == 0); others_ = 0; name_ = other.name_; committed_ = other.committed_; attached_ = other.attached_; settings_read_in_ = other.settings_read_in_; keyinfo_begin = other.keyinfo_begin; keyinfo_end = other.keyinfo_end; extra_begin = other.extra_begin; extra_end = other.extra_end; filter_modules = other.filter_modules; #ifdef HAVE_LIBDL filter_modules_ptrs = other.filter_modules_ptrs; for (Vector<Cacheable *>::iterator i = filter_modules_ptrs.begin(); i != filter_modules_ptrs.end(); ++i) (*i)->copy(); #endif md_info_list_index = other.md_info_list_index; insert_point_ = 0; Entry * const * src = &other.first_; Entry * * dest = &first_; while (*src) { *dest = new Entry(**src); if (src == other.insert_point_) insert_point_ = dest; src = &((*src)->next); dest = &((*dest)->next); } if (insert_point_ == 0) insert_point_ = dest; *dest = 0; Vector<Notifier *>::const_iterator i = other.notifier_list.begin(); Vector<Notifier *>::const_iterator end = other.notifier_list.end(); for(; i != end; ++i) { Notifier * tmp = (*i)->clone(this); if (tmp != 0) notifier_list.push_back(tmp); } } void Config::del() { while (first_) { Entry * tmp = first_->next; delete first_; first_ = tmp; } while (others_) { Entry * tmp = others_->next; delete first_; others_ = tmp; } Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); for(; i != end; ++i) { delete (*i); *i = 0; } notifier_list.clear(); #ifdef HAVE_LIBDL filter_modules.clear(); for (Vector<Cacheable *>::iterator i = filter_modules_ptrs.begin(); i != filter_modules_ptrs.end(); ++i) (*i)->release(); filter_modules_ptrs.clear(); #endif } void Config::set_filter_modules(const ConfigModule * modbegin, const ConfigModule * modend) { assert(filter_modules_ptrs.empty()); filter_modules.clear(); filter_modules.assign(modbegin, modend); } void Config::set_extra(const KeyInfo * begin, const KeyInfo * end) { extra_begin = begin; extra_end = end; } // // // // // Notifier methods // NotifierEnumeration * Config::notifiers() const { return new NotifierEnumeration(notifier_list); } bool Config::add_notifier(Notifier * n) { Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); while (i != end && *i != n) ++i; if (i != end) { return false; } else { notifier_list.push_back(n); return true; } } bool Config::remove_notifier(const Notifier * n) { Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); while (i != end && *i != n) ++i; if (i == end) { return false; } else { delete *i; notifier_list.erase(i); return true; } } bool Config::replace_notifier(const Notifier * o, Notifier * n) { Vector<Notifier *>::iterator i = notifier_list.begin(); Vector<Notifier *>::iterator end = notifier_list.end(); while (i != end && *i != o) ++i; if (i == end) { return false; } else { delete *i; *i = n; return true; } } // // retrieve methods // const Config::Entry * Config::lookup(const char * key) const { const Entry * res = 0; const Entry * cur = first_; while (cur) { if (cur->key == key && cur->action != NoOp) res = cur; cur = cur->next; } if (!res || res->action == Reset) return 0; return res; } bool Config::have(ParmStr key) const { PosibErr<const KeyInfo *> pe = keyinfo(key); if (pe.has_err()) {pe.ignore_err(); return false;} return lookup(pe.data->name); } PosibErr<String> Config::retrieve(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type == KeyInfoList) return make_err(key_not_string, ki->name); const Entry * cur = lookup(ki->name); return cur ? cur->value : get_default(ki); } PosibErr<String> Config::retrieve_any(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoList) { const Entry * cur = lookup(ki->name); return cur ? cur->value : get_default(ki); } else { StringList sl; RET_ON_ERR(retrieve_list(key, &sl)); StringListEnumeration els = sl.elements_obj(); const char * s; String val; while ( (s = els.next()) != 0 ) { val += s; val += '\n'; } val.pop_back(); return val; } } PosibErr<bool> Config::retrieve_bool(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoBool) return make_err(key_not_bool, ki->name); const Entry * cur = lookup(ki->name); String value(cur ? cur->value : get_default(ki)); if (value == "false") return false; else return true; } PosibErr<int> Config::retrieve_int(ParmStr key) const { assert(committed_); // otherwise the value may not be an integer // as it has not been verified. RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoInt) return make_err(key_not_int, ki->name); const Entry * cur = lookup(ki->name); String value(cur ? cur->value : get_default(ki)); return atoi(value.str()); } void Config::lookup_list(const KeyInfo * ki, MutableContainer & m, bool include_default) const { const Entry * cur = first_; const Entry * first_to_use = 0; while (cur) { if (cur->key == ki->name && (first_to_use == 0 || cur->action == Reset || cur->action == Set || cur->action == ListClear)) first_to_use = cur; cur = cur->next; } cur = first_to_use; if (include_default && (!cur || !(cur->action == Set || cur->action == ListClear))) { String def = get_default(ki); separate_list(def, m, true); } if (cur && cur->action == Reset) { cur = cur->next; } if (cur && cur->action == Set) { if (!include_default) m.clear(); m.add(cur->value); cur = cur->next; } if (cur && cur->action == ListClear) { if (!include_default) m.clear(); cur = cur->next; } while (cur) { if (cur->key == ki->name) { if (cur->action == ListAdd) m.add(cur->value); else if (cur->action == ListRemove) m.remove(cur->value); } cur = cur->next; } } PosibErr<void> Config::retrieve_list(ParmStr key, MutableContainer * m) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); if (ki->type != KeyInfoList) return make_err(key_not_list, ki->name); lookup_list(ki, *m, true); return no_err; } static const KeyInfo * find(ParmStr key, const KeyInfo * i, const KeyInfo * end) { while (i != end) { if (strcmp(key, i->name) == 0) return i; ++i; } return i; } static const ConfigModule * find(ParmStr key, const ConfigModule * i, const ConfigModule * end) { while (i != end) { if (strcmp(key, i->name) == 0) return i; ++i; } return i; } PosibErr<const KeyInfo *> Config::keyinfo(ParmStr key) const { typedef PosibErr<const KeyInfo *> Ret; { const KeyInfo * i; i = acommon::find(key, keyinfo_begin, keyinfo_end); if (i != keyinfo_end) return Ret(i); i = acommon::find(key, extra_begin, extra_end); if (i != extra_end) return Ret(i); const char * s = strncmp(key, "f-", 2) == 0 ? key + 2 : key.str(); const char * h = strchr(s, '-'); if (h == 0) goto err; String k(s, h - s); const ConfigModule * j = acommon::find(k, filter_modules.pbegin(), filter_modules.pend()); if (j == filter_modules.pend() && load_filter_hook && committed_) { // FIXME: This isn't quite right PosibErrBase pe = load_filter_hook(const_cast<Config *>(this), k); pe.ignore_err(); j = acommon::find(k, filter_modules.pbegin(), filter_modules.pend()); } if (j == filter_modules.pend()) goto err; i = acommon::find(key, j->begin, j->end); if (i != j->end) return Ret(i); if (strncmp(key, "f-", 2) != 0) k = "f-"; else k = ""; k += key; i = acommon::find(k, j->begin, j->end); if (i != j->end) return Ret(i); } err: return Ret().prim_err(unknown_key, key); } static bool proc_locale_str(ParmStr lang, String & final_str) { if (lang == 0) return false; const char * i = lang; if (!(asc_islower(i[0]) && asc_islower(i[1]))) return false; final_str.assign(i, 2); i += 2; if (! (i[0] == '_' || i[0] == '-')) return true; i += 1; if (!(asc_isupper(i[0]) && asc_isupper(i[1]))) return true; final_str += '_'; final_str.append(i, 2); return true; } static void get_lang_env(String & str) { if (proc_locale_str(getenv("LC_MESSAGES"), str)) return; if (proc_locale_str(getenv("LANG"), str)) return; if (proc_locale_str(getenv("LANGUAGE"), str)) return; str = DEFAULT_LANG; } #ifdef USE_LOCALE static void get_lang(String & final_str) { // FIXME: THIS IS NOT THREAD SAFE String locale = setlocale (LC_ALL, NULL); if (locale == "C") setlocale (LC_ALL, ""); const char * lang = setlocale (LC_MESSAGES, NULL); bool res = proc_locale_str(lang, final_str); if (locale == "C") setlocale(LC_MESSAGES, locale.c_str()); if (!res) get_lang_env(final_str); } #else static inline void get_lang(String & str) { get_lang_env(str); } #endif #if defined USE_LOCALE && defined HAVE_LANGINFO_CODESET static inline void get_encoding(const Config & c, String & final_str) { const char * codeset = nl_langinfo(CODESET); if (ascii_encoding(c, codeset)) codeset = "none"; final_str = codeset; } #else static inline void get_encoding(const Config &, String & final_str) { final_str = "none"; } #endif String Config::get_default(const KeyInfo * ki) const { bool in_replace = false; String final_str; String replace; const char * i = ki->def; if (*i == '!') { // special cases ++i; if (strcmp(i, "lang") == 0) { const Entry * entry; if (entry = lookup("actual-lang"), entry) { return entry->value; } else if (have("master")) { final_str = "<unknown>"; } else { get_lang(final_str); } } else if (strcmp(i, "encoding") == 0) { get_encoding(*this, final_str); } else if (strcmp(i, "special") == 0) { // do nothing } else { abort(); // this should not happen } } else for(; *i; ++i) { if (!in_replace) { if (*i == '<') { in_replace = true; } else { final_str += *i; } } else { // in_replace if (*i == '/' || *i == ':' || *i == '|' || *i == '#' || *i == '^') { char sep = *i; String second; ++i; while (*i != '\0' && *i != '>') second += *i++; if (sep == '/') { String s1 = retrieve(replace); String s2 = retrieve(second); final_str += add_possible_dir(s1, s2); } else if (sep == ':') { String s1 = retrieve(replace); final_str += add_possible_dir(s1, second); } else if (sep == '#') { String s1 = retrieve(replace); assert(second.size() == 1); unsigned int s = 0; while (s != s1.size() && s1[s] != second[0]) ++s; final_str.append(s1, s); } else if (sep == '^') { String s1 = retrieve(replace); String s2 = retrieve(second); final_str += figure_out_dir(s1, s2); } else { // sep == '|' assert(replace[0] == '$'); const char * env = getenv(replace.c_str()+1); final_str += env ? env : second; } replace = ""; in_replace = false; } else if (*i == '>') { final_str += retrieve(replace).data; replace = ""; in_replace = false; } else { replace += *i; } } } return final_str; } PosibErr<String> Config::get_default(ParmStr key) const { RET_ON_ERR_SET(keyinfo(key), const KeyInfo *, ki); return get_default(ki); } #define TEST(v,l,a) \ do { \ if (len == l && memcmp(s, v, l) == 0) { \ if (action) *action = a; \ return c + 1; \ } \ } while (false) const char * Config::base_name(const char * s, Action * action) { if (action) *action = Set; const char * c = strchr(s, '-'); if (!c) return s; unsigned len = c - s; TEST("reset", 5, Reset); TEST("enable", 6, Enable); TEST("dont", 4, Disable); TEST("disable", 7, Disable); TEST("lset", 4, ListSet); TEST("rem", 3, ListRemove); TEST("remove", 6, ListRemove); TEST("add", 3, ListAdd); TEST("clear", 5, ListClear); return s; } #undef TEST void separate_list(ParmStr value, AddableContainer & out, bool do_unescape) { unsigned len = value.size(); VARARRAY(char, buf, len + 1); memcpy(buf, value, len + 1); len = strlen(buf); char * s = buf; char * end = buf + len; while (s < end) { if (do_unescape) while (*s == ' ' || *s == '\t') ++s; char * b = s; char * e = s; while (*s != '\0') { if (do_unescape && *s == '\\') { ++s; if (*s == '\0') break; e = s; ++s; } else { if (*s == ':') break; if (!do_unescape || (*s != ' ' && *s != '\t')) e = s; ++s; } } if (s != b) { ++e; *e = '\0'; if (do_unescape) unescape(b); out.add(b); } ++s; } } void combine_list(String & res, const StringList & in) { res.clear(); StringListEnumeration els = in.elements_obj(); const char * s = 0; while ( (s = els.next()) != 0) { for (; *s; ++s) { if (*s == ':') res.append('\\'); res.append(*s); } res.append(':'); } if (res.back() == ':') res.pop_back(); } struct ListAddHelper : public AddableContainer { Config * config; Config::Entry * orig_entry; PosibErr<bool> add(ParmStr val); }; PosibErr<bool> ListAddHelper::add(ParmStr val) { Config::Entry * entry = new Config::Entry(*orig_entry); entry->value = val; entry->action = Config::ListAdd; config->set(entry); return true; } void Config::replace_internal(ParmStr key, ParmStr value) { Entry * entry = new Entry; entry->key = key; entry->value = value; entry->action = Set; entry->next = *insert_point_; *insert_point_ = entry; insert_point_ = &entry->next; } PosibErr<void> Config::replace(ParmStr key, ParmStr value) { Entry * entry = new Entry; entry->key = key; entry->value = value; return set(entry); } PosibErr<void> Config::remove(ParmStr key) { Entry * entry = new Entry; entry->key = key; entry->action = Reset; return set(entry); } PosibErr<void> Config::set(Entry * entry0, bool do_unescape) { StackPtr<Entry> entry(entry0); if (entry->action == NoOp) entry->key = base_name(entry->key.str(), &entry->action); if (num_parms(entry->action) == 0 && !entry->value.empty()) { if (entry->place_holder == -1) { switch (entry->action) { case Reset: return make_err(no_value_reset, entry->key); case Enable: return make_err(no_value_enable, entry->key); case Disable: return make_err(no_value_disable, entry->key); case ListClear: return make_err(no_value_clear, entry->key); default: abort(); // this shouldn't happen } } else { entry->place_holder = -1; } } if (entry->action != ListSet) { switch (entry->action) { case Enable: entry->value = "true"; entry->action = Set; break; case Disable: entry->value = "false"; entry->action = Set; break; default: ; } if (do_unescape) unescape(entry->value.mstr()); entry->next = *insert_point_; *insert_point_ = entry; insert_point_ = &entry->next; entry.release(); if (committed_) RET_ON_ERR(commit(entry0)); // entry0 == entry } else { // action == ListSet Entry * ent = new Entry; ent->key = entry->key; ent->action = ListClear; set(ent); ListAddHelper helper; helper.config = this; helper.orig_entry = entry; separate_list(entry->value.str(), helper, do_unescape); } return no_err; } PosibErr<void> Config::merge(const Config & other) { const Entry * src = other.first_; while (src) { Entry * entry = new Entry(*src); entry->next = *insert_point_; *insert_point_ = entry; insert_point_ = &entry->next; if (committed_) RET_ON_ERR(commit(entry)); src = src->next; } return no_err; } void Config::lang_config_merge(const Config & other, int which, ParmStr data_encoding) { Conv to_utf8; to_utf8.setup(*this, data_encoding, "utf-8", NormTo); const Entry * src = other.first_; Entry * * ip = &first_; while (src) { const KeyInfo * l_ki = other.keyinfo(src->key); if (l_ki->other_data == which) { const KeyInfo * c_ki = keyinfo(src->key); Entry * entry = new Entry(*src); if (c_ki->flags & KEYINFO_UTF8) entry->value = to_utf8(entry->value); entry->next = *ip; *ip = entry; ip = &entry->next; } src = src->next; } } #define NOTIFY_ALL(fun) \ do { \ Vector<Notifier *>::iterator i = notifier_list.begin(); \ Vector<Notifier *>::iterator end = notifier_list.end(); \ while (i != end) { \ RET_ON_ERR((*i)->fun); \ ++i; \ } \ } while (false) PosibErr<int> Config::commit(Entry * entry, Conv * conv) { PosibErr<const KeyInfo *> pe = keyinfo(entry->key); { if (pe.has_err()) goto error; const KeyInfo * ki = pe; entry->key = ki->name; // FIXME: This is the correct thing to do but it causes problems // with changing a filter mode in "pipe" mode and probably // elsewhere. //if (attached_ && !(ki->flags & KEYINFO_MAY_CHANGE)) { // pe = make_err(cant_change_value, entry->key); // goto error; //} int place_holder = entry->place_holder; if (conv && ki->flags & KEYINFO_UTF8) entry->value = (*conv)(entry->value); if (ki->type != KeyInfoList && list_action(entry->action)) { pe = make_err(key_not_list, entry->key); goto error; } assert(ki->def != 0); // if null this key should never have values // directly added to it String value(entry->action == Reset ? get_default(ki) : entry->value); switch (ki->type) { case KeyInfoBool: { bool val; if (value.empty() || entry->place_holder != -1) { // if entry->place_holder != -1 than IGNORE the value no // matter what it is entry->value = "true"; val = true; place_holder = -1; } else if (value == "true") { val = true; } else if (value == "false") { val = false; } else { pe = make_err(bad_value, entry->key, value, /* TRANSLATORS: "true" and "false" are literal * values and should not be translated.*/ _("either \"true\" or \"false\"")); goto error; } NOTIFY_ALL(item_updated(ki, val)); break; } case KeyInfoString: NOTIFY_ALL(item_updated(ki, value)); break; case KeyInfoInt: { int num; if (sscanf(value.str(), "%i", &num) == 1 && num >= 0) { NOTIFY_ALL(item_updated(ki, num)); } else { pe = make_err(bad_value, entry->key, value, _("a positive integer")); goto error; } break; } case KeyInfoList: NOTIFY_ALL(list_updated(ki)); break; } return place_holder; } error: entry->action = NoOp; if (!entry->file.empty()) return pe.with_file(entry->file, entry->line_num); else return (PosibErrBase &)pe; } #undef NOTIFY_ALL ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// class PossibleElementsEmul : public KeyInfoEnumeration { private: bool include_extra; bool include_modules; bool module_changed; const Config * cd; const KeyInfo * i; const ConfigModule * m; public: PossibleElementsEmul(const Config * d, bool ic, bool im) : include_extra(ic), include_modules(im), module_changed(false), cd(d), i(d->keyinfo_begin), m(0) {} KeyInfoEnumeration * clone() const { return new PossibleElementsEmul(*this); } void assign(const KeyInfoEnumeration * other) { *this = *(const PossibleElementsEmul *)(other); } virtual bool active_filter_module_changed(void) { return module_changed; } const char * active_filter_module_name(void){ if (m != 0) return m->name; return ""; } virtual const char * active_filter_module_desc(void) { if (m != 0) return m->desc; return ""; } const KeyInfo * next() { if (i == cd->keyinfo_end) { if (include_extra) i = cd->extra_begin; else i = cd->extra_end; } module_changed = false; if (i == cd->extra_end) { m = cd->filter_modules.pbegin(); if (!include_modules || m == cd->filter_modules.pend()) return 0; else { i = m->begin; module_changed = true; } } if (m == 0){ return i++; } if (m == cd->filter_modules.pend()){ return 0; } while (i == m->end) { ++m; if (m == cd->filter_modules.pend()) return 0; else { i = m->begin; module_changed = true; } } return i++; } bool at_end() const { return (m == cd->filter_modules.pend()); } }; KeyInfoEnumeration * Config::possible_elements(bool include_extra, bool include_modules) const { return new PossibleElementsEmul(this, include_extra, include_modules); } struct ListDefaultDump : public AddableContainer { OStream & out; bool first; const char * first_prefix; unsigned num_blanks; ListDefaultDump(OStream & o); PosibErr<bool> add(ParmStr d); }; ListDefaultDump::ListDefaultDump(OStream & o) : out(o), first(false) { first_prefix = _("# default: "); num_blanks = strlen(first_prefix) - 1; } PosibErr<bool> ListDefaultDump::add(ParmStr d) { if (first) { out.write(first_prefix); } else { out.put('#'); for (unsigned i = 0; i != num_blanks; ++i) out.put(' '); } VARARRAY(char, buf, d.size() * 2 + 1); escape(buf, d); out.printl(buf); first = false; return true; } class ListDump : public MutableContainer { OStream & out; const char * name; public: ListDump(OStream & o, ParmStr n) : out(o), name(n) {} PosibErr<bool> add(ParmStr d); PosibErr<bool> remove(ParmStr d); PosibErr<void> clear(); }; PosibErr<bool> ListDump::add(ParmStr d) { VARARRAY(char, buf, d.size() * 2 + 1); escape(buf, d); out.printf("add-%s %s\n", name, buf); return true; } PosibErr<bool> ListDump::remove(ParmStr d) { VARARRAY(char, buf, d.size() * 2 + 1); escape(buf, d); out.printf("remove-%s %s\n", name, buf); return true; } PosibErr<void> ListDump::clear() { out.printf("clear-%s\n", name); return no_err; } void Config::write_to_stream(OStream & out, bool include_extra) { KeyInfoEnumeration * els = possible_elements(include_extra); const KeyInfo * i; String buf; String obuf; String def; bool have_value; while ((i = els->next()) != 0) { if (i->desc == 0) continue; if (els->active_filter_module_changed()) { out.printf(_("\n" "#######################################################################\n" "#\n" "# Filter: %s\n" "# %s\n" "#\n" "# configured as follows:\n" "\n"), els->active_filter_module_name(), _(els->active_filter_module_desc())); } obuf.clear(); have_value = false; obuf.printf("# %s (%s)\n# %s\n", i->name, _(keyinfo_type_name[i->type]), _(i->desc)); if (i->def != 0) { if (i->type != KeyInfoList) { buf.resize(strlen(i->def) * 2 + 1); escape(buf.data(), i->def); obuf.printf("# default: %s", buf.data()); def = get_default(i); if (def != i->def) { buf.resize(def.size() * 2 + 1); escape(buf.data(), def.str()); obuf.printf(" = %s", buf.data()); } obuf << '\n'; const Entry * entry = lookup(i->name); if (entry) { have_value = true; buf.resize(entry->value.size() * 2 + 1); escape(buf.data(), entry->value.str()); obuf.printf("%s %s\n", i->name, buf.data()); } } else { unsigned s = obuf.size(); ListDump ld(obuf, i->name); lookup_list(i, ld, false); have_value = s != obuf.size(); } } obuf << '\n'; if (!(i->flags & KEYINFO_HIDDEN) || have_value) out.write(obuf); } delete els; } PosibErr<void> Config::read_in(IStream & in, ParmStr id) { String buf; DataPair dp; while (getdata_pair(in, dp, buf)) { to_lower(dp.key); Entry * entry = new Entry; entry->key = dp.key; entry->value = dp.value; entry->file = id; entry->line_num = dp.line_num; RET_ON_ERR(set(entry, true)); } return no_err; } PosibErr<void> Config::read_in_file(ParmStr file) { FStream in; RET_ON_ERR(in.open(file, "r")); return read_in(in, file); } PosibErr<void> Config::read_in_string(ParmStr str, const char * what) { StringIStream in(str); return read_in(in, what); } PosibErr<bool> Config::read_in_settings(const Config * other) { if (settings_read_in_) return false; bool was_committed = committed_; set_committed_state(false); if (other && other->settings_read_in_) { assert(empty()); del(); // to clean up any notifiers and similar stuff copy(*other); } else { if (other) merge(*other); const char * env = getenv("ASPELL_CONF"); if (env != 0) { insert_point_ = &first_; RET_ON_ERR(read_in_string(env, _("ASPELL_CONF env var"))); } { insert_point_ = &first_; PosibErrBase pe = read_in_file(retrieve("per-conf-path")); if (pe.has_err() && !pe.has_err(cant_read_file)) return pe; } { insert_point_ = &first_; PosibErrBase pe = read_in_file(retrieve("conf-path")); if (pe.has_err() && !pe.has_err(cant_read_file)) return pe; } if (was_committed) RET_ON_ERR(commit_all()); settings_read_in_ = true; } return true; } PosibErr<void> Config::commit_all(Vector<int> * phs, const char * codeset) { committed_ = true; others_ = first_; first_ = 0; insert_point_ = &first_; Conv to_utf8; if (codeset) RET_ON_ERR(to_utf8.setup(*this, codeset, "utf-8", NormTo)); while (others_) { *insert_point_ = others_; others_ = others_->next; (*insert_point_)->next = 0; RET_ON_ERR_SET(commit(*insert_point_, codeset ? &to_utf8 : 0), int, place_holder); if (phs && place_holder != -1 && (phs->empty() || phs->back() != place_holder)) phs->push_back(place_holder); insert_point_ = &((*insert_point_)->next); } return no_err; } PosibErr<void> Config::set_committed_state(bool val) { if (val && !committed_) { RET_ON_ERR(commit_all()); } else if (!val && committed_) { assert(empty()); committed_ = false; } return no_err; } #ifdef ENABLE_WIN32_RELOCATABLE # define HOME_DIR "<prefix>" # define PERSONAL "<lang>.pws" # define REPL "<lang>.prepl" #else # define HOME_DIR "<$HOME|./>" # define PERSONAL ".aspell.<lang>.pws" # define REPL ".aspell.<lang>.prepl" #endif static const KeyInfo config_keys[] = { // the description should be under 50 chars {"actual-dict-dir", KeyInfoString, "<dict-dir^master>", 0} , {"actual-lang", KeyInfoString, "", 0} , {"conf", KeyInfoString, "aspell.conf", /* TRANSLATORS: The remaining strings in config.cpp should be kept under 50 characters, begin with a lower case character and not include any trailing punctuation marks. */ N_("main configuration file")} , {"conf-dir", KeyInfoString, CONF_DIR, N_("location of main configuration file")} , {"conf-path", KeyInfoString, "<conf-dir/conf>", 0} , {"data-dir", KeyInfoString, DATA_DIR, N_("location of language data files")} , {"dict-alias", KeyInfoList, "", N_("create dictionary aliases")} , {"dict-dir", KeyInfoString, DICT_DIR, N_("location of the main word list")} , {"encoding", KeyInfoString, "!encoding", N_("encoding to expect data to be in"), KEYINFO_COMMON} , {"filter", KeyInfoList , "url", N_("add or removes a filter"), KEYINFO_MAY_CHANGE} , {"filter-path", KeyInfoList, DICT_DIR, N_("path(s) aspell looks for filters")} //, {"option-path", KeyInfoList, DATA_DIR, // N_("path(s) aspell looks for options descriptions")} , {"mode", KeyInfoString, "url", N_("filter mode"), KEYINFO_COMMON} , {"extra-dicts", KeyInfoList, "", N_("extra dictionaries to use")} , {"home-dir", KeyInfoString, HOME_DIR, N_("location for personal files")} , {"ignore", KeyInfoInt , "1", N_("ignore words <= n chars"), KEYINFO_MAY_CHANGE} , {"ignore-accents" , KeyInfoBool, "false", /* TRANSLATORS: It is OK if this is longer than 50 chars */ N_("ignore accents when checking words -- CURRENTLY IGNORED"), KEYINFO_MAY_CHANGE | KEYINFO_HIDDEN} , {"ignore-case", KeyInfoBool , "false", N_("ignore case when checking words"), KEYINFO_MAY_CHANGE} , {"ignore-repl", KeyInfoBool , "false", N_("ignore commands to store replacement pairs"), KEYINFO_MAY_CHANGE} , {"jargon", KeyInfoString, "", N_("extra information for the word list"), KEYINFO_HIDDEN} , {"keyboard", KeyInfoString, "standard", N_("keyboard definition to use for typo analysis")} , {"lang", KeyInfoString, "<language-tag>", N_("language code"), KEYINFO_COMMON} , {"language-tag", KeyInfoString, "!lang", N_("deprecated, use lang instead"), KEYINFO_HIDDEN} , {"local-data-dir", KeyInfoString, "<actual-dict-dir>", N_("location of local language data files") } , {"master", KeyInfoString, "<lang>", N_("base name of the main dictionary to use"), KEYINFO_COMMON} , {"master-flags", KeyInfoString, "", 0} , {"master-path", KeyInfoString, "<dict-dir/master>", 0} , {"module", KeyInfoString, "default", N_("set module name"), KEYINFO_HIDDEN} , {"module-search-order", KeyInfoList, "", N_("search order for modules"), KEYINFO_HIDDEN} , {"normalize", KeyInfoBool, "true", N_("enable Unicode normalization")} , {"norm-required", KeyInfoBool, "false", N_("Unicode normalization required for current lang")} , {"norm-form", KeyInfoString, "nfc", /* TRANSLATORS: the values after the ':' are literal values and should not be translated. */ N_("Unicode normalization form: none, nfd, nfc, comp")} , {"norm-strict", KeyInfoBool, "false", N_("avoid lossy conversions when normalization")} , {"per-conf", KeyInfoString, ".aspell.conf", N_("personal configuration file")} , {"per-conf-path", KeyInfoString, "<home-dir/per-conf>", 0} , {"personal", KeyInfoString, PERSONAL, N_("personal dictionary file name")} , {"personal-path", KeyInfoString, "<home-dir/personal>", 0} , {"prefix", KeyInfoString, PREFIX, N_("prefix directory")} , {"repl", KeyInfoString, REPL, N_("replacements list file name") } , {"repl-path", KeyInfoString, "<home-dir/repl>", 0} , {"run-together", KeyInfoBool, "false", N_("consider run-together words legal"), KEYINFO_MAY_CHANGE} , {"run-together-limit", KeyInfoInt, "2", N_("maximum number that can be strung together"), KEYINFO_MAY_CHANGE} , {"run-together-min", KeyInfoInt, "3", N_("minimal length of interior words"), KEYINFO_MAY_CHANGE} , {"save-repl", KeyInfoBool , "true", N_("save replacement pairs on save all")} , {"set-prefix", KeyInfoBool, "true", N_("set the prefix based on executable location")} , {"size", KeyInfoString, "+60", N_("size of the word list")} , {"spelling", KeyInfoString, "", N_("no longer used"), KEYINFO_HIDDEN} , {"sug-mode", KeyInfoString, "normal", N_("suggestion mode"), KEYINFO_MAY_CHANGE | KEYINFO_COMMON} , {"sug-typo-analysis", KeyInfoBool, "true", /* TRANSLATORS: "sug-mode" is a literal value and should not be translated. */ N_("use typo analysis, override sug-mode default")} , {"sug-repl-table", KeyInfoBool, "true", N_("use replacement tables, override sug-mode default")} , {"sug-split-char", KeyInfoList, "\\ :-", N_("characters to insert when a word is split"), KEYINFO_UTF8} , {"use-other-dicts", KeyInfoBool, "true", N_("use personal, replacement & session dictionaries")} , {"variety", KeyInfoList, "", N_("extra information for the word list")} , {"word-list-path", KeyInfoList, DATA_DIR, N_("search path for word list information files"), KEYINFO_HIDDEN} , {"warn", KeyInfoBool, "true", N_("enable warnings")} // // These options are generally used when creating dictionaries // and may also be specified in the language data file // , {"affix-char", KeyInfoString, "/", // FIXME: Implement /* TRANSLATORS: It is OK if this is longer than 50 chars */ N_("indicator for affix flags in word lists -- CURRENTLY IGNORED"), KEYINFO_UTF8 | KEYINFO_HIDDEN} , {"affix-compress", KeyInfoBool, "false", N_("use affix compression when creating dictionaries")} , {"clean-affixes", KeyInfoBool, "true", N_("remove invalid affix flags")} , {"clean-words", KeyInfoBool, "false", N_("attempts to clean words so that they are valid")} , {"invisible-soundslike", KeyInfoBool, "false", N_("compute soundslike on demand rather than storing")} , {"partially-expand", KeyInfoBool, "false", N_("partially expand affixes for better suggestions")} , {"skip-invalid-words", KeyInfoBool, "true", N_("skip invalid words")} , {"validate-affixes", KeyInfoBool, "true", N_("check if affix flags are valid")} , {"validate-words", KeyInfoBool, "true", N_("check if words are valid")} // // These options are specific to the "aspell" utility. They are // here so that they can be specified in configuration files. // , {"backup", KeyInfoBool, "true", N_("create a backup file by appending \".bak\"")} , {"byte-offsets", KeyInfoBool, "false", N_("use byte offsets instead of character offsets")} , {"guess", KeyInfoBool, "false", N_("create missing root/affix combinations"), KEYINFO_MAY_CHANGE} , {"keymapping", KeyInfoString, "aspell", N_("keymapping for check mode: \"aspell\" or \"ispell\"")} , {"reverse", KeyInfoBool, "false", N_("reverse the order of the suggest list")} , {"suggest", KeyInfoBool, "true", N_("suggest possible replacements"), KEYINFO_MAY_CHANGE} , {"time" , KeyInfoBool, "false", N_("time load time and suggest time in pipe mode"), KEYINFO_MAY_CHANGE} }; const KeyInfo * config_impl_keys_begin = config_keys; const KeyInfo * config_impl_keys_end = config_keys + sizeof(config_keys)/sizeof(KeyInfo); Config * new_basic_config() { aspell_gettext_init(); return new Config("aspell", config_impl_keys_begin, config_impl_keys_end); } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_1183_0
crossvul-cpp_data_good_1383_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1998-2010 Zend Technologies Ltd. (http://www.zend.com) | +----------------------------------------------------------------------+ | This source file is subject to version 2.00 of the Zend license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.zend.com/license/2_00.txt. | | If you did not receive a copy of the Zend license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@zend.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/base/zend-printf.h" #include "hphp/runtime/base/zend-math.h" #include "hphp/util/lock.h" #include "hphp/util/overflow.h" #include <algorithm> #include <cmath> #ifndef _MSC_VER #include <monetary.h> #endif #include "hphp/util/bstring.h" #include "hphp/runtime/base/exceptions.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/runtime-error.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/builtin-functions.h" #include <folly/portability/String.h> #define PHP_QPRINT_MAXL 75 namespace HPHP { /////////////////////////////////////////////////////////////////////////////// // helpers void string_charmask(const char *sinput, int len, char *mask) { const unsigned char *input = (unsigned char *)sinput; const unsigned char *end; unsigned char c; memset(mask, 0, 256); for (end = input+len; input < end; input++) { c=*input; if ((input+3 < end) && input[1] == '.' && input[2] == '.' && input[3] >= c) { memset(mask+c, 1, input[3] - c + 1); input+=3; } else if ((input+1 < end) && input[0] == '.' && input[1] == '.') { /* Error, try to be as helpful as possible: (a range ending/starting with '.' won't be captured here) */ if (end-len >= input) { /* there was no 'left' char */ throw_invalid_argument ("charlist: Invalid '..'-range, missing left of '..'"); continue; } if (input+2 >= end) { /* there is no 'right' char */ throw_invalid_argument ("charlist: Invalid '..'-range, missing right of '..'"); continue; } if (input[-1] > input[2]) { /* wrong order */ throw_invalid_argument ("charlist: '..'-range needs to be incrementing"); continue; } /* FIXME: better error (a..b..c is the only left possibility?) */ throw_invalid_argument("charlist: Invalid '..'-range"); continue; } else { mask[c]=1; } } } int string_copy(char *dst, const char *src, int siz) { register char *d = dst; register const char *s = src; register size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0 && --n != 0) { do { if ((*d++ = *s++) == 0) break; } while (--n != 0); } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) *d = '\0'; /* NUL-terminate dst */ while (*s++) ; } return(s - src - 1); /* count does not include NUL */ } /////////////////////////////////////////////////////////////////////////////// // comparisons int string_ncmp(const char *s1, const char *s2, int len) { for (int i = 0; i < len; i++) { char c1 = s1[i]; char c2 = s2[i]; if (c1 > c2) return 1; if (c1 < c2) return -1; } return 0; } static int compare_right(char const **a, char const *aend, char const **b, char const *bend) { int bias = 0; /* The longest run of digits wins. That aside, the greatest value wins, but we can't know that it will until we've scanned both numbers to know that they have the same magnitude, so we remember it in BIAS. */ for(;; (*a)++, (*b)++) { if ((*a == aend || !isdigit((int)(unsigned char)**a)) && (*b == bend || !isdigit((int)(unsigned char)**b))) return bias; else if (*a == aend || !isdigit((int)(unsigned char)**a)) return -1; else if (*b == bend || !isdigit((int)(unsigned char)**b)) return +1; else if (**a < **b) { if (!bias) bias = -1; } else if (**a > **b) { if (!bias) bias = +1; } } return 0; } static int compare_left(char const **a, char const *aend, char const **b, char const *bend) { /* Compare two left-aligned numbers: the first to have a different value wins. */ for(;; (*a)++, (*b)++) { if ((*a == aend || !isdigit((int)(unsigned char)**a)) && (*b == bend || !isdigit((int)(unsigned char)**b))) return 0; else if (*a == aend || !isdigit((int)(unsigned char)**a)) return -1; else if (*b == bend || !isdigit((int)(unsigned char)**b)) return +1; else if (**a < **b) return -1; else if (**a > **b) return +1; } return 0; } int string_natural_cmp(char const *a, size_t a_len, char const *b, size_t b_len, int fold_case) { char ca, cb; char const *ap, *bp; char const *aend = a + a_len, *bend = b + b_len; int fractional, result; if (a_len == 0 || b_len == 0) return a_len - b_len; ap = a; bp = b; while (1) { ca = *ap; cb = *bp; /* skip over leading spaces or zeros */ while (isspace((int)(unsigned char)ca)) ca = *++ap; while (isspace((int)(unsigned char)cb)) cb = *++bp; /* process run of digits */ if (isdigit((int)(unsigned char)ca) && isdigit((int)(unsigned char)cb)) { fractional = (ca == '0' || cb == '0'); if (fractional) result = compare_left(&ap, aend, &bp, bend); else result = compare_right(&ap, aend, &bp, bend); if (result != 0) return result; else if (ap == aend && bp == bend) /* End of the strings. Let caller sort them out. */ return 0; else { /* Keep on comparing from the current point. */ ca = *ap; cb = *bp; } } if (fold_case) { ca = toupper((int)(unsigned char)ca); cb = toupper((int)(unsigned char)cb); } if (ca < cb) return -1; else if (ca > cb) return +1; ++ap; ++bp; if (ap >= aend && bp >= bend) /* The strings compare the same. Perhaps the caller will want to call strcmp to break the tie. */ return 0; else if (ap >= aend) return -1; else if (bp >= bend) return 1; } } /////////////////////////////////////////////////////////////////////////////// void string_to_case(String& s, int (*tocase)(int)) { assertx(!s.isNull()); assertx(tocase); auto data = s.mutableData(); auto len = s.size(); for (int i = 0; i < len; i++) { data[i] = tocase(data[i]); } } /////////////////////////////////////////////////////////////////////////////// #define STR_PAD_LEFT 0 #define STR_PAD_RIGHT 1 #define STR_PAD_BOTH 2 String string_pad(const char *input, int len, int pad_length, const char *pad_string, int pad_str_len, int pad_type) { assertx(input); int num_pad_chars = pad_length - len; /* If resulting string turns out to be shorter than input string, we simply copy the input and return. */ if (pad_length < 0 || num_pad_chars < 0) { return String(input, len, CopyString); } /* Setup the padding string values if specified. */ if (pad_str_len == 0) { throw_invalid_argument("pad_string: (empty)"); return String(); } String ret(pad_length, ReserveString); char *result = ret.mutableData(); /* We need to figure out the left/right padding lengths. */ int left_pad, right_pad; switch (pad_type) { case STR_PAD_RIGHT: left_pad = 0; right_pad = num_pad_chars; break; case STR_PAD_LEFT: left_pad = num_pad_chars; right_pad = 0; break; case STR_PAD_BOTH: left_pad = num_pad_chars / 2; right_pad = num_pad_chars - left_pad; break; default: throw_invalid_argument("pad_type: %d", pad_type); return String(); } /* First we pad on the left. */ int result_len = 0; for (int i = 0; i < left_pad; i++) { result[result_len++] = pad_string[i % pad_str_len]; } /* Then we copy the input string. */ memcpy(result + result_len, input, len); result_len += len; /* Finally, we pad on the right. */ for (int i = 0; i < right_pad; i++) { result[result_len++] = pad_string[i % pad_str_len]; } ret.setSize(result_len); return ret; } /////////////////////////////////////////////////////////////////////////////// int string_find(const char *input, int len, char ch, int pos, bool case_sensitive) { assertx(input); if (pos < 0 || pos > len) { return -1; } const void *ptr; if (case_sensitive) { ptr = memchr(input + pos, ch, len - pos); } else { ptr = bstrcasechr(input + pos, ch, len - pos); } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } int string_rfind(const char *input, int len, char ch, int pos, bool case_sensitive) { assertx(input); if (pos < -len || pos > len) { return -1; } const void *ptr; if (case_sensitive) { if (pos >= 0) { ptr = memrchr(input + pos, ch, len - pos); } else { ptr = memrchr(input, ch, len + pos + 1); } } else { if (pos >= 0) { ptr = bstrrcasechr(input + pos, ch, len - pos); } else { ptr = bstrrcasechr(input, ch, len + pos + 1); } } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } int string_find(const char *input, int len, const char *s, int s_len, int pos, bool case_sensitive) { assertx(input); assertx(s); if (!s_len || pos < 0 || pos > len) { return -1; } void *ptr; if (case_sensitive) { ptr = (void*)string_memnstr(input + pos, s, s_len, input + len); } else { ptr = bstrcasestr(input + pos, len - pos, s, s_len); } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } int string_rfind(const char *input, int len, const char *s, int s_len, int pos, bool case_sensitive) { assertx(input); assertx(s); if (!s_len || pos < -len || pos > len) { return -1; } void *ptr; if (case_sensitive) { if (pos >= 0) { ptr = bstrrstr(input + pos, len - pos, s, s_len); } else { ptr = bstrrstr(input, len + std::min(pos + s_len, 0), s, s_len); } } else { if (pos >= 0) { ptr = bstrrcasestr(input + pos, len - pos, s, s_len); } else { ptr = bstrrcasestr(input, len + std::min(pos + s_len, 0), s, s_len); } } if (ptr != nullptr) { return (int)((const char *)ptr - input); } return -1; } const char *string_memnstr(const char *haystack, const char *needle, int needle_len, const char *end) { const char *p = haystack; char ne = needle[needle_len-1]; end -= needle_len; while (p <= end) { if ((p = (char *)memchr(p, *needle, (end-p+1))) && ne == p[needle_len-1]) { if (!memcmp(needle, p, needle_len-1)) { return p; } } if (p == nullptr) { return nullptr; } p++; } return nullptr; } String string_replace(const char *s, int len, int start, int length, const char *replacement, int len_repl) { assertx(s); assertx(replacement); assertx(len >= 0); // if "start" position is negative, count start position from the end // of the string if (start < 0) { start = len + start; if (start < 0) { start = 0; } } if (start > len) { start = len; } // if "length" position is negative, set it to the length // needed to stop that many chars from the end of the string if (length < 0) { length = (len - start) + length; if (length < 0) { length = 0; } } // check if length is too large if (length > len) { length = len; } // check if the length is too large adjusting for non-zero start // Write this way instead of start + length > len to avoid overflow if (length > len - start) { length = len - start; } String retString(len + len_repl - length, ReserveString); char *ret = retString.mutableData(); int ret_len = 0; if (start) { memcpy(ret, s, start); ret_len += start; } if (len_repl) { memcpy(ret + ret_len, replacement, len_repl); ret_len += len_repl; } len -= (start + length); if (len) { memcpy(ret + ret_len, s + start + length, len); ret_len += len; } retString.setSize(ret_len); return retString; } String string_replace(const char *input, int len, const char *search, int len_search, const char *replacement, int len_replace, int &count, bool case_sensitive) { assertx(input); assertx(search && len_search); assertx(len >= 0); assertx(len_search >= 0); assertx(len_replace >= 0); if (len == 0) { return String(); } req::vector<int> founds; founds.reserve(16); if (len_search == 1) { for (int pos = string_find(input, len, *search, 0, case_sensitive); pos >= 0; pos = string_find(input, len, *search, pos + len_search, case_sensitive)) { founds.push_back(pos); } } else { for (int pos = string_find(input, len, search, len_search, 0, case_sensitive); pos >= 0; pos = string_find(input, len, search, len_search, pos + len_search, case_sensitive)) { founds.push_back(pos); } } count = founds.size(); if (count == 0) { return String(); // not found } int reserve; // Make sure the new size of the string wouldn't overflow int32_t. Don't // bother if the replacement wouldn't make the string longer. if (len_replace > len_search) { auto raise = [&] { raise_error("String too large"); }; if (mul_overflow(len_replace - len_search, count)) { raise(); } int diff = (len_replace - len_search) * count; if (add_overflow(len, diff)) { raise(); } reserve = len + diff; } else { reserve = len + (len_replace - len_search) * count; } String retString(reserve, ReserveString); char *ret = retString.mutableData(); char *p = ret; int pos = 0; // last position in input that hasn't been copied over yet int n; for (unsigned int i = 0; i < founds.size(); i++) { n = founds[i]; if (n > pos) { n -= pos; memcpy(p, input, n); p += n; input += n; pos += n; } if (len_replace) { memcpy(p, replacement, len_replace); p += len_replace; } input += len_search; pos += len_search; } n = len; if (n > pos) { n -= pos; memcpy(p, input, n); p += n; } retString.setSize(p - ret); return retString; } /////////////////////////////////////////////////////////////////////////////// String string_chunk_split(const char *src, int srclen, const char *end, int endlen, int chunklen) { int chunks = srclen / chunklen; // complete chunks! int restlen = srclen - chunks * chunklen; /* srclen % chunklen */ String ret( safe_address( chunks + 1, endlen, srclen ), ReserveString ); char *dest = ret.mutableData(); const char *p; char *q; const char *pMax = src + srclen - chunklen + 1; for (p = src, q = dest; p < pMax; ) { memcpy(q, p, chunklen); q += chunklen; memcpy(q, end, endlen); q += endlen; p += chunklen; } if (restlen) { memcpy(q, p, restlen); q += restlen; memcpy(q, end, endlen); q += endlen; } ret.setSize(q - dest); return ret; } /////////////////////////////////////////////////////////////////////////////// #define PHP_TAG_BUF_SIZE 1023 /** * Check if tag is in a set of tags * * states: * * 0 start tag * 1 first non-whitespace char seen */ static int string_tag_find(const char *tag, int len, const char *set) { char c, *n; const char *t; int state=0, done=0; char *norm; if (len <= 0) { return 0; } norm = (char *)req::malloc_noptrs(len+1); SCOPE_EXIT { req::free(norm); }; n = norm; t = tag; c = tolower(*t); /* normalize the tag removing leading and trailing whitespace and turn any <a whatever...> into just <a> and any </tag> into <tag> */ while (!done) { switch (c) { case '<': *(n++) = c; break; case '>': done =1; break; default: if (!isspace((int)c)) { if (state == 0) { state=1; } if (c != '/') { *(n++) = c; } } else { if (state == 1) done=1; } break; } c = tolower(*(++t)); } *(n++) = '>'; *n = '\0'; if (strstr(set, norm)) { done=1; } else { done=0; } return done; } /** * A simple little state-machine to strip out html and php tags * * State 0 is the output state, State 1 means we are inside a * normal html tag and state 2 means we are inside a php tag. * * The state variable is passed in to allow a function like fgetss * to maintain state across calls to the function. * * lc holds the last significant character read and br is a bracket * counter. * * When an allow string is passed in we keep track of the string * in state 1 and when the tag is closed check it against the * allow string to see if we should allow it. * swm: Added ability to strip <?xml tags without assuming it PHP * code. */ String string_strip_tags(const char *s, const int len, const char *allow, const int allow_len, bool allow_tag_spaces) { const char *abuf, *p; char *rbuf, *tbuf, *tp, *rp, c, lc; int br, i=0, depth=0, in_q = 0; int state = 0, pos; assertx(s); assertx(allow); String retString(s, len, CopyString); rbuf = retString.mutableData(); String allowString; c = *s; lc = '\0'; p = s; rp = rbuf; br = 0; if (allow_len) { assertx(allow); allowString = String(allow_len, ReserveString); char *atmp = allowString.mutableData(); for (const char *tmp = allow; *tmp; tmp++, atmp++) { *atmp = tolower((int)*(const unsigned char *)tmp); } allowString.setSize(allow_len); abuf = allowString.data(); tbuf = (char *)req::malloc_noptrs(PHP_TAG_BUF_SIZE+1); tp = tbuf; } else { abuf = nullptr; tbuf = tp = nullptr; } auto move = [&pos, &tbuf, &tp]() { if (tp - tbuf >= PHP_TAG_BUF_SIZE) { pos = tp - tbuf; tbuf = (char*)req::realloc_noptrs(tbuf, (tp - tbuf) + PHP_TAG_BUF_SIZE + 1); tp = tbuf + pos; } }; while (i < len) { switch (c) { case '\0': break; case '<': if (isspace(*(p + 1)) && !allow_tag_spaces) { goto reg_char; } if (state == 0) { lc = '<'; state = 1; if (allow_len) { move(); *(tp++) = '<'; } } else if (state == 1) { depth++; } break; case '(': if (state == 2) { if (lc != '"' && lc != '\'') { lc = '('; br++; } } else if (allow_len && state == 1) { move(); *(tp++) = c; } else if (state == 0) { *(rp++) = c; } break; case ')': if (state == 2) { if (lc != '"' && lc != '\'') { lc = ')'; br--; } } else if (allow_len && state == 1) { move(); *(tp++) = c; } else if (state == 0) { *(rp++) = c; } break; case '>': if (depth) { depth--; break; } if (in_q) { break; } switch (state) { case 1: /* HTML/XML */ lc = '>'; in_q = state = 0; if (allow_len) { move(); *(tp++) = '>'; *tp='\0'; if (string_tag_find(tbuf, tp-tbuf, abuf)) { memcpy(rp, tbuf, tp-tbuf); rp += tp-tbuf; } tp = tbuf; } break; case 2: /* PHP */ if (!br && lc != '\"' && *(p-1) == '?') { in_q = state = 0; tp = tbuf; } break; case 3: in_q = state = 0; tp = tbuf; break; case 4: /* JavaScript/CSS/etc... */ if (p >= s + 2 && *(p-1) == '-' && *(p-2) == '-') { in_q = state = 0; tp = tbuf; } break; default: *(rp++) = c; break; } break; case '"': case '\'': if (state == 4) { /* Inside <!-- comment --> */ break; } else if (state == 2 && *(p-1) != '\\') { if (lc == c) { lc = '\0'; } else if (lc != '\\') { lc = c; } } else if (state == 0) { *(rp++) = c; } else if (allow_len && state == 1) { move(); *(tp++) = c; } if (state && p != s && *(p-1) != '\\' && (!in_q || *p == in_q)) { if (in_q) { in_q = 0; } else { in_q = *p; } } break; case '!': /* JavaScript & Other HTML scripting languages */ if (state == 1 && *(p-1) == '<') { state = 3; lc = c; } else { if (state == 0) { *(rp++) = c; } else if (allow_len && state == 1) { move(); *(tp++) = c; } } break; case '-': if (state == 3 && p >= s + 2 && *(p-1) == '-' && *(p-2) == '!') { state = 4; } else { goto reg_char; } break; case '?': if (state == 1 && *(p-1) == '<') { br=0; state=2; break; } case 'E': case 'e': /* !DOCTYPE exception */ if (state==3 && p > s+6 && tolower(*(p-1)) == 'p' && tolower(*(p-2)) == 'y' && tolower(*(p-3)) == 't' && tolower(*(p-4)) == 'c' && tolower(*(p-5)) == 'o' && tolower(*(p-6)) == 'd') { state = 1; break; } /* fall-through */ case 'l': /* swm: If we encounter '<?xml' then we shouldn't be in * state == 2 (PHP). Switch back to HTML. */ if (state == 2 && p > s+2 && *(p-1) == 'm' && *(p-2) == 'x') { state = 1; break; } /* fall-through */ default: reg_char: if (state == 0) { *(rp++) = c; } else if (allow_len && state == 1) { move(); *(tp++) = c; } break; } c = *(++p); i++; } if (rp < rbuf + len) { *rp = '\0'; } if (allow_len) { req::free(tbuf); } retString.setSize(rp - rbuf); return retString; } /////////////////////////////////////////////////////////////////////////////// static char string_hex2int(int c) { if (isdigit(c)) { return c - '0'; } if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } return -1; } String string_quoted_printable_encode(const char *input, int len) { size_t length = len; const unsigned char *str = (unsigned char*)input; unsigned long lp = 0; unsigned char c; char *d, *buffer; char *hex = "0123456789ABCDEF"; String ret( safe_address( 3, length + ((safe_address(3, length, 0)/(PHP_QPRINT_MAXL-9)) + 1), 1), ReserveString ); d = buffer = ret.mutableData(); while (length--) { if (((c = *str++) == '\015') && (*str == '\012') && length > 0) { *d++ = '\015'; *d++ = *str++; length--; lp = 0; } else { if (iscntrl (c) || (c == 0x7f) || (c & 0x80) || (c == '=') || ((c == ' ') && (*str == '\015'))) { if ((((lp+= 3) > PHP_QPRINT_MAXL) && (c <= 0x7f)) || ((c > 0x7f) && (c <= 0xdf) && ((lp + 3) > PHP_QPRINT_MAXL)) || ((c > 0xdf) && (c <= 0xef) && ((lp + 6) > PHP_QPRINT_MAXL)) || ((c > 0xef) && (c <= 0xf4) && ((lp + 9) > PHP_QPRINT_MAXL))) { *d++ = '='; *d++ = '\015'; *d++ = '\012'; lp = 3; } *d++ = '='; *d++ = hex[c >> 4]; *d++ = hex[c & 0xf]; } else { if ((++lp) > PHP_QPRINT_MAXL) { *d++ = '='; *d++ = '\015'; *d++ = '\012'; lp = 1; } *d++ = c; } } } len = d - buffer; ret.setSize(len); return ret; } String string_quoted_printable_decode(const char *input, int len, bool is_q) { assertx(input); if (len == 0) { return String(); } int i = 0, j = 0, k; const char *str_in = input; String ret(len, ReserveString); char *str_out = ret.mutableData(); while (i < len && str_in[i]) { switch (str_in[i]) { case '=': if (i + 2 < len && str_in[i + 1] && str_in[i + 2] && isxdigit((int) str_in[i + 1]) && isxdigit((int) str_in[i + 2])) { str_out[j++] = (string_hex2int((int) str_in[i + 1]) << 4) + string_hex2int((int) str_in[i + 2]); i += 3; } else /* check for soft line break according to RFC 2045*/ { k = 1; while (str_in[i + k] && ((str_in[i + k] == 32) || (str_in[i + k] == 9))) { /* Possibly, skip spaces/tabs at the end of line */ k++; } if (!str_in[i + k]) { /* End of line reached */ i += k; } else if ((str_in[i + k] == 13) && (str_in[i + k + 1] == 10)) { /* CRLF */ i += k + 2; } else if ((str_in[i + k] == 13) || (str_in[i + k] == 10)) { /* CR or LF */ i += k + 1; } else { str_out[j++] = str_in[i++]; } } break; case '_': if (is_q) { str_out[j++] = ' '; i++; } else { str_out[j++] = str_in[i++]; } break; default: str_out[j++] = str_in[i++]; } } ret.setSize(j); return ret; } Variant string_base_to_numeric(const char *s, int len, int base) { int64_t num = 0; double fnum = 0; int mode = 0; int64_t cutoff; int cutlim; assertx(string_validate_base(base)); cutoff = LONG_MAX / base; cutlim = LONG_MAX % base; for (int i = len; i > 0; i--) { char c = *s++; /* might not work for EBCDIC */ if (c >= '0' && c <= '9') c -= '0'; else if (c >= 'A' && c <= 'Z') c -= 'A' - 10; else if (c >= 'a' && c <= 'z') c -= 'a' - 10; else continue; if (c >= base) continue; switch (mode) { case 0: /* Integer */ if (num < cutoff || (num == cutoff && c <= cutlim)) { num = num * base + c; break; } else { fnum = num; mode = 1; } /* fall-through */ case 1: /* Float */ fnum = fnum * base + c; } } if (mode == 1) { return fnum; } return num; } String string_long_to_base(unsigned long value, int base) { static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; char buf[(sizeof(unsigned long) << 3) + 1]; char *ptr, *end; assertx(string_validate_base(base)); end = ptr = buf + sizeof(buf) - 1; do { *--ptr = digits[value % base]; value /= base; } while (ptr > buf && value); return String(ptr, end - ptr, CopyString); } String string_numeric_to_base(const Variant& value, int base) { static char digits[] = "0123456789abcdefghijklmnopqrstuvwxyz"; assertx(string_validate_base(base)); if ((!value.isInteger() && !value.isDouble())) { return empty_string(); } if (value.isDouble()) { double fvalue = floor(value.toDouble()); /* floor it just in case */ char *ptr, *end; char buf[(sizeof(double) << 3) + 1]; /* Don't try to convert +/- infinity */ if (fvalue == HUGE_VAL || fvalue == -HUGE_VAL) { raise_warning("Number too large"); return empty_string(); } end = ptr = buf + sizeof(buf) - 1; do { *--ptr = digits[(int) fmod(fvalue, base)]; fvalue /= base; } while (ptr > buf && fabs(fvalue) >= 1); return String(ptr, end - ptr, CopyString); } return string_long_to_base(value.toInt64(), base); } /////////////////////////////////////////////////////////////////////////////// // uuencode #define PHP_UU_ENC(c) \ ((c) ? ((c) & 077) + ' ' : '`') #define PHP_UU_ENC_C2(c) \ PHP_UU_ENC(((*(c) * 16) & 060) | ((*((c) + 1) >> 4) & 017)) #define PHP_UU_ENC_C3(c) \ PHP_UU_ENC(((*(c + 1) * 4) & 074) | ((*((c) + 2) >> 6) & 03)) #define PHP_UU_DEC(c) \ (((c) - ' ') & 077) String string_uuencode(const char *src, int src_len) { assertx(src); assertx(src_len); int len = 45; char *p; const char *s, *e, *ee; char *dest; /* encoded length is ~ 38% greater than the original */ String ret((int)ceil(src_len * 1.38) + 45, ReserveString); p = dest = ret.mutableData(); s = src; e = src + src_len; while ((s + 3) < e) { ee = s + len; if (ee > e) { ee = e; len = ee - s; if (len % 3) { ee = s + (int) (floor(len / 3) * 3); } } *p++ = PHP_UU_ENC(len); while (s < ee) { *p++ = PHP_UU_ENC(*s >> 2); *p++ = PHP_UU_ENC_C2(s); *p++ = PHP_UU_ENC_C3(s); *p++ = PHP_UU_ENC(*(s + 2) & 077); s += 3; } if (len == 45) { *p++ = '\n'; } } if (s < e) { if (len == 45) { *p++ = PHP_UU_ENC(e - s); len = 0; } *p++ = PHP_UU_ENC(*s >> 2); *p++ = PHP_UU_ENC_C2(s); *p++ = ((e - s) > 1) ? PHP_UU_ENC_C3(s) : PHP_UU_ENC('\0'); *p++ = ((e - s) > 2) ? PHP_UU_ENC(*(s + 2) & 077) : PHP_UU_ENC('\0'); } if (len < 45) { *p++ = '\n'; } *p++ = PHP_UU_ENC('\0'); *p++ = '\n'; *p = '\0'; ret.setSize(p - dest); return ret; } String string_uudecode(const char *src, int src_len) { int total_len = 0; int len; const char *s, *e, *ee; char *p, *dest; String ret(ceil(src_len * 0.75), ReserveString); p = dest = ret.mutableData(); s = src; e = src + src_len; while (s < e) { if ((len = PHP_UU_DEC(*s++)) <= 0) { break; } /* sanity check */ if (len > src_len) { goto err; } total_len += len; ee = s + (len == 45 ? 60 : (int) floor(len * 1.33)); /* sanity check */ if (ee > e) { goto err; } while (s < ee) { if (s + 4 > e) goto err; *p++ = PHP_UU_DEC(*s) << 2 | PHP_UU_DEC(*(s + 1)) >> 4; *p++ = PHP_UU_DEC(*(s + 1)) << 4 | PHP_UU_DEC(*(s + 2)) >> 2; *p++ = PHP_UU_DEC(*(s + 2)) << 6 | PHP_UU_DEC(*(s + 3)); s += 4; } if (len < 45) { break; } /* skip \n */ s++; } if ((len = total_len > (p - dest))) { *p++ = PHP_UU_DEC(*s) << 2 | PHP_UU_DEC(*(s + 1)) >> 4; if (len > 1) { *p++ = PHP_UU_DEC(*(s + 1)) << 4 | PHP_UU_DEC(*(s + 2)) >> 2; if (len > 2) { *p++ = PHP_UU_DEC(*(s + 2)) << 6 | PHP_UU_DEC(*(s + 3)); } } } ret.setSize(total_len); return ret; err: return String(); } /////////////////////////////////////////////////////////////////////////////// // base64 namespace { const char base64_table[] = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', '\0' }; const char base64_pad = '='; const short base64_reverse_table[256] = { -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -1, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -1, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 62, -2, -2, -2, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -2, -2, -2, -2, -2, -2, -2, 0, 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, -2, -2, -2, -2, -2, -2, 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, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2 }; folly::Optional<int> maxEncodedSize(int length) { if ((length + 2) < 0 || ((length + 2) / 3) >= (1 << (sizeof(int) * 8 - 2))) { return folly::none; } return ((length + 2) / 3) * 4; } // outstr must be at least maxEncodedSize(length) bytes size_t php_base64_encode(const unsigned char *str, int length, unsigned char* outstr) { const unsigned char *current = str; unsigned char *p = outstr; while (length > 2) { /* keep going until we have less than 24 bits */ *p++ = base64_table[current[0] >> 2]; *p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)]; *p++ = base64_table[((current[1] & 0x0f) << 2) + (current[2] >> 6)]; *p++ = base64_table[current[2] & 0x3f]; current += 3; length -= 3; /* we just handle 3 octets of data */ } /* now deal with the tail end of things */ if (length != 0) { *p++ = base64_table[current[0] >> 2]; if (length > 1) { *p++ = base64_table[((current[0] & 0x03) << 4) + (current[1] >> 4)]; *p++ = base64_table[(current[1] & 0x0f) << 2]; *p++ = base64_pad; } else { *p++ = base64_table[(current[0] & 0x03) << 4]; *p++ = base64_pad; *p++ = base64_pad; } } return p - outstr; } // outstr must be at least length bytes ssize_t php_base64_decode(const char *str, int length, bool strict, unsigned char* outstr) { const unsigned char *current = (unsigned char*)str; int ch, i = 0, j = 0, k; /* this sucks for threaded environments */ unsigned char* result = outstr; /* run through the whole string, converting as we go */ while ((ch = *current++) != '\0' && length-- > 0) { if (ch == base64_pad) { if (*current != '=' && ((i % 4) == 1 || (strict && length > 0))) { if ((i % 4) != 1) { while (isspace(*(++current))) { continue; } if (*current == '\0') { continue; } } return -1; } continue; } ch = base64_reverse_table[ch]; if ((!strict && ch < 0) || ch == -1) { /* a space or some other separator character, we simply skip over */ continue; } else if (ch == -2) { return -1; } switch(i % 4) { case 0: result[j] = ch << 2; break; case 1: result[j++] |= ch >> 4; result[j] = (ch & 0x0f) << 4; break; case 2: result[j++] |= ch >>2; result[j] = (ch & 0x03) << 6; break; case 3: result[j++] |= ch; break; } i++; } k = j; /* mop things up if we ended on a boundary */ if (ch == base64_pad) { switch(i % 4) { case 1: return -1; case 2: k++; case 3: result[k] = 0; } } return j; } } String string_base64_encode(const char* input, int len) { if (auto const wantedSize = maxEncodedSize(len)) { String ret(*wantedSize, ReserveString); auto actualSize = php_base64_encode((unsigned char*)input, len, (unsigned char*)ret.mutableData()); ret.setSize(actualSize); return ret; } return String(); } String string_base64_decode(const char* input, int len, bool strict) { String ret(len, ReserveString); auto actualSize = php_base64_decode(input, len, strict, (unsigned char*)ret.mutableData()); if (actualSize < 0) return String(); ret.setSize(actualSize); return ret; } std::string base64_encode(const char* input, int len) { if (auto const wantedSize = maxEncodedSize(len)) { std::string ret; ret.resize(*wantedSize); auto actualSize = php_base64_encode((unsigned char*)input, len, (unsigned char*)ret.data()); ret.resize(actualSize); return ret; } return std::string(); } std::string base64_decode(const char* input, int len, bool strict) { if (!len) return std::string(); std::string ret; ret.resize(len); auto actualSize = php_base64_decode(input, len, strict, (unsigned char*)ret.data()); if (!actualSize) return std::string(); ret.resize(actualSize); return ret; } /////////////////////////////////////////////////////////////////////////////// String string_escape_shell_arg(const char *str) { int x, y, l; char *cmd; y = 0; l = strlen(str); String ret(safe_address(l, 4, 3), ReserveString); /* worst case */ cmd = ret.mutableData(); #ifdef _MSC_VER cmd[y++] = '"'; #else cmd[y++] = '\''; #endif for (x = 0; x < l; x++) { switch (str[x]) { #ifdef _MSC_VER case '"': case '%': case '!': cmd[y++] = ' '; break; #else case '\'': cmd[y++] = '\''; cmd[y++] = '\\'; cmd[y++] = '\''; #endif /* fall-through */ default: cmd[y++] = str[x]; } } #ifdef _MSC_VER if (y > 0 && '\\' == cmd[y - 1]) { int k = 0, n = y - 1; for (; n >= 0 && '\\' == cmd[n]; n--, k++); if (k % 2) { cmd[y++] = '\\'; } } cmd[y++] = '"'; #else cmd[y++] = '\''; #endif ret.setSize(y); return ret; } String string_escape_shell_cmd(const char *str) { register int x, y, l; char *cmd; char *p = nullptr; l = strlen(str); String ret(safe_address(l, 2, 1), ReserveString); cmd = ret.mutableData(); for (x = 0, y = 0; x < l; x++) { switch (str[x]) { #ifndef _MSC_VER case '"': case '\'': if (!p && (p = (char *)memchr(str + x + 1, str[x], l - x - 1))) { /* noop */ } else if (p && *p == str[x]) { p = nullptr; } else { cmd[y++] = '\\'; } cmd[y++] = str[x]; break; #else /* % is Windows specific for environmental variables, ^%PATH% will output PATH while ^%PATH^% will not. escapeshellcmd->val will escape all % and !. */ case '%': case '!': case '"': case '\'': #endif case '#': /* This is character-set independent */ case '&': case ';': case '`': case '|': case '*': case '?': case '~': case '<': case '>': case '^': case '(': case ')': case '[': case ']': case '{': case '}': case '$': case '\\': case '\x0A': /* excluding these two */ case '\xFF': #ifdef _MSC_VER cmd[y++] = '^'; #else cmd[y++] = '\\'; #endif /* fall-through */ default: cmd[y++] = str[x]; } } ret.setSize(y); return ret; } /////////////////////////////////////////////////////////////////////////////// static void string_similar_str(const char *txt1, int len1, const char *txt2, int len2, int *pos1, int *pos2, int *max) { const char *p, *q; const char *end1 = txt1 + len1; const char *end2 = txt2 + len2; int l; *max = 0; for (p = txt1; p < end1; p++) { for (q = txt2; q < end2; q++) { for (l = 0; (p + l < end1) && (q + l < end2) && (p[l] == q[l]); l++); if (l > *max) { *max = l; *pos1 = p - txt1; *pos2 = q - txt2; } } } } static int string_similar_char(const char *txt1, int len1, const char *txt2, int len2) { int sum; int pos1 = 0, pos2 = 0, max; string_similar_str(txt1, len1, txt2, len2, &pos1, &pos2, &max); if ((sum = max)) { if (pos1 && pos2) { sum += string_similar_char(txt1, pos1, txt2, pos2); } if ((pos1 + max < len1) && (pos2 + max < len2)) { sum += string_similar_char(txt1 + pos1 + max, len1 - pos1 - max, txt2 + pos2 + max, len2 - pos2 - max); } } return sum; } int string_similar_text(const char *t1, int len1, const char *t2, int len2, float *percent) { if (len1 == 0 && len2 == 0) { if (percent) *percent = 0.0; return 0; } int sim = string_similar_char(t1, len1, t2, len2); if (percent) *percent = sim * 200.0 / (len1 + len2); return sim; } /////////////////////////////////////////////////////////////////////////////// #define LEVENSHTEIN_MAX_LENTH 255 // reference implementation, only optimized for memory usage, not speed int string_levenshtein(const char *s1, int l1, const char *s2, int l2, int cost_ins, int cost_rep, int cost_del ) { int *p1, *p2, *tmp; int i1, i2, c0, c1, c2; if (l1==0) return l2*cost_ins; if (l2==0) return l1*cost_del; if ((l1>LEVENSHTEIN_MAX_LENTH)||(l2>LEVENSHTEIN_MAX_LENTH)) { raise_warning("levenshtein(): Argument string(s) too long"); return -1; } p1 = (int*)req::malloc_noptrs((l2+1) * sizeof(int)); SCOPE_EXIT { req::free(p1); }; p2 = (int*)req::malloc_noptrs((l2+1) * sizeof(int)); SCOPE_EXIT { req::free(p2); }; for(i2=0;i2<=l2;i2++) { p1[i2] = i2*cost_ins; } for(i1=0;i1<l1;i1++) { p2[0]=p1[0]+cost_del; for(i2=0;i2<l2;i2++) { c0=p1[i2]+((s1[i1]==s2[i2])?0:cost_rep); c1=p1[i2+1]+cost_del; if (c1<c0) c0=c1; c2=p2[i2]+cost_ins; if (c2<c0) c0=c2; p2[i2+1]=c0; } tmp=p1; p1=p2; p2=tmp; } c0=p1[l2]; return c0; } /////////////////////////////////////////////////////////////////////////////// String string_money_format(const char *format, double value) { bool check = false; const char *p = format; while ((p = strchr(p, '%'))) { if (*(p + 1) == '%') { p += 2; } else if (!check) { check = true; p++; } else { throw_invalid_argument ("format: Only a single %%i or %%n token can be used"); return String(); } } int format_len = strlen(format); int str_len = safe_address(format_len, 1, 1024); String ret(str_len, ReserveString); char *str = ret.mutableData(); if ((str_len = strfmon(str, str_len, format, value)) < 0) { return String(); } ret.setSize(str_len); return ret; } /////////////////////////////////////////////////////////////////////////////// String string_number_format(double d, int dec, const String& dec_point, const String& thousand_sep) { char *tmpbuf = nullptr, *resbuf; char *s, *t; /* source, target */ char *dp; int integral; int tmplen, reslen=0; int count=0; int is_negative=0; if (d < 0) { is_negative = 1; d = -d; } if (dec < 0) dec = 0; d = php_math_round(d, dec); // departure from PHP: we got rid of dependencies on spprintf() here. String tmpstr(63, ReserveString); tmpbuf = tmpstr.mutableData(); tmplen = snprintf(tmpbuf, 64, "%.*F", dec, d); if (tmplen < 0) return empty_string(); if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) { tmpstr.setSize(tmplen); return tmpstr; } if (tmplen >= 64) { // Uncommon, asked for more than 64 chars worth of precision tmpstr = String(tmplen, ReserveString); tmpbuf = tmpstr.mutableData(); tmplen = snprintf(tmpbuf, tmplen + 1, "%.*F", dec, d); if (tmplen < 0) return empty_string(); if (tmpbuf == nullptr || !isdigit((int)tmpbuf[0])) { tmpstr.setSize(tmplen); return tmpstr; } } /* find decimal point, if expected */ if (dec) { dp = strpbrk(tmpbuf, ".,"); } else { dp = nullptr; } /* calculate the length of the return buffer */ if (dp) { integral = dp - tmpbuf; } else { /* no decimal point was found */ integral = tmplen; } /* allow for thousand separators */ if (!thousand_sep.empty()) { if (integral + thousand_sep.size() * ((integral-1) / 3) < integral) { /* overflow */ raise_error("String overflow"); } integral += ((integral-1) / 3) * thousand_sep.size(); } reslen = integral; if (dec) { reslen += dec; if (!dec_point.empty()) { if (reslen + dec_point.size() < dec_point.size()) { /* overflow */ raise_error("String overflow"); } reslen += dec_point.size(); } } /* add a byte for minus sign */ if (is_negative) { reslen++; } String resstr(reslen, ReserveString); resbuf = resstr.mutableData(); s = tmpbuf+tmplen-1; t = resbuf+reslen-1; /* copy the decimal places. * Take care, as the sprintf implementation may return less places than * we requested due to internal buffer limitations */ if (dec) { int declen = dp ? s - dp : 0; int topad = dec > declen ? dec - declen : 0; /* pad with '0's */ while (topad--) { *t-- = '0'; } if (dp) { s -= declen + 1; /* +1 to skip the point */ t -= declen; /* now copy the chars after the point */ memcpy(t + 1, dp + 1, declen); } /* add decimal point */ if (!dec_point.empty()) { memcpy(t + (1 - dec_point.size()), dec_point.data(), dec_point.size()); t -= dec_point.size(); } } /* copy the numbers before the decimal point, adding thousand * separator every three digits */ while(s >= tmpbuf) { *t-- = *s--; if (thousand_sep && (++count%3)==0 && s>=tmpbuf) { memcpy(t + (1 - thousand_sep.size()), thousand_sep.data(), thousand_sep.size()); t -= thousand_sep.size(); } } /* and a minus sign, if needed */ if (is_negative) { *t-- = '-'; } resstr.setSize(reslen); return resstr; } /////////////////////////////////////////////////////////////////////////////// // soundex /* Simple soundex algorithm as described by Knuth in TAOCP, vol 3 */ String string_soundex(const String& str) { assertx(!str.empty()); int _small, code, last; String retString(4, ReserveString); char* soundex = retString.mutableData(); static char soundex_table[26] = { 0, /* A */ '1', /* B */ '2', /* C */ '3', /* D */ 0, /* E */ '1', /* F */ '2', /* G */ 0, /* H */ 0, /* I */ '2', /* J */ '2', /* K */ '4', /* L */ '5', /* M */ '5', /* N */ 0, /* O */ '1', /* P */ '2', /* Q */ '6', /* R */ '2', /* S */ '3', /* T */ 0, /* U */ '1', /* V */ 0, /* W */ '2', /* X */ 0, /* Y */ '2' /* Z */ }; /* build soundex string */ last = -1; auto p = str.slice().data(); for (_small = 0; *p && _small < 4; p++) { /* convert chars to upper case and strip non-letter chars */ /* BUG: should also map here accented letters used in non */ /* English words or names (also found in English text!): */ /* esstsett, thorn, n-tilde, c-cedilla, s-caron, ... */ code = toupper((int)(unsigned char)(*p)); if (code >= 'A' && code <= 'Z') { if (_small == 0) { /* remember first valid char */ soundex[_small++] = code; last = soundex_table[code - 'A']; } else { /* ignore sequences of consonants with same soundex */ /* code in trail, and vowels unless they separate */ /* consonant letters */ code = soundex_table[code - 'A']; if (code != last) { if (code != 0) { soundex[_small++] = code; } last = code; } } } } /* pad with '0' and terminate with 0 ;-) */ while (_small < 4) { soundex[_small++] = '0'; } retString.setSize(4); return retString; } /////////////////////////////////////////////////////////////////////////////// // metaphone /** * this is now the original code by Michael G Schwern: * i've changed it just a slightly bit (use emalloc, * get rid of includes etc) * - thies - 13.09.1999 */ /*----------------------------- */ /* this used to be "metaphone.h" */ /*----------------------------- */ /* Special encodings */ #define SH 'X' #define TH '0' /*----------------------------- */ /* end of "metaphone.h" */ /*----------------------------- */ /*----------------------------- */ /* this used to be "metachar.h" */ /*----------------------------- */ /* Metachar.h ... little bits about characters for metaphone */ /*-- Character encoding array & accessing macros --*/ /* Stolen directly out of the book... */ char _codes[26] = { 1,16,4,16,9,2,4,16,9,2,0,2,2,2,1,4,0,2,4,4,1,0,0,0,8,0}; #define ENCODE(c) (isalpha(c) ? _codes[((toupper(c)) - 'A')] : 0) #define isvowel(c) (ENCODE(c) & 1) /* AEIOU */ /* These letters are passed through unchanged */ #define NOCHANGE(c) (ENCODE(c) & 2) /* FJMNR */ /* These form dipthongs when preceding H */ #define AFFECTH(c) (ENCODE(c) & 4) /* CGPST */ /* These make C and G soft */ #define MAKESOFT(c) (ENCODE(c) & 8) /* EIY */ /* These prevent GH from becoming F */ #define NOGHTOF(c) (ENCODE(c) & 16) /* BDH */ /*----------------------------- */ /* end of "metachar.h" */ /*----------------------------- */ /* I suppose I could have been using a character pointer instead of * accesssing the array directly... */ /* Look at the next letter in the word */ #define Next_Letter ((char)toupper(word[w_idx+1])) /* Look at the current letter in the word */ #define Curr_Letter ((char)toupper(word[w_idx])) /* Go N letters back. */ #define Look_Back_Letter(n) (w_idx >= n ? (char)toupper(word[w_idx-n]) : '\0') /* Previous letter. I dunno, should this return null on failure? */ #define Prev_Letter (Look_Back_Letter(1)) /* Look two letters down. It makes sure you don't walk off the string. */ #define After_Next_Letter (Next_Letter != '\0' ? (char)toupper(word[w_idx+2]) \ : '\0') #define Look_Ahead_Letter(n) ((char)toupper(Lookahead(word+w_idx, n))) /* Allows us to safely look ahead an arbitrary # of letters */ /* I probably could have just used strlen... */ static char Lookahead(unsigned char *word, int how_far) { char letter_ahead = '\0'; /* null by default */ int idx; for (idx = 0; word[idx] != '\0' && idx < how_far; idx++); /* Edge forward in the string... */ letter_ahead = (char)word[idx]; /* idx will be either == to how_far or * at the end of the string */ return letter_ahead; } /* phonize one letter * We don't know the buffers size in advance. On way to solve this is to just * re-allocate the buffer size. We're using an extra of 2 characters (this * could be one though; or more too). */ #define Phonize(c) { buffer.append(c); } /* How long is the phoned word? */ #define Phone_Len (buffer.size()) /* Note is a letter is a 'break' in the word */ #define Isbreak(c) (!isalpha(c)) String string_metaphone(const char *input, int word_len, long max_phonemes, int traditional) { unsigned char *word = (unsigned char *)input; int w_idx = 0; /* point in the phonization we're at. */ int max_buffer_len = 0; /* maximum length of the destination buffer */ /*-- Parameter checks --*/ /* Negative phoneme length is meaningless */ if (max_phonemes < 0) return String(); /* Empty/null string is meaningless */ /* Overly paranoid */ /* always_assert(word != NULL && word[0] != '\0'); */ if (word == nullptr) return String(); /*-- Allocate memory for our phoned_phrase --*/ if (max_phonemes == 0) { /* Assume largest possible */ max_buffer_len = word_len; } else { max_buffer_len = max_phonemes; } StringBuffer buffer(max_buffer_len); /*-- The first phoneme has to be processed specially. --*/ /* Find our first letter */ for (; !isalpha(Curr_Letter); w_idx++) { /* On the off chance we were given nothing but crap... */ if (Curr_Letter == '\0') { return buffer.detach(); /* For testing */ } } switch (Curr_Letter) { /* AE becomes E */ case 'A': if (Next_Letter == 'E') { Phonize('E'); w_idx += 2; } /* Remember, preserve vowels at the beginning */ else { Phonize('A'); w_idx++; } break; /* [GKP]N becomes N */ case 'G': case 'K': case 'P': if (Next_Letter == 'N') { Phonize('N'); w_idx += 2; } break; /* WH becomes H, WR becomes R W if followed by a vowel */ case 'W': if (Next_Letter == 'H' || Next_Letter == 'R') { Phonize(Next_Letter); w_idx += 2; } else if (isvowel(Next_Letter)) { Phonize('W'); w_idx += 2; } /* else ignore */ break; /* X becomes S */ case 'X': Phonize('S'); w_idx++; break; /* Vowels are kept */ /* We did A already case 'A': case 'a': */ case 'E': case 'I': case 'O': case 'U': Phonize(Curr_Letter); w_idx++; break; default: /* do nothing */ break; } /* On to the metaphoning */ for (; Curr_Letter != '\0' && (max_phonemes == 0 || Phone_Len < max_phonemes); w_idx++) { /* How many letters to skip because an eariler encoding handled * multiple letters */ unsigned short int skip_letter = 0; /* THOUGHT: It would be nice if, rather than having things like... * well, SCI. For SCI you encode the S, then have to remember * to skip the C. So the phonome SCI invades both S and C. It would * be better, IMHO, to skip the C from the S part of the encoding. * Hell, I'm trying it. */ /* Ignore non-alphas */ if (!isalpha(Curr_Letter)) continue; /* Drop duplicates, except CC */ if (Curr_Letter == Prev_Letter && Curr_Letter != 'C') continue; switch (Curr_Letter) { /* B -> B unless in MB */ case 'B': if (Prev_Letter != 'M') Phonize('B'); break; /* 'sh' if -CIA- or -CH, but not SCH, except SCHW. * (SCHW is handled in S) * S if -CI-, -CE- or -CY- * dropped if -SCI-, SCE-, -SCY- (handed in S) * else K */ case 'C': if (MAKESOFT(Next_Letter)) { /* C[IEY] */ if (After_Next_Letter == 'A' && Next_Letter == 'I') { /* CIA */ Phonize(SH); } /* SC[IEY] */ else if (Prev_Letter == 'S') { /* Dropped */ } else { Phonize('S'); } } else if (Next_Letter == 'H') { if ((!traditional) && (After_Next_Letter == 'R' || Prev_Letter == 'S')) { /* Christ, School */ Phonize('K'); } else { Phonize(SH); } skip_letter++; } else { Phonize('K'); } break; /* J if in -DGE-, -DGI- or -DGY- * else T */ case 'D': if (Next_Letter == 'G' && MAKESOFT(After_Next_Letter)) { Phonize('J'); skip_letter++; } else Phonize('T'); break; /* F if in -GH and not B--GH, D--GH, -H--GH, -H---GH * else dropped if -GNED, -GN, * else dropped if -DGE-, -DGI- or -DGY- (handled in D) * else J if in -GE-, -GI, -GY and not GG * else K */ case 'G': if (Next_Letter == 'H') { if (!(NOGHTOF(Look_Back_Letter(3)) || Look_Back_Letter(4) == 'H')) { Phonize('F'); skip_letter++; } else { /* silent */ } } else if (Next_Letter == 'N') { if (Isbreak(After_Next_Letter) || (After_Next_Letter == 'E' && Look_Ahead_Letter(3) == 'D')) { /* dropped */ } else Phonize('K'); } else if (MAKESOFT(Next_Letter) && Prev_Letter != 'G') { Phonize('J'); } else { Phonize('K'); } break; /* H if before a vowel and not after C,G,P,S,T */ case 'H': if (isvowel(Next_Letter) && !AFFECTH(Prev_Letter)) Phonize('H'); break; /* dropped if after C * else K */ case 'K': if (Prev_Letter != 'C') Phonize('K'); break; /* F if before H * else P */ case 'P': if (Next_Letter == 'H') { Phonize('F'); } else { Phonize('P'); } break; /* K */ case 'Q': Phonize('K'); break; /* 'sh' in -SH-, -SIO- or -SIA- or -SCHW- * else S */ case 'S': if (Next_Letter == 'I' && (After_Next_Letter == 'O' || After_Next_Letter == 'A')) { Phonize(SH); } else if (Next_Letter == 'H') { Phonize(SH); skip_letter++; } else if ((!traditional) && (Next_Letter == 'C' && Look_Ahead_Letter(2) == 'H' && Look_Ahead_Letter(3) == 'W')) { Phonize(SH); skip_letter += 2; } else { Phonize('S'); } break; /* 'sh' in -TIA- or -TIO- * else 'th' before H * else T */ case 'T': if (Next_Letter == 'I' && (After_Next_Letter == 'O' || After_Next_Letter == 'A')) { Phonize(SH); } else if (Next_Letter == 'H') { Phonize(TH); skip_letter++; } else { Phonize('T'); } break; /* F */ case 'V': Phonize('F'); break; /* W before a vowel, else dropped */ case 'W': if (isvowel(Next_Letter)) Phonize('W'); break; /* KS */ case 'X': Phonize('K'); Phonize('S'); break; /* Y if followed by a vowel */ case 'Y': if (isvowel(Next_Letter)) Phonize('Y'); break; /* S */ case 'Z': Phonize('S'); break; /* No transformation */ case 'F': case 'J': case 'L': case 'M': case 'N': case 'R': Phonize(Curr_Letter); break; default: /* nothing */ break; } /* END SWITCH */ w_idx += skip_letter; } /* END FOR */ return buffer.detach(); } /////////////////////////////////////////////////////////////////////////////// // Cyrillic /** * This is codetables for different Cyrillic charsets (relative to koi8-r). * Each table contains data for 128-255 symbols from ASCII table. * First 256 symbols are for conversion from koi8-r to corresponding charset, * second 256 symbols are for reverse conversion, from charset to koi8-r. * * Here we have the following tables: * _cyr_win1251 - for windows-1251 charset * _cyr_iso88595 - for iso8859-5 charset * _cyr_cp866 - for x-cp866 charset * _cyr_mac - for x-mac-cyrillic charset */ typedef unsigned char _cyr_charset_table[512]; static const _cyr_charset_table _cyr_win1251 = { 0,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, 46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46, 46,46,46,46,46,46,46,46,46,46,46,46,46,46,46,46, 154,174,190,46,159,189,46,46,179,191,180,157,46,46,156,183, 46,46,182,166,173,46,46,158,163,152,164,155,46,46,46,167, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209, 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,184,186,32,179,191,32,32,32,32,32,180,162,32, 32,32,32,168,170,32,178,175,32,32,32,32,32,165,161,169, 254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238, 239,255,240,241,242,243,230,226,252,251,231,248,253,249,247,250, 222,192,193,214,196,197,212,195,213,200,201,202,203,204,205,206, 207,223,208,209,210,211,198,194,220,219,199,216,221,217,215,218, }; static const _cyr_charset_table _cyr_cp866 = { 0,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, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 35,35,35,124,124,124,124,43,43,124,124,43,43,43,43,43, 43,45,45,124,45,43,124,124,43,43,45,45,124,45,43,45, 45,45,45,43,43,43,43,43,43,43,43,35,35,124,124,35, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209, 179,163,180,164,183,167,190,174,32,149,158,32,152,159,148,154, 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 205,186,213,241,243,201,32,245,187,212,211,200,190,32,247,198, 199,204,181,240,242,185,32,244,203,207,208,202,216,32,246,32, 238,160,161,230,164,165,228,163,229,168,169,170,171,172,173,174, 175,239,224,225,226,227,166,162,236,235,167,232,237,233,231,234, 158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142, 143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154, }; static const _cyr_charset_table _cyr_iso88595 = { 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,179,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,209, 32,163,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 0,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, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,241,32,32,32,32,32,32,32,32,32,32,32,32, 32,32,32,161,32,32,32,32,32,32,32,32,32,32,32,32, 238,208,209,230,212,213,228,211,229,216,217,218,219,220,221,222, 223,239,224,225,226,227,214,210,236,235,215,232,237,233,231,234, 206,176,177,198,180,181,196,179,197,184,185,186,187,188,189,190, 191,207,192,193,194,195,182,178,204,203,183,200,205,201,199,202, }; static const _cyr_charset_table _cyr_mac = { 0,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, 225,226,247,231,228,229,246,250,233,234,235,236,237,238,239,240, 242,243,244,245,230,232,227,254,251,253,255,249,248,252,224,241, 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, 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,179,163,209, 193,194,215,199,196,197,214,218,201,202,203,204,205,206,207,208, 210,211,212,213,198,200,195,222,219,221,223,217,216,220,192,255, 0,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, 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207, 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223, 160,161,162,222,164,165,166,167,168,169,170,171,172,173,174,175, 176,177,178,221,180,181,182,183,184,185,186,187,188,189,190,191, 254,224,225,246,228,229,244,227,245,232,233,234,235,236,237,238, 239,223,240,241,242,243,230,226,252,251,231,248,253,249,247,250, 158,128,129,150,132,133,148,131,149,136,137,138,139,140,141,142, 143,159,144,145,146,147,134,130,156,155,135,152,157,153,151,154, }; /** * This is the function that performs real in-place conversion of the string * between charsets. * Parameters: * str - string to be converted * from,to - one-symbol label of source and destination charset * The following symbols are used as labels: * k - koi8-r * w - windows-1251 * i - iso8859-5 * a - x-cp866 * d - x-cp866 * m - x-mac-cyrillic */ String string_convert_cyrillic_string(const String& input, char from, char to) { const unsigned char *from_table, *to_table; unsigned char tmp; auto uinput = (unsigned char*)input.slice().data(); String retString(input.size(), ReserveString); unsigned char *str = (unsigned char *)retString.mutableData(); from_table = nullptr; to_table = nullptr; switch (toupper((int)(unsigned char)from)) { case 'W': from_table = _cyr_win1251; break; case 'A': case 'D': from_table = _cyr_cp866; break; case 'I': from_table = _cyr_iso88595; break; case 'M': from_table = _cyr_mac; break; case 'K': break; default: throw_invalid_argument("Unknown source charset: %c", from); break; } switch (toupper((int)(unsigned char)to)) { case 'W': to_table = _cyr_win1251; break; case 'A': case 'D': to_table = _cyr_cp866; break; case 'I': to_table = _cyr_iso88595; break; case 'M': to_table = _cyr_mac; break; case 'K': break; default: throw_invalid_argument("Unknown destination charset: %c", to); break; } for (int i = 0; i < input.size(); i++) { tmp = from_table == nullptr ? uinput[i] : from_table[uinput[i]]; str[i] = to_table == nullptr ? tmp : to_table[tmp + 256]; } retString.setSize(input.size()); return retString; } /////////////////////////////////////////////////////////////////////////////// // Hebrew #define HEB_BLOCK_TYPE_ENG 1 #define HEB_BLOCK_TYPE_HEB 2 #define isheb(c) \ (((((unsigned char) c) >= 224) && (((unsigned char) c) <= 250)) ? 1 : 0) #define _isblank(c) \ (((((unsigned char) c) == ' ' || ((unsigned char) c) == '\t')) ? 1 : 0) #define _isnewline(c) \ (((((unsigned char) c) == '\n' || ((unsigned char) c) == '\r')) ? 1 : 0) /** * Converts Logical Hebrew text (Hebrew Windows style) to Visual text * Cheers/complaints/flames - Zeev Suraski <zeev@php.net> */ String string_convert_hebrew_string(const String& inStr, int /*max_chars_per_line*/, int convert_newlines) { assertx(!inStr.empty()); auto str = inStr.data(); auto str_len = inStr.size(); const char *tmp; char *heb_str, *broken_str; char *target; int block_start, block_end, block_type, block_length, i; long max_chars=0; int begin, end, char_count, orig_begin; tmp = str; block_start=block_end=0; heb_str = (char *) req::malloc_noptrs(str_len + 1); SCOPE_EXIT { req::free(heb_str); }; target = heb_str+str_len; *target = 0; target--; block_length=0; if (isheb(*tmp)) { block_type = HEB_BLOCK_TYPE_HEB; } else { block_type = HEB_BLOCK_TYPE_ENG; } do { if (block_type == HEB_BLOCK_TYPE_HEB) { while ((isheb((int)*(tmp+1)) || _isblank((int)*(tmp+1)) || ispunct((int)*(tmp+1)) || (int)*(tmp+1)=='\n' ) && block_end<str_len-1) { tmp++; block_end++; block_length++; } for (i = block_start; i<= block_end; i++) { *target = str[i]; switch (*target) { case '(': *target = ')'; break; case ')': *target = '('; break; case '[': *target = ']'; break; case ']': *target = '['; break; case '{': *target = '}'; break; case '}': *target = '{'; break; case '<': *target = '>'; break; case '>': *target = '<'; break; case '\\': *target = '/'; break; case '/': *target = '\\'; break; default: break; } target--; } block_type = HEB_BLOCK_TYPE_ENG; } else { while (!isheb(*(tmp+1)) && (int)*(tmp+1)!='\n' && block_end < str_len-1) { tmp++; block_end++; block_length++; } while ((_isblank((int)*tmp) || ispunct((int)*tmp)) && *tmp!='/' && *tmp!='-' && block_end > block_start) { tmp--; block_end--; } for (i = block_end; i >= block_start; i--) { *target = str[i]; target--; } block_type = HEB_BLOCK_TYPE_HEB; } block_start=block_end+1; } while (block_end < str_len-1); String brokenStr(str_len, ReserveString); broken_str = brokenStr.mutableData(); begin=end=str_len-1; target = broken_str; while (1) { char_count=0; while ((!max_chars || char_count < max_chars) && begin > 0) { char_count++; begin--; if (begin <= 0 || _isnewline(heb_str[begin])) { while (begin > 0 && _isnewline(heb_str[begin-1])) { begin--; char_count++; } break; } } if (char_count == max_chars) { /* try to avoid breaking words */ int new_char_count=char_count, new_begin=begin; while (new_char_count > 0) { if (_isblank(heb_str[new_begin]) || _isnewline(heb_str[new_begin])) { break; } new_begin++; new_char_count--; } if (new_char_count > 0) { char_count=new_char_count; begin=new_begin; } } orig_begin=begin; if (_isblank(heb_str[begin])) { heb_str[begin]='\n'; } while (begin <= end && _isnewline(heb_str[begin])) { /* skip leading newlines */ begin++; } for (i = begin; i <= end; i++) { /* copy content */ *target = heb_str[i]; target++; } for (i = orig_begin; i <= end && _isnewline(heb_str[i]); i++) { *target = heb_str[i]; target++; } begin=orig_begin; if (begin <= 0) { *target = 0; break; } begin--; end=begin; } if (convert_newlines) { int count; auto ret = string_replace(broken_str, str_len, "\n", strlen("\n"), "<br />\n", strlen("<br />\n"), count, true); if (!ret.isNull()) { return ret; } } brokenStr.setSize(str_len); return brokenStr; } /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_1383_0
crossvul-cpp_data_bad_94_1
/* Library for accessing X3F Files ---------------------------------------------------------------- BSD-style License ---------------------------------------------------------------- * Copyright (c) 2010, Roland Karlsson (roland@proxel.se) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the organization nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY ROLAND KARLSSON ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ROLAND KARLSSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* From X3F_IO.H */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <stdio.h> #include "../libraw/libraw_datastream.h" #define SIZE_UNIQUE_IDENTIFIER 16 #define SIZE_WHITE_BALANCE 32 #define SIZE_COLOR_MODE 32 #define NUM_EXT_DATA_2_1 32 #define NUM_EXT_DATA_3_0 64 #define NUM_EXT_DATA NUM_EXT_DATA_3_0 #define X3F_VERSION(MAJ,MIN) (uint32_t)(((MAJ)<<16) + MIN) #define X3F_VERSION_2_0 X3F_VERSION(2,0) #define X3F_VERSION_2_1 X3F_VERSION(2,1) #define X3F_VERSION_2_2 X3F_VERSION(2,2) #define X3F_VERSION_2_3 X3F_VERSION(2,3) #define X3F_VERSION_3_0 X3F_VERSION(3,0) #define X3F_VERSION_4_0 X3F_VERSION(4,0) /* Main file identifier */ #define X3F_FOVb (uint32_t)(0x62564f46) /* Directory identifier */ #define X3F_SECd (uint32_t)(0x64434553) /* Property section identifiers */ #define X3F_PROP (uint32_t)(0x504f5250) #define X3F_SECp (uint32_t)(0x70434553) /* Image section identifiers */ #define X3F_IMAG (uint32_t)(0x46414d49) #define X3F_IMA2 (uint32_t)(0x32414d49) #define X3F_SECi (uint32_t)(0x69434553) /* CAMF section identifiers */ #define X3F_CAMF (uint32_t)(0x464d4143) #define X3F_SECc (uint32_t)(0x63434553) /* CAMF entry identifiers */ #define X3F_CMbP (uint32_t)(0x50624d43) #define X3F_CMbT (uint32_t)(0x54624d43) #define X3F_CMbM (uint32_t)(0x4d624d43) #define X3F_CMb (uint32_t)(0x00624d43) /* SDQ section identifiers ? - TODO */ #define X3F_SPPA (uint32_t)(0x41505053) #define X3F_SECs (uint32_t)(0x73434553) #define X3F_IMAGE_THUMB_PLAIN (uint32_t)(0x00020003) #define X3F_IMAGE_THUMB_HUFFMAN (uint32_t)(0x0002000b) #define X3F_IMAGE_THUMB_JPEG (uint32_t)(0x00020012) #define X3F_IMAGE_THUMB_SDQ (uint32_t)(0x00020019) /* SDQ ? - TODO */ #define X3F_IMAGE_RAW_HUFFMAN_X530 (uint32_t)(0x00030005) #define X3F_IMAGE_RAW_HUFFMAN_10BIT (uint32_t)(0x00030006) #define X3F_IMAGE_RAW_TRUE (uint32_t)(0x0003001e) #define X3F_IMAGE_RAW_MERRILL (uint32_t)(0x0001001e) #define X3F_IMAGE_RAW_QUATTRO (uint32_t)(0x00010023) #define X3F_IMAGE_RAW_SDQ (uint32_t)(0x00010025) #define X3F_IMAGE_RAW_SDQH (uint32_t)(0x00010027) #define X3F_IMAGE_RAW_SDQH2 (uint32_t)(0x00010029) #define X3F_IMAGE_HEADER_SIZE 28 #define X3F_CAMF_HEADER_SIZE 28 #define X3F_PROPERTY_LIST_HEADER_SIZE 24 typedef uint16_t utf16_t; typedef int bool_t; typedef enum x3f_extended_types_e { X3F_EXT_TYPE_NONE=0, X3F_EXT_TYPE_EXPOSURE_ADJUST=1, X3F_EXT_TYPE_CONTRAST_ADJUST=2, X3F_EXT_TYPE_SHADOW_ADJUST=3, X3F_EXT_TYPE_HIGHLIGHT_ADJUST=4, X3F_EXT_TYPE_SATURATION_ADJUST=5, X3F_EXT_TYPE_SHARPNESS_ADJUST=6, X3F_EXT_TYPE_RED_ADJUST=7, X3F_EXT_TYPE_GREEN_ADJUST=8, X3F_EXT_TYPE_BLUE_ADJUST=9, X3F_EXT_TYPE_FILL_LIGHT_ADJUST=10 } x3f_extended_types_t; typedef struct x3f_property_s { /* Read from file */ uint32_t name_offset; uint32_t value_offset; /* Computed */ utf16_t *name; /* 0x0000 terminated UTF 16 */ utf16_t *value; /* 0x0000 terminated UTF 16 */ char *name_utf8; /* converted to UTF 8 */ char *value_utf8; /* converted to UTF 8 */ } x3f_property_t; typedef struct x3f_property_table_s { uint32_t size; x3f_property_t *element; } x3f_property_table_t; typedef struct x3f_property_list_s { /* 2.0 Fields */ uint32_t num_properties; uint32_t character_format; uint32_t reserved; uint32_t total_length; x3f_property_table_t property_table; void *data; uint32_t data_size; } x3f_property_list_t; typedef struct x3f_table8_s { uint32_t size; uint8_t *element; } x3f_table8_t; typedef struct x3f_table16_s { uint32_t size; uint16_t *element; } x3f_table16_t; typedef struct x3f_table32_s { uint32_t size; uint32_t *element; } x3f_table32_t; typedef struct { uint8_t *data; /* Pointer to actual image data */ void *buf; /* Pointer to allocated buffer for free() */ uint32_t rows; uint32_t columns; uint32_t channels; uint32_t row_stride; } x3f_area8_t; typedef struct { uint16_t *data; /* Pointer to actual image data */ void *buf; /* Pointer to allocated buffer for free() */ uint32_t rows; uint32_t columns; uint32_t channels; uint32_t row_stride; } x3f_area16_t; #define UNDEFINED_LEAF 0xffffffff typedef struct x3f_huffnode_s { struct x3f_huffnode_s *branch[2]; uint32_t leaf; } x3f_huffnode_t; typedef struct x3f_hufftree_s { uint32_t free_node_index; /* Free node index in huffman tree array */ x3f_huffnode_t *nodes; /* Coding tree */ } x3f_hufftree_t; typedef struct x3f_true_huffman_element_s { uint8_t code_size; uint8_t code; } x3f_true_huffman_element_t; typedef struct x3f_true_huffman_s { uint32_t size; x3f_true_huffman_element_t *element; } x3f_true_huffman_t; /* 0=bottom, 1=middle, 2=top */ #define TRUE_PLANES 3 typedef struct x3f_true_s { uint16_t seed[TRUE_PLANES]; /* Always 512,512,512 */ uint16_t unknown; /* Always 0 */ x3f_true_huffman_t table; /* Huffman table - zero terminated. size is the number of leaves plus 1.*/ x3f_table32_t plane_size; /* Size of the 3 planes */ uint8_t *plane_address[TRUE_PLANES]; /* computed offset to the planes */ x3f_hufftree_t tree; /* Coding tree */ x3f_area16_t x3rgb16; /* 3x16 bit X3-RGB data */ } x3f_true_t; typedef struct x3f_quattro_s { struct { uint16_t columns; uint16_t rows; } plane[TRUE_PLANES]; uint32_t unknown; bool_t quattro_layout; x3f_area16_t top16; /* Container for the bigger top layer */ } x3f_quattro_t; typedef struct x3f_huffman_s { x3f_table16_t mapping; /* Value Mapping = X3F lossy compression */ x3f_table32_t table; /* Coding Table */ x3f_hufftree_t tree; /* Coding tree */ x3f_table32_t row_offsets; /* Row offsets */ x3f_area8_t rgb8; /* 3x8 bit RGB data */ x3f_area16_t x3rgb16; /* 3x16 bit X3-RGB data */ } x3f_huffman_t; typedef struct x3f_image_data_s { /* 2.0 Fields */ /* ------------------------------------------------------------------ */ /* Known combinations of type and format are: 1-6, 2-3, 2-11, 2-18, 3-6 */ uint32_t type; /* 1 = RAW X3 (SD1) 2 = thumbnail or maybe just RGB 3 = RAW X3 */ uint32_t format; /* 3 = 3x8 bit pixmap 6 = 3x10 bit huffman with map table 11 = 3x8 bit huffman 18 = JPEG */ uint32_t type_format; /* type<<16 + format */ /* ------------------------------------------------------------------ */ uint32_t columns; /* width / row size in pixels */ uint32_t rows; /* height */ uint32_t row_stride; /* row size in bytes */ /* NULL if not used */ x3f_huffman_t *huffman; /* Huffman help data */ x3f_true_t *tru; /* TRUE help data */ x3f_quattro_t *quattro; /* Quattro help data */ void *data; /* Take from file if NULL. Otherwise, this is the actual data bytes in the file. */ uint32_t data_size; } x3f_image_data_t; typedef struct camf_dim_entry_s { uint32_t size; uint32_t name_offset; uint32_t n; /* 0,1,2,3... */ char *name; } camf_dim_entry_t; typedef enum {M_FLOAT, M_INT, M_UINT} matrix_type_t; typedef struct camf_entry_s { /* pointer into decoded data */ void *entry; /* entry header */ uint32_t id; uint32_t version; uint32_t entry_size; uint32_t name_offset; uint32_t value_offset; /* computed values */ char *name_address; void *value_address; uint32_t name_size; uint32_t value_size; /* extracted values for explicit CAMF entry types*/ uint32_t text_size; char *text; uint32_t property_num; char **property_name; uint8_t **property_value; uint32_t matrix_dim; camf_dim_entry_t *matrix_dim_entry; /* Offset, pointer and size and type of raw data */ uint32_t matrix_type; uint32_t matrix_data_off; void *matrix_data; uint32_t matrix_element_size; /* Pointer and type of copied data */ matrix_type_t matrix_decoded_type; void *matrix_decoded; /* Help data to try to estimate element size */ uint32_t matrix_elements; uint32_t matrix_used_space; double matrix_estimated_element_size; } camf_entry_t; typedef struct camf_entry_table_s { uint32_t size; camf_entry_t *element; } camf_entry_table_t; typedef struct x3f_camf_typeN_s { uint32_t val0; uint32_t val1; uint32_t val2; uint32_t val3; } x3f_camf_typeN_t; typedef struct x3f_camf_type2_s { uint32_t reserved; uint32_t infotype; uint32_t infotype_version; uint32_t crypt_key; } x3f_camf_type2_t; typedef struct x3f_camf_type4_s { uint32_t decoded_data_size; uint32_t decode_bias; uint32_t block_size; uint32_t block_count; } x3f_camf_type4_t; typedef struct x3f_camf_type5_s { uint32_t decoded_data_size; uint32_t decode_bias; uint32_t unknown2; uint32_t unknown3; } x3f_camf_type5_t; typedef struct x3f_camf_s { /* Header info */ uint32_t type; union { x3f_camf_typeN_t tN; x3f_camf_type2_t t2; x3f_camf_type4_t t4; x3f_camf_type5_t t5; }; /* The encrypted raw data */ void *data; uint32_t data_size; /* Help data for type 4 Huffman compression */ x3f_true_huffman_t table; x3f_hufftree_t tree; uint8_t *decoding_start; uint32_t decoding_size; /* The decrypted data */ void *decoded_data; uint32_t decoded_data_size; /* Pointers into the decrypted data */ camf_entry_table_t entry_table; } x3f_camf_t; typedef struct x3f_directory_entry_header_s { uint32_t identifier; /* Should be ´SECp´, "SECi", ... */ uint32_t version; /* 0x00020001 is version 2.1 */ union { x3f_property_list_t property_list; x3f_image_data_t image_data; x3f_camf_t camf; } data_subsection; } x3f_directory_entry_header_t; typedef struct x3f_directory_entry_s { struct { uint32_t offset; uint32_t size; } input, output; uint32_t type; x3f_directory_entry_header_t header; } x3f_directory_entry_t; typedef struct x3f_directory_section_s { uint32_t identifier; /* Should be ´SECd´ */ uint32_t version; /* 0x00020001 is version 2.1 */ /* 2.0 Fields */ uint32_t num_directory_entries; x3f_directory_entry_t *directory_entry; } x3f_directory_section_t; typedef struct x3f_header_s { /* 2.0 Fields */ uint32_t identifier; /* Should be ´FOVb´ */ uint32_t version; /* 0x00020001 means 2.1 */ uint8_t unique_identifier[SIZE_UNIQUE_IDENTIFIER]; uint32_t mark_bits; uint32_t columns; /* Columns and rows ... */ uint32_t rows; /* ... before rotation */ uint32_t rotation; /* 0, 90, 180, 270 */ char white_balance[SIZE_WHITE_BALANCE]; /* Introduced in 2.1 */ char color_mode[SIZE_COLOR_MODE]; /* Introduced in 2.3 */ /* Introduced in 2.1 and extended from 32 to 64 in 3.0 */ uint8_t extended_types[NUM_EXT_DATA]; /* x3f_extended_types_t */ float extended_data[NUM_EXT_DATA]; /* 32 bits, but do type differ? */ } x3f_header_t; typedef struct x3f_info_s { char *error; struct { LibRaw_abstract_datastream *file; /* Use if more data is needed */ } input, output; } x3f_info_t; typedef struct x3f_s { x3f_info_t info; x3f_header_t header; x3f_directory_section_t directory_section; } x3f_t; typedef enum x3f_return_e { X3F_OK=0, X3F_ARGUMENT_ERROR=1, X3F_INFILE_ERROR=2, X3F_OUTFILE_ERROR=3, X3F_INTERNAL_ERROR=4 } x3f_return_t; x3f_return_t x3f_delete(x3f_t *x3f); /* Hacky external flags */ /* --------------------------------------------------------------------- */ /* extern */ int legacy_offset = 0; /* extern */ bool_t auto_legacy_offset = 1; /* --------------------------------------------------------------------- */ /* Huffman Decode Macros */ /* --------------------------------------------------------------------- */ #define HUF_TREE_MAX_LENGTH 27 #define HUF_TREE_MAX_NODES(_leaves) ((HUF_TREE_MAX_LENGTH+1)*(_leaves)) #define HUF_TREE_GET_LENGTH(_v) (((_v)>>27)&0x1f) #define HUF_TREE_GET_CODE(_v) ((_v)&0x07ffffff) /* --------------------------------------------------------------------- */ /* Reading and writing - assuming little endian in the file */ /* --------------------------------------------------------------------- */ static int x3f_get1(LibRaw_abstract_datastream *f) { /* Little endian file */ return f->get_char(); } static int x3f_sget2 (uchar *s) { return s[0] | s[1] << 8; } static int x3f_get2(LibRaw_abstract_datastream *f) { uchar str[2] = { 0xff,0xff }; f->read (str, 1, 2); return x3f_sget2(str); } unsigned x3f_sget4 (uchar *s) { return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; } unsigned x3f_get4(LibRaw_abstract_datastream *f) { uchar str[4] = { 0xff,0xff,0xff,0xff }; f->read (str, 1, 4); return x3f_sget4(str); } #define FREE(P) do { free(P); (P) = NULL; } while (0) #define PUT_GET_N(_buffer,_size,_file,_func) \ do \ { \ int _left = _size; \ while (_left != 0) { \ int _cur = _file->_func(_buffer,1,_left); \ if (_cur == 0) { \ throw LIBRAW_EXCEPTION_IO_CORRUPT; \ exit(1); \ } \ _left -= _cur; \ } \ } while(0) #define GET1(_v) do {(_v) = x3f_get1(I->input.file);} while (0) #define GET2(_v) do {(_v) = x3f_get2(I->input.file);} while (0) #define GET4(_v) do {(_v) = x3f_get4(I->input.file);} while (0) #define GET4F(_v) \ do { \ union {int32_t i; float f;} _tmp; \ _tmp.i = x3f_get4(I->input.file); \ (_v) = _tmp.f; \ } while (0) #define GETN(_v,_s) PUT_GET_N(_v,_s,I->input.file,read) #define GET_TABLE(_T, _GETX, _NUM,_TYPE) \ do { \ int _i; \ (_T).size = (_NUM); \ (_T).element = (_TYPE *)realloc((_T).element, \ (_NUM)*sizeof((_T).element[0])); \ for (_i = 0; _i < (_T).size; _i++) \ _GETX((_T).element[_i]); \ } while (0) #define GET_PROPERTY_TABLE(_T, _NUM) \ do { \ int _i; \ (_T).size = (_NUM); \ (_T).element = (x3f_property_t *)realloc((_T).element, \ (_NUM)*sizeof((_T).element[0])); \ for (_i = 0; _i < (_T).size; _i++) { \ GET4((_T).element[_i].name_offset); \ GET4((_T).element[_i].value_offset); \ } \ } while (0) #define GET_TRUE_HUFF_TABLE(_T) \ do { \ int _i; \ (_T).element = NULL; \ for (_i = 0; ; _i++) { \ (_T).size = _i + 1; \ (_T).element = (x3f_true_huffman_element_t *)realloc((_T).element, \ (_i + 1)*sizeof((_T).element[0])); \ GET1((_T).element[_i].code_size); \ GET1((_T).element[_i].code); \ if ((_T).element[_i].code_size == 0) break; \ } \ } while (0) /* --------------------------------------------------------------------- */ /* Allocating Huffman tree help data */ /* --------------------------------------------------------------------- */ static void cleanup_huffman_tree(x3f_hufftree_t *HTP) { free(HTP->nodes); } static void new_huffman_tree(x3f_hufftree_t *HTP, int bits) { int leaves = 1<<bits; HTP->free_node_index = 0; HTP->nodes = (x3f_huffnode_t *) calloc(1, HUF_TREE_MAX_NODES(leaves)*sizeof(x3f_huffnode_t)); } /* --------------------------------------------------------------------- */ /* Allocating TRUE engine RAW help data */ /* --------------------------------------------------------------------- */ static void cleanup_true(x3f_true_t **TRUP) { x3f_true_t *TRU = *TRUP; if (TRU == NULL) return; FREE(TRU->table.element); FREE(TRU->plane_size.element); cleanup_huffman_tree(&TRU->tree); FREE(TRU->x3rgb16.buf); FREE(TRU); *TRUP = NULL; } static x3f_true_t *new_true(x3f_true_t **TRUP) { x3f_true_t *TRU = (x3f_true_t *)calloc(1, sizeof(x3f_true_t)); cleanup_true(TRUP); TRU->table.size = 0; TRU->table.element = NULL; TRU->plane_size.size = 0; TRU->plane_size.element = NULL; TRU->tree.nodes = NULL; TRU->x3rgb16.data = NULL; TRU->x3rgb16.buf = NULL; *TRUP = TRU; return TRU; } static void cleanup_quattro(x3f_quattro_t **QP) { x3f_quattro_t *Q = *QP; if (Q == NULL) return; FREE(Q->top16.buf); FREE(Q); *QP = NULL; } static x3f_quattro_t *new_quattro(x3f_quattro_t **QP) { x3f_quattro_t *Q = (x3f_quattro_t *)calloc(1, sizeof(x3f_quattro_t)); int i; cleanup_quattro(QP); for (i=0; i<TRUE_PLANES; i++) { Q->plane[i].columns = 0; Q->plane[i].rows = 0; } Q->unknown = 0; Q->top16.data = NULL; Q->top16.buf = NULL; *QP = Q; return Q; } /* --------------------------------------------------------------------- */ /* Allocating Huffman engine help data */ /* --------------------------------------------------------------------- */ static void cleanup_huffman(x3f_huffman_t **HUFP) { x3f_huffman_t *HUF = *HUFP; if (HUF == NULL) return; FREE(HUF->mapping.element); FREE(HUF->table.element); cleanup_huffman_tree(&HUF->tree); FREE(HUF->row_offsets.element); FREE(HUF->rgb8.buf); FREE(HUF->x3rgb16.buf); FREE(HUF); *HUFP = NULL; } static x3f_huffman_t *new_huffman(x3f_huffman_t **HUFP) { x3f_huffman_t *HUF = (x3f_huffman_t *)calloc(1, sizeof(x3f_huffman_t)); cleanup_huffman(HUFP); /* Set all not read data block pointers to NULL */ HUF->mapping.size = 0; HUF->mapping.element = NULL; HUF->table.size = 0; HUF->table.element = NULL; HUF->tree.nodes = NULL; HUF->row_offsets.size = 0; HUF->row_offsets.element = NULL; HUF->rgb8.data = NULL; HUF->rgb8.buf = NULL; HUF->x3rgb16.data = NULL; HUF->x3rgb16.buf = NULL; *HUFP = HUF; return HUF; } /* --------------------------------------------------------------------- */ /* Creating a new x3f structure from file */ /* --------------------------------------------------------------------- */ /* extern */ x3f_t *x3f_new_from_file(LibRaw_abstract_datastream *infile) { if (!infile) return NULL; INT64 fsize = infile->size(); x3f_t *x3f = (x3f_t *)calloc(1, sizeof(x3f_t)); x3f_info_t *I = NULL; x3f_header_t *H = NULL; x3f_directory_section_t *DS = NULL; int i, d; I = &x3f->info; I->error = NULL; I->input.file = infile; I->output.file = NULL; /* Read file header */ H = &x3f->header; infile->seek(0, SEEK_SET); GET4(H->identifier); if (H->identifier != X3F_FOVb) { free(x3f); return NULL; } GET4(H->version); GETN(H->unique_identifier, SIZE_UNIQUE_IDENTIFIER); /* TODO: the meaning of the rest of the header for version >= 4.0 (Quattro) is unknown */ if (H->version < X3F_VERSION_4_0) { GET4(H->mark_bits); GET4(H->columns); GET4(H->rows); GET4(H->rotation); if (H->version >= X3F_VERSION_2_1) { int num_ext_data = H->version >= X3F_VERSION_3_0 ? NUM_EXT_DATA_3_0 : NUM_EXT_DATA_2_1; GETN(H->white_balance, SIZE_WHITE_BALANCE); if (H->version >= X3F_VERSION_2_3) GETN(H->color_mode, SIZE_COLOR_MODE); GETN(H->extended_types, num_ext_data); for (i = 0; i < num_ext_data; i++) GET4F(H->extended_data[i]); } } /* Go to the beginning of the directory */ infile->seek(-4, SEEK_END); infile->seek(x3f_get4(infile), SEEK_SET); /* Read the directory header */ DS = &x3f->directory_section; GET4(DS->identifier); GET4(DS->version); GET4(DS->num_directory_entries); if (DS->num_directory_entries > 50) goto _err; // too much direntries, most likely broken file if (DS->num_directory_entries > 0) { size_t size = DS->num_directory_entries * sizeof(x3f_directory_entry_t); DS->directory_entry = (x3f_directory_entry_t *)calloc(1, size); } /* Traverse the directory */ for (d=0; d<DS->num_directory_entries; d++) { x3f_directory_entry_t *DE = &DS->directory_entry[d]; x3f_directory_entry_header_t *DEH = &DE->header; uint32_t save_dir_pos; /* Read the directory entry info */ GET4(DE->input.offset); GET4(DE->input.size); if (DE->input.offset + DE->input.size > fsize * 2) goto _err; DE->output.offset = 0; DE->output.size = 0; GET4(DE->type); /* Save current pos and go to the entry */ save_dir_pos = infile->tell(); infile->seek(DE->input.offset, SEEK_SET); /* Read the type independent part of the entry header */ DEH = &DE->header; GET4(DEH->identifier); GET4(DEH->version); /* NOTE - the tests below could be made on DE->type instead */ if (DEH->identifier == X3F_SECp) { x3f_property_list_t *PL = &DEH->data_subsection.property_list; if (!PL) goto _err; /* Read the property part of the header */ GET4(PL->num_properties); GET4(PL->character_format); GET4(PL->reserved); GET4(PL->total_length); /* Set all not read data block pointers to NULL */ PL->data = NULL; PL->data_size = 0; } if (DEH->identifier == X3F_SECi) { x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID) goto _err; /* Read the image part of the header */ GET4(ID->type); GET4(ID->format); ID->type_format = (ID->type << 16) + (ID->format); GET4(ID->columns); GET4(ID->rows); GET4(ID->row_stride); /* Set all not read data block pointers to NULL */ ID->huffman = NULL; ID->data = NULL; ID->data_size = 0; } if (DEH->identifier == X3F_SECc) { x3f_camf_t *CAMF = &DEH->data_subsection.camf; if (!CAMF) goto _err; /* Read the CAMF part of the header */ GET4(CAMF->type); GET4(CAMF->tN.val0); GET4(CAMF->tN.val1); GET4(CAMF->tN.val2); GET4(CAMF->tN.val3); /* Set all not read data block pointers to NULL */ CAMF->data = NULL; CAMF->data_size = 0; /* Set all not allocated help pointers to NULL */ CAMF->table.element = NULL; CAMF->table.size = 0; CAMF->tree.nodes = NULL; CAMF->decoded_data = NULL; CAMF->decoded_data_size = 0; CAMF->entry_table.element = NULL; CAMF->entry_table.size = 0; } /* Reset the file pointer back to the directory */ infile->seek(save_dir_pos, SEEK_SET); } return x3f; _err: if (x3f) { DS = &x3f->directory_section; if (DS && DS->directory_entry) free(DS->directory_entry); free(x3f); } return NULL; } /* --------------------------------------------------------------------- */ /* Clean up an x3f structure */ /* --------------------------------------------------------------------- */ static void free_camf_entry(camf_entry_t *entry) { FREE(entry->property_name); FREE(entry->property_value); FREE(entry->matrix_decoded); FREE(entry->matrix_dim_entry); } /* extern */ x3f_return_t x3f_delete(x3f_t *x3f) { x3f_directory_section_t *DS; int d; if (x3f == NULL) return X3F_ARGUMENT_ERROR; DS = &x3f->directory_section; if (DS->num_directory_entries > 50) return X3F_ARGUMENT_ERROR; for (d=0; d<DS->num_directory_entries; d++) { x3f_directory_entry_t *DE = &DS->directory_entry[d]; x3f_directory_entry_header_t *DEH = &DE->header; if (DEH->identifier == X3F_SECp) { x3f_property_list_t *PL = &DEH->data_subsection.property_list; if (PL) { int i; for (i = 0; i < PL->property_table.size; i++) { FREE(PL->property_table.element[i].name_utf8); FREE(PL->property_table.element[i].value_utf8); } } FREE(PL->property_table.element); FREE(PL->data); } if (DEH->identifier == X3F_SECi) { x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (ID) { cleanup_huffman(&ID->huffman); cleanup_true(&ID->tru); cleanup_quattro(&ID->quattro); FREE(ID->data); } } if (DEH->identifier == X3F_SECc) { x3f_camf_t *CAMF = &DEH->data_subsection.camf; int i; if (CAMF) { FREE(CAMF->data); FREE(CAMF->table.element); cleanup_huffman_tree(&CAMF->tree); FREE(CAMF->decoded_data); for (i = 0; i < CAMF->entry_table.size; i++) { free_camf_entry(&CAMF->entry_table.element[i]); } } FREE(CAMF->entry_table.element); } } FREE(DS->directory_entry); FREE(x3f); return X3F_OK; } /* --------------------------------------------------------------------- */ /* Getting a reference to a directory entry */ /* --------------------------------------------------------------------- */ /* TODO: all those only get the first instance */ static x3f_directory_entry_t *x3f_get(x3f_t *x3f, uint32_t type, uint32_t image_type) { x3f_directory_section_t *DS; int d; if (x3f == NULL) return NULL; DS = &x3f->directory_section; for (d=0; d<DS->num_directory_entries; d++) { x3f_directory_entry_t *DE = &DS->directory_entry[d]; x3f_directory_entry_header_t *DEH = &DE->header; if (DEH->identifier == type) { switch (DEH->identifier) { case X3F_SECi: { x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (ID->type_format == image_type) return DE; } break; default: return DE; } } } return NULL; } /* extern */ x3f_directory_entry_t *x3f_get_raw(x3f_t *x3f) { x3f_directory_entry_t *DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_HUFFMAN_X530)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_HUFFMAN_10BIT)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_TRUE)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_MERRILL)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_QUATTRO)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_SDQ)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_SDQH)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_SDQH2)) != NULL) return DE; return NULL; } /* extern */ x3f_directory_entry_t *x3f_get_thumb_plain(x3f_t *x3f) { return x3f_get(x3f, X3F_SECi, X3F_IMAGE_THUMB_PLAIN); } /* extern */ x3f_directory_entry_t *x3f_get_thumb_huffman(x3f_t *x3f) { return x3f_get(x3f, X3F_SECi, X3F_IMAGE_THUMB_HUFFMAN); } /* extern */ x3f_directory_entry_t *x3f_get_thumb_jpeg(x3f_t *x3f) { return x3f_get(x3f, X3F_SECi, X3F_IMAGE_THUMB_JPEG); } /* extern */ x3f_directory_entry_t *x3f_get_camf(x3f_t *x3f) { return x3f_get(x3f, X3F_SECc, 0); } /* extern */ x3f_directory_entry_t *x3f_get_prop(x3f_t *x3f) { return x3f_get(x3f, X3F_SECp, 0); } /* For some obscure reason, the bit numbering is weird. It is generally some kind of "big endian" style - e.g. the bit 7 is the first in a byte and bit 31 first in a 4 byte int. For patterns in the huffman pattern table, bit 27 is the first bit and bit 26 the next one. */ #define PATTERN_BIT_POS(_len, _bit) ((_len) - (_bit) - 1) #define MEMORY_BIT_POS(_bit) PATTERN_BIT_POS(8, _bit) /* --------------------------------------------------------------------- */ /* Huffman Decode */ /* --------------------------------------------------------------------- */ /* Make the huffman tree */ #ifdef DBG_PRNT static char *display_code(int length, uint32_t code, char *buffer) { int i; for (i=0; i<length; i++) { int pos = PATTERN_BIT_POS(length, i); buffer[i] = ((code>>pos)&1) == 0 ? '0' : '1'; } buffer[i] = 0; return buffer; } #endif static x3f_huffnode_t *new_node(x3f_hufftree_t *tree) { x3f_huffnode_t *t = &tree->nodes[tree->free_node_index]; t->branch[0] = NULL; t->branch[1] = NULL; t->leaf = UNDEFINED_LEAF; tree->free_node_index++; return t; } static void add_code_to_tree(x3f_hufftree_t *tree, int length, uint32_t code, uint32_t value) { int i; x3f_huffnode_t *t = tree->nodes; for (i=0; i<length; i++) { int pos = PATTERN_BIT_POS(length, i); int bit = (code>>pos)&1; x3f_huffnode_t *t_next = t->branch[bit]; if (t_next == NULL) t_next = t->branch[bit] = new_node(tree); t = t_next; } t->leaf = value; } static void populate_true_huffman_tree(x3f_hufftree_t *tree, x3f_true_huffman_t *table) { int i; new_node(tree); for (i=0; i<table->size; i++) { x3f_true_huffman_element_t *element = &table->element[i]; uint32_t length = element->code_size; if (length != 0) { /* add_code_to_tree wants the code right adjusted */ uint32_t code = ((element->code) >> (8 - length)) & 0xff; uint32_t value = i; add_code_to_tree(tree, length, code, value); #ifdef DBG_PRNT { char buffer[100]; x3f_printf(DEBUG, "H %5d : %5x : %5d : %02x %08x (%08x) (%s)\n", i, i, value, length, code, value, display_code(length, code, buffer)); } #endif } } } static void populate_huffman_tree(x3f_hufftree_t *tree, x3f_table32_t *table, x3f_table16_t *mapping) { int i; new_node(tree); for (i=0; i<table->size; i++) { uint32_t element = table->element[i]; if (element != 0) { uint32_t length = HUF_TREE_GET_LENGTH(element); uint32_t code = HUF_TREE_GET_CODE(element); uint32_t value; /* If we have a valid mapping table - then the value from the mapping table shall be used. Otherwise we use the current index in the table as value. */ if (table->size == mapping->size) value = mapping->element[i]; else value = i; add_code_to_tree(tree, length, code, value); #ifdef DBG_PRNT { char buffer[100]; x3f_printf(DEBUG, "H %5d : %5x : %5d : %02x %08x (%08x) (%s)\n", i, i, value, length, code, element, display_code(length, code, buffer)); } #endif } } } #ifdef DBG_PRNT static void print_huffman_tree(x3f_huffnode_t *t, int length, uint32_t code) { char buf1[100]; char buf2[100]; x3f_printf(DEBUG, "%*s (%s,%s) %s (%s)\n", length, length < 1 ? "-" : (code&1) ? "1" : "0", t->branch[0]==NULL ? "-" : "0", t->branch[1]==NULL ? "-" : "1", t->leaf==UNDEFINED_LEAF ? "-" : (sprintf(buf1, "%x", t->leaf),buf1), display_code(length, code, buf2)); code = code << 1; if (t->branch[0]) print_huffman_tree(t->branch[0], length+1, code+0); if (t->branch[1]) print_huffman_tree(t->branch[1], length+1, code+1); } #endif /* Help machinery for reading bits in a memory */ typedef struct bit_state_s { uint8_t *next_address; uint8_t bit_offset; uint8_t bits[8]; } bit_state_t; static void set_bit_state(bit_state_t *BS, uint8_t *address) { BS->next_address = address; BS->bit_offset = 8; } static uint8_t get_bit(bit_state_t *BS) { if (BS->bit_offset == 8) { uint8_t byte = *BS->next_address; int i; for (i=7; i>= 0; i--) { BS->bits[i] = byte&1; byte = byte >> 1; } BS->next_address++; BS->bit_offset = 0; } return BS->bits[BS->bit_offset++]; } /* Decode use the TRUE algorithm */ static int32_t get_true_diff(bit_state_t *BS, x3f_hufftree_t *HTP) { int32_t diff; x3f_huffnode_t *node = &HTP->nodes[0]; uint8_t bits; while (node->branch[0] != NULL || node->branch[1] != NULL) { uint8_t bit = get_bit(BS); x3f_huffnode_t *new_node = node->branch[bit]; node = new_node; if (node == NULL) { /* TODO: Shouldn't this be treated as a fatal error? */ return 0; } } bits = node->leaf; if (bits == 0) diff = 0; else { uint8_t first_bit = get_bit(BS); int i; diff = first_bit; for (i=1; i<bits; i++) diff = (diff << 1) + get_bit(BS); if (first_bit == 0) diff -= (1<<bits) - 1; } return diff; } /* This code (that decodes one of the X3F color planes, really is a decoding of a compression algorithm suited for Bayer CFA data. In Bayer CFA the data is divided into 2x2 squares that represents (R,G1,G2,B) data. Those four positions are (in this compression) treated as one data stream each, where you store the differences to previous data in the stream. The reason for this is, of course, that the date is more often than not near to the next data in a stream that represents the same color. */ /* TODO: write more about the compression */ static void true_decode_one_color(x3f_image_data_t *ID, int color) { x3f_true_t *TRU = ID->tru; x3f_quattro_t *Q = ID->quattro; uint32_t seed = TRU->seed[color]; /* TODO : Is this correct ? */ int row; x3f_hufftree_t *tree = &TRU->tree; bit_state_t BS; int32_t row_start_acc[2][2]; uint32_t rows = ID->rows; uint32_t cols = ID->columns; x3f_area16_t *area = &TRU->x3rgb16; uint16_t *dst = area->data + color; set_bit_state(&BS, TRU->plane_address[color]); row_start_acc[0][0] = seed; row_start_acc[0][1] = seed; row_start_acc[1][0] = seed; row_start_acc[1][1] = seed; if (ID->type_format == X3F_IMAGE_RAW_QUATTRO || ID->type_format == X3F_IMAGE_RAW_SDQ || ID->type_format == X3F_IMAGE_RAW_SDQH || ID->type_format == X3F_IMAGE_RAW_SDQH2 ) { rows = Q->plane[color].rows; cols = Q->plane[color].columns; if (Q->quattro_layout && color == 2) { area = &Q->top16; dst = area->data; } } else { } if(rows != area->rows || cols < area->columns) throw LIBRAW_EXCEPTION_IO_CORRUPT; for (row = 0; row < rows; row++) { int col; bool_t odd_row = row&1; int32_t acc[2]; for (col = 0; col < cols; col++) { bool_t odd_col = col&1; int32_t diff = get_true_diff(&BS, tree); int32_t prev = col < 2 ? row_start_acc[odd_row][odd_col] : acc[odd_col]; int32_t value = prev + diff; acc[odd_col] = value; if (col < 2) row_start_acc[odd_row][odd_col] = value; /* Discard additional data at the right for binned Quattro plane 2 */ if (col >= area->columns) continue; *dst = value; dst += area->channels; } } } static void true_decode(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; int color; for (color = 0; color < 3; color++) { true_decode_one_color(ID, color); } } /* Decode use the huffman tree */ static int32_t get_huffman_diff(bit_state_t *BS, x3f_hufftree_t *HTP) { int32_t diff; x3f_huffnode_t *node = &HTP->nodes[0]; while (node->branch[0] != NULL || node->branch[1] != NULL) { uint8_t bit = get_bit(BS); x3f_huffnode_t *new_node = node->branch[bit]; node = new_node; if (node == NULL) { /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; return 0; } } diff = node->leaf; return diff; } static void huffman_decode_row(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int row, int offset, int *minimum) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = ID->huffman; int16_t c[3] = {(int16_t)offset,(int16_t)offset,(int16_t)offset}; int col; bit_state_t BS; set_bit_state(&BS, (uint8_t*)ID->data + HUF->row_offsets.element[row]); for (col = 0; col < ID->columns; col++) { int color; for (color = 0; color < 3; color++) { uint16_t c_fix; c[color] += get_huffman_diff(&BS, &HUF->tree); if (c[color] < 0) { c_fix = 0; if (c[color] < *minimum) *minimum = c[color]; } else { c_fix = c[color]; } switch (ID->type_format) { case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: HUF->x3rgb16.data[3*(row*ID->columns + col) + color] = (uint16_t)c_fix; break; case X3F_IMAGE_THUMB_HUFFMAN: HUF->rgb8.data[3*(row*ID->columns + col) + color] = (uint8_t)c_fix; break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } } } } static void huffman_decode(x3f_info_t *I, x3f_directory_entry_t *DE, int bits) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; int row; int minimum = 0; int offset = legacy_offset; for (row = 0; row < ID->rows; row++) huffman_decode_row(I, DE, bits, row, offset, &minimum); if (auto_legacy_offset && minimum < 0) { offset = -minimum; for (row = 0; row < ID->rows; row++) huffman_decode_row(I, DE, bits, row, offset, &minimum); } } static int32_t get_simple_diff(x3f_huffman_t *HUF, uint16_t index) { if (HUF->mapping.size == 0) return index; else return HUF->mapping.element[index]; } static void simple_decode_row(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int row, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = ID->huffman; uint32_t *data = (uint32_t *)((unsigned char*)ID->data + row*row_stride); uint16_t c[3] = {0,0,0}; int col; uint32_t mask = 0; switch (bits) { case 8: mask = 0x0ff; break; case 9: mask = 0x1ff; break; case 10: mask = 0x3ff; break; case 11: mask = 0x7ff; break; case 12: mask = 0xfff; break; default: mask = 0; /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; break; } for (col = 0; col < ID->columns; col++) { int color; uint32_t val = data[col]; for (color = 0; color < 3; color++) { uint16_t c_fix; c[color] += get_simple_diff(HUF, (val>>(color*bits))&mask); switch (ID->type_format) { case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: c_fix = (int16_t)c[color] > 0 ? c[color] : 0; HUF->x3rgb16.data[3*(row*ID->columns + col) + color] = c_fix; break; case X3F_IMAGE_THUMB_HUFFMAN: c_fix = (int8_t)c[color] > 0 ? c[color] : 0; HUF->rgb8.data[3*(row*ID->columns + col) + color] = c_fix; break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } } } } static void simple_decode(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; int row; for (row = 0; row < ID->rows; row++) simple_decode_row(I, DE, bits, row, row_stride); } /* --------------------------------------------------------------------- */ /* Loading the data in a directory entry */ /* --------------------------------------------------------------------- */ /* First you set the offset to where to start reading the data ... */ static void read_data_set_offset(x3f_info_t *I, x3f_directory_entry_t *DE, uint32_t header_size) { uint32_t i_off = DE->input.offset + header_size; I->input.file->seek(i_off, SEEK_SET); } /* ... then you read the data, block for block */ static uint32_t read_data_block(void **data, x3f_info_t *I, x3f_directory_entry_t *DE, uint32_t footer) { INT64 fpos = I->input.file->tell(); uint32_t size = DE->input.size + DE->input.offset - fpos - footer; if (fpos + size > I->input.file->size()) throw LIBRAW_EXCEPTION_IO_CORRUPT; *data = (void *)malloc(size); GETN(*data, size); return size; } static uint32_t data_block_size(void **data, x3f_info_t *I, x3f_directory_entry_t *DE, uint32_t footer) { uint32_t size = DE->input.size + DE->input.offset - I->input.file->tell() - footer; return size; } static void x3f_load_image_verbatim(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, 0); } static int32_t x3f_load_image_verbatim_size(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; return data_block_size(&ID->data, I, DE, 0); } static void x3f_load_property_list(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_property_list_t *PL = &DEH->data_subsection.property_list; int i; read_data_set_offset(I, DE, X3F_PROPERTY_LIST_HEADER_SIZE); GET_PROPERTY_TABLE(PL->property_table, PL->num_properties); if (!PL->data_size) PL->data_size = read_data_block(&PL->data, I, DE, 0); for (i=0; i<PL->num_properties; i++) { x3f_property_t *P = &PL->property_table.element[i]; P->name = ((utf16_t *)PL->data + P->name_offset); P->value = ((utf16_t *)PL->data + P->value_offset); P->name_utf8 = 0;// utf16le_to_utf8(P->name); P->value_utf8 = 0;//utf16le_to_utf8(P->value); } } static void x3f_load_true(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_true_t *TRU = new_true(&ID->tru); x3f_quattro_t *Q = NULL; int i; if (ID->type_format == X3F_IMAGE_RAW_QUATTRO || ID->type_format == X3F_IMAGE_RAW_SDQ || ID->type_format == X3F_IMAGE_RAW_SDQH || ID->type_format == X3F_IMAGE_RAW_SDQH2 ) { Q = new_quattro(&ID->quattro); for (i=0; i<TRUE_PLANES; i++) { GET2(Q->plane[i].columns); GET2(Q->plane[i].rows); } if (Q->plane[0].rows == ID->rows/2) { Q->quattro_layout = 1; } else if (Q->plane[0].rows == ID->rows) { Q->quattro_layout = 0; } else { throw LIBRAW_EXCEPTION_IO_CORRUPT; } } /* Read TRUE header data */ GET2(TRU->seed[0]); GET2(TRU->seed[1]); GET2(TRU->seed[2]); GET2(TRU->unknown); GET_TRUE_HUFF_TABLE(TRU->table); if (ID->type_format == X3F_IMAGE_RAW_QUATTRO ||ID->type_format == X3F_IMAGE_RAW_SDQ ||ID->type_format == X3F_IMAGE_RAW_SDQH ||ID->type_format == X3F_IMAGE_RAW_SDQH2 ) { GET4(Q->unknown); } GET_TABLE(TRU->plane_size, GET4, TRUE_PLANES,uint32_t); /* Read image data */ if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, 0); /* TODO: can it be fewer than 8 bits? Maybe taken from TRU->table? */ new_huffman_tree(&TRU->tree, 8); populate_true_huffman_tree(&TRU->tree, &TRU->table); #ifdef DBG_PRNT print_huffman_tree(TRU->tree.nodes, 0, 0); #endif TRU->plane_address[0] = (uint8_t*)ID->data; for (i=1; i<TRUE_PLANES; i++) TRU->plane_address[i] = TRU->plane_address[i-1] + (((TRU->plane_size.element[i-1] + 15) / 16) * 16); if ( (ID->type_format == X3F_IMAGE_RAW_QUATTRO || ID->type_format == X3F_IMAGE_RAW_SDQ || ID->type_format == X3F_IMAGE_RAW_SDQH || ID->type_format == X3F_IMAGE_RAW_SDQH2 ) && Q->quattro_layout) { uint32_t columns = Q->plane[0].columns; uint32_t rows = Q->plane[0].rows; uint32_t channels = 3; uint32_t size = columns * rows * channels; TRU->x3rgb16.columns = columns; TRU->x3rgb16.rows = rows; TRU->x3rgb16.channels = channels; TRU->x3rgb16.row_stride = columns * channels; TRU->x3rgb16.buf = malloc(sizeof(uint16_t)*size); TRU->x3rgb16.data = (uint16_t *) TRU->x3rgb16.buf; columns = Q->plane[2].columns; rows = Q->plane[2].rows; channels = 1; size = columns * rows * channels; Q->top16.columns = columns; Q->top16.rows = rows; Q->top16.channels = channels; Q->top16.row_stride = columns * channels; Q->top16.buf = malloc(sizeof(uint16_t)*size); Q->top16.data = (uint16_t *)Q->top16.buf; } else { uint32_t size = ID->columns * ID->rows * 3; TRU->x3rgb16.columns = ID->columns; TRU->x3rgb16.rows = ID->rows; TRU->x3rgb16.channels = 3; TRU->x3rgb16.row_stride = ID->columns * 3; TRU->x3rgb16.buf =malloc(sizeof(uint16_t)*size); TRU->x3rgb16.data = (uint16_t *)TRU->x3rgb16.buf; } true_decode(I, DE); } static void x3f_load_huffman_compressed(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int use_map_table) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = ID->huffman; int table_size = 1<<bits; int row_offsets_size = ID->rows * sizeof(HUF->row_offsets.element[0]); GET_TABLE(HUF->table, GET4, table_size,uint32_t); if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, row_offsets_size); GET_TABLE(HUF->row_offsets, GET4, ID->rows,uint32_t); new_huffman_tree(&HUF->tree, bits); populate_huffman_tree(&HUF->tree, &HUF->table, &HUF->mapping); huffman_decode(I, DE, bits); } static void x3f_load_huffman_not_compressed(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int use_map_table, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, 0); simple_decode(I, DE, bits, row_stride); } static void x3f_load_huffman(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int use_map_table, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = new_huffman(&ID->huffman); uint32_t size; if (use_map_table) { int table_size = 1<<bits; GET_TABLE(HUF->mapping, GET2, table_size,uint16_t); } switch (ID->type_format) { case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: size = ID->columns * ID->rows * 3; HUF->x3rgb16.columns = ID->columns; HUF->x3rgb16.rows = ID->rows; HUF->x3rgb16.channels = 3; HUF->x3rgb16.row_stride = ID->columns * 3; HUF->x3rgb16.buf = malloc(sizeof(uint16_t)*size); HUF->x3rgb16.data = (uint16_t *)HUF->x3rgb16.buf; break; case X3F_IMAGE_THUMB_HUFFMAN: size = ID->columns * ID->rows * 3; HUF->rgb8.columns = ID->columns; HUF->rgb8.rows = ID->rows; HUF->rgb8.channels = 3; HUF->rgb8.row_stride = ID->columns * 3; HUF->rgb8.buf = malloc(sizeof(uint8_t)*size); HUF->rgb8.data = (uint8_t *)HUF->rgb8.buf; break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } if (row_stride == 0) return x3f_load_huffman_compressed(I, DE, bits, use_map_table); else return x3f_load_huffman_not_compressed(I, DE, bits, use_map_table, row_stride); } static void x3f_load_pixmap(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_load_image_verbatim(I, DE); } static uint32_t x3f_load_pixmap_size(x3f_info_t *I, x3f_directory_entry_t *DE) { return x3f_load_image_verbatim_size(I, DE); } static void x3f_load_jpeg(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_load_image_verbatim(I, DE); } static uint32_t x3f_load_jpeg_size(x3f_info_t *I, x3f_directory_entry_t *DE) { return x3f_load_image_verbatim_size(I, DE); } static void x3f_load_image(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; read_data_set_offset(I, DE, X3F_IMAGE_HEADER_SIZE); switch (ID->type_format) { case X3F_IMAGE_RAW_TRUE: case X3F_IMAGE_RAW_MERRILL: case X3F_IMAGE_RAW_QUATTRO: case X3F_IMAGE_RAW_SDQ: case X3F_IMAGE_RAW_SDQH: case X3F_IMAGE_RAW_SDQH2: x3f_load_true(I, DE); break; case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: x3f_load_huffman(I, DE, 10, 1, ID->row_stride); break; case X3F_IMAGE_THUMB_PLAIN: x3f_load_pixmap(I, DE); break; case X3F_IMAGE_THUMB_HUFFMAN: x3f_load_huffman(I, DE, 8, 0, ID->row_stride); break; case X3F_IMAGE_THUMB_JPEG: x3f_load_jpeg(I, DE); break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } } // Used only for thumbnail size estimation static uint32_t x3f_load_image_size(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; read_data_set_offset(I, DE, X3F_IMAGE_HEADER_SIZE); switch (ID->type_format) { case X3F_IMAGE_THUMB_PLAIN: return x3f_load_pixmap_size(I, DE); case X3F_IMAGE_THUMB_JPEG: return x3f_load_jpeg_size(I, DE); break; default: return 0; } } static void x3f_load_camf_decode_type2(x3f_camf_t *CAMF) { uint32_t key = CAMF->t2.crypt_key; int i; CAMF->decoded_data_size = CAMF->data_size; CAMF->decoded_data = malloc(CAMF->decoded_data_size); for (i=0; i<CAMF->data_size; i++) { uint8_t old, _new; uint32_t tmp; old = ((uint8_t *)CAMF->data)[i]; key = (key * 1597 + 51749) % 244944; tmp = (uint32_t)(key * ((int64_t)301593171) >> 24); _new = (uint8_t)(old ^ (uint8_t)(((((key << 8) - tmp) >> 1) + tmp) >> 17)); ((uint8_t *)CAMF->decoded_data)[i] = _new; } } /* NOTE: the unpacking in this code is in big respects identical to true_decode_one_color(). The difference is in the output you build. It might be possible to make some parts shared. NOTE ALSO: This means that the meta data is obfuscated using an image compression algorithm. */ static void camf_decode_type4(x3f_camf_t *CAMF) { uint32_t seed = CAMF->t4.decode_bias; int row; uint8_t *dst; uint32_t dst_size = CAMF->t4.decoded_data_size; uint8_t *dst_end; bool_t odd_dst = 0; x3f_hufftree_t *tree = &CAMF->tree; bit_state_t BS; int32_t row_start_acc[2][2]; uint32_t rows = CAMF->t4.block_count; uint32_t cols = CAMF->t4.block_size; CAMF->decoded_data_size = dst_size; CAMF->decoded_data = malloc(CAMF->decoded_data_size); memset(CAMF->decoded_data, 0, CAMF->decoded_data_size); dst = (uint8_t *)CAMF->decoded_data; dst_end = dst + dst_size; set_bit_state(&BS, CAMF->decoding_start); row_start_acc[0][0] = seed; row_start_acc[0][1] = seed; row_start_acc[1][0] = seed; row_start_acc[1][1] = seed; for (row = 0; row < rows; row++) { int col; bool_t odd_row = row&1; int32_t acc[2]; /* We loop through all the columns and the rows. But the actual data is smaller than that, so we break the loop when reaching the end. */ for (col = 0; col < cols; col++) { bool_t odd_col = col&1; int32_t diff = get_true_diff(&BS, tree); int32_t prev = col < 2 ? row_start_acc[odd_row][odd_col] : acc[odd_col]; int32_t value = prev + diff; acc[odd_col] = value; if (col < 2) row_start_acc[odd_row][odd_col] = value; switch(odd_dst) { case 0: *dst++ = (uint8_t)((value>>4)&0xff); if (dst >= dst_end) { goto ready; } *dst = (uint8_t)((value<<4)&0xf0); break; case 1: *dst++ |= (uint8_t)((value>>8)&0x0f); if (dst >= dst_end) { goto ready; } *dst++ = (uint8_t)((value<<0)&0xff); if (dst >= dst_end) { goto ready; } break; } odd_dst = !odd_dst; } /* end col */ } /* end row */ ready:; } static void x3f_load_camf_decode_type4(x3f_camf_t *CAMF) { int i; uint8_t *p; x3f_true_huffman_element_t *element = NULL; for (i=0, p = (uint8_t*)CAMF->data; *p != 0; i++) { /* TODO: Is this too expensive ??*/ element = (x3f_true_huffman_element_t *)realloc(element, (i+1)*sizeof(*element)); element[i].code_size = *p++; element[i].code = *p++; } CAMF->table.size = i; CAMF->table.element = element; /* TODO: where does the values 28 and 32 come from? */ #define CAMF_T4_DATA_SIZE_OFFSET 28 #define CAMF_T4_DATA_OFFSET 32 CAMF->decoding_size = *(uint32_t *)((unsigned char*)CAMF->data + CAMF_T4_DATA_SIZE_OFFSET); CAMF->decoding_start = (uint8_t *)CAMF->data + CAMF_T4_DATA_OFFSET; /* TODO: can it be fewer than 8 bits? Maybe taken from TRU->table? */ new_huffman_tree(&CAMF->tree, 8); populate_true_huffman_tree(&CAMF->tree, &CAMF->table); #ifdef DBG_PRNT print_huffman_tree(CAMF->tree.nodes, 0, 0); #endif camf_decode_type4(CAMF); } static void camf_decode_type5(x3f_camf_t *CAMF) { int32_t acc = CAMF->t5.decode_bias; uint8_t *dst; x3f_hufftree_t *tree = &CAMF->tree; bit_state_t BS; int32_t i; CAMF->decoded_data_size = CAMF->t5.decoded_data_size; CAMF->decoded_data = malloc(CAMF->decoded_data_size); dst = (uint8_t *)CAMF->decoded_data; set_bit_state(&BS, CAMF->decoding_start); for (i = 0; i < CAMF->decoded_data_size; i++) { int32_t diff = get_true_diff(&BS, tree); acc = acc + diff; *dst++ = (uint8_t)(acc & 0xff); } } static void x3f_load_camf_decode_type5(x3f_camf_t *CAMF) { int i; uint8_t *p; x3f_true_huffman_element_t *element = NULL; for (i=0, p = (uint8_t*)CAMF->data; *p != 0; i++) { /* TODO: Is this too expensive ??*/ element = (x3f_true_huffman_element_t *)realloc(element, (i+1)*sizeof(*element)); element[i].code_size = *p++; element[i].code = *p++; } CAMF->table.size = i; CAMF->table.element = element; /* TODO: where does the values 28 and 32 come from? */ #define CAMF_T5_DATA_SIZE_OFFSET 28 #define CAMF_T5_DATA_OFFSET 32 CAMF->decoding_size = *(uint32_t *)((uint8_t*)CAMF->data + CAMF_T5_DATA_SIZE_OFFSET); CAMF->decoding_start = (uint8_t *)CAMF->data + CAMF_T5_DATA_OFFSET; /* TODO: can it be fewer than 8 bits? Maybe taken from TRU->table? */ new_huffman_tree(&CAMF->tree, 8); populate_true_huffman_tree(&CAMF->tree, &CAMF->table); #ifdef DBG_PRNT print_huffman_tree(CAMF->tree.nodes, 0, 0); #endif camf_decode_type5(CAMF); } static void x3f_setup_camf_text_entry(camf_entry_t *entry) { entry->text_size = *(uint32_t *)entry->value_address; entry->text = (char*)entry->value_address + 4; } static void x3f_setup_camf_property_entry(camf_entry_t *entry) { int i; uint8_t *e = (uint8_t*)entry->entry; uint8_t *v = (uint8_t*)entry->value_address; uint32_t num = entry->property_num = *(uint32_t *)v; uint32_t off = *(uint32_t *)(v + 4); entry->property_name = (char **)malloc(num*sizeof(uint8_t*)); entry->property_value = (uint8_t **)malloc(num*sizeof(uint8_t*)); for (i=0; i<num; i++) { uint32_t name_off = off + *(uint32_t *)(v + 8 + 8*i); uint32_t value_off = off + *(uint32_t *)(v + 8 + 8*i + 4); entry->property_name[i] = (char *)(e + name_off); entry->property_value[i] = e + value_off; } } static void set_matrix_element_info(uint32_t type, uint32_t *size, matrix_type_t *decoded_type) { switch (type) { case 0: *size = 2; *decoded_type = M_INT; /* known to be true */ break; case 1: *size = 4; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; case 2: *size = 4; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; case 3: *size = 4; *decoded_type = M_FLOAT; /* known to be true */ break; case 5: *size = 1; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; case 6: *size = 2; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } } static void get_matrix_copy(camf_entry_t *entry) { uint32_t element_size = entry->matrix_element_size; uint32_t elements = entry->matrix_elements; int i, size = (entry->matrix_decoded_type==M_FLOAT ? sizeof(double) : sizeof(uint32_t)) * elements; entry->matrix_decoded = malloc(size); switch (element_size) { case 4: switch (entry->matrix_decoded_type) { case M_INT: case M_UINT: memcpy(entry->matrix_decoded, entry->matrix_data, size); break; case M_FLOAT: for (i=0; i<elements; i++) ((double *)entry->matrix_decoded)[i] = (double)((float *)entry->matrix_data)[i]; break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } break; case 2: switch (entry->matrix_decoded_type) { case M_INT: for (i=0; i<elements; i++) ((int32_t *)entry->matrix_decoded)[i] = (int32_t)((int16_t *)entry->matrix_data)[i]; break; case M_UINT: for (i=0; i<elements; i++) ((uint32_t *)entry->matrix_decoded)[i] = (uint32_t)((uint16_t *)entry->matrix_data)[i]; break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } break; case 1: switch (entry->matrix_decoded_type) { case M_INT: for (i=0; i<elements; i++) ((int32_t *)entry->matrix_decoded)[i] = (int32_t)((int8_t *)entry->matrix_data)[i]; break; case M_UINT: for (i=0; i<elements; i++) ((uint32_t *)entry->matrix_decoded)[i] = (uint32_t)((uint8_t *)entry->matrix_data)[i]; break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } } static void x3f_setup_camf_matrix_entry(camf_entry_t *entry) { int i; int totalsize = 1; uint8_t *e = (uint8_t *)entry->entry; uint8_t *v = (uint8_t *)entry->value_address; uint32_t type = entry->matrix_type = *(uint32_t *)(v + 0); uint32_t dim = entry->matrix_dim = *(uint32_t *)(v + 4); uint32_t off = entry->matrix_data_off = *(uint32_t *)(v + 8); camf_dim_entry_t *dentry = entry->matrix_dim_entry = (camf_dim_entry_t*)malloc(dim*sizeof(camf_dim_entry_t)); for (i=0; i<dim; i++) { uint32_t size = dentry[i].size = *(uint32_t *)(v + 12 + 12*i + 0); dentry[i].name_offset = *(uint32_t *)(v + 12 + 12*i + 4); dentry[i].n = *(uint32_t *)(v + 12 + 12*i + 8); dentry[i].name = (char *)(e + dentry[i].name_offset); if (dentry[i].n != i) { } totalsize *= size; } set_matrix_element_info(type, &entry->matrix_element_size, &entry->matrix_decoded_type); entry->matrix_data = (void *)(e + off); entry->matrix_elements = totalsize; entry->matrix_used_space = entry->entry_size - off; /* This estimate only works for matrices above a certain size */ entry->matrix_estimated_element_size = entry->matrix_used_space / totalsize; get_matrix_copy(entry); } static void x3f_setup_camf_entries(x3f_camf_t *CAMF) { uint8_t *p = (uint8_t *)CAMF->decoded_data; uint8_t *end = p + CAMF->decoded_data_size; camf_entry_t *entry = NULL; int i; for (i=0; p < end; i++) { uint32_t *p4 = (uint32_t *)p; switch (*p4) { case X3F_CMbP: case X3F_CMbT: case X3F_CMbM: break; default: goto stop; } /* TODO: lots of realloc - may be inefficient */ entry = (camf_entry_t *)realloc(entry, (i+1)*sizeof(camf_entry_t)); /* Pointer */ entry[i].entry = p; /* Header */ entry[i].id = *p4++; entry[i].version = *p4++; entry[i].entry_size = *p4++; entry[i].name_offset = *p4++; entry[i].value_offset = *p4++; /* Compute adresses and sizes */ entry[i].name_address = (char *)(p + entry[i].name_offset); entry[i].value_address = p + entry[i].value_offset; entry[i].name_size = entry[i].value_offset - entry[i].name_offset; entry[i].value_size = entry[i].entry_size - entry[i].value_offset; entry[i].text_size = 0; entry[i].text = NULL; entry[i].property_num = 0; entry[i].property_name = NULL; entry[i].property_value = NULL; entry[i].matrix_type = 0; entry[i].matrix_dim = 0; entry[i].matrix_data_off = 0; entry[i].matrix_data = NULL; entry[i].matrix_dim_entry = NULL; entry[i].matrix_decoded = NULL; switch (entry[i].id) { case X3F_CMbP: x3f_setup_camf_property_entry(&entry[i]); break; case X3F_CMbT: x3f_setup_camf_text_entry(&entry[i]); break; case X3F_CMbM: x3f_setup_camf_matrix_entry(&entry[i]); break; } p += entry[i].entry_size; } stop: CAMF->entry_table.size = i; CAMF->entry_table.element = entry; } static void x3f_load_camf(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_camf_t *CAMF = &DEH->data_subsection.camf; read_data_set_offset(I, DE, X3F_CAMF_HEADER_SIZE); if (!CAMF->data_size) CAMF->data_size = read_data_block(&CAMF->data, I, DE, 0); switch (CAMF->type) { case 2: /* Older SD9-SD14 */ x3f_load_camf_decode_type2(CAMF); break; case 4: /* TRUE ... Merrill */ x3f_load_camf_decode_type4(CAMF); break; case 5: /* Quattro ... */ x3f_load_camf_decode_type5(CAMF); break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } if (CAMF->decoded_data != NULL) x3f_setup_camf_entries(CAMF); else throw LIBRAW_EXCEPTION_IO_CORRUPT; } /* extern */ x3f_return_t x3f_load_data(x3f_t *x3f, x3f_directory_entry_t *DE) { x3f_info_t *I = &x3f->info; if (DE == NULL) return X3F_ARGUMENT_ERROR; switch (DE->header.identifier) { case X3F_SECp: x3f_load_property_list(I, DE); break; case X3F_SECi: x3f_load_image(I, DE); break; case X3F_SECc: x3f_load_camf(I, DE); break; default: return X3F_INTERNAL_ERROR; } return X3F_OK; } /* extern */ int64_t x3f_load_data_size(x3f_t *x3f, x3f_directory_entry_t *DE) { x3f_info_t *I = &x3f->info; if (DE == NULL) return -1; switch (DE->header.identifier) { case X3F_SECi: return x3f_load_image_size(I, DE); default: return 0; } } /* extern */ x3f_return_t x3f_load_image_block(x3f_t *x3f, x3f_directory_entry_t *DE) { x3f_info_t *I = &x3f->info; if (DE == NULL) return X3F_ARGUMENT_ERROR; switch (DE->header.identifier) { case X3F_SECi: read_data_set_offset(I, DE, X3F_IMAGE_HEADER_SIZE); x3f_load_image_verbatim(I, DE); break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; return X3F_INTERNAL_ERROR; } return X3F_OK; } /* --------------------------------------------------------------------- */ /* The End */ /* --------------------------------------------------------------------- */
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_94_1
crossvul-cpp_data_good_845_0
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-present Facebook, Inc. (http://www.facebook.com) | | Copyright (c) 1997-2010 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/ext/gd/ext_gd.h" #include <sys/types.h> #include <sys/stat.h> #include "hphp/runtime/base/array-init.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/comparisons.h" #include "hphp/runtime/base/plain-file.h" #include "hphp/runtime/base/request-event-handler.h" #include "hphp/runtime/base/runtime-option.h" #include "hphp/runtime/base/string-util.h" #include "hphp/runtime/base/zend-printf.h" #include "hphp/runtime/base/zend-string.h" #include "hphp/runtime/ext/std/ext_std_file.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/util/alloc.h" #include "hphp/util/rds-local.h" #include "hphp/runtime/ext/gd/libgd/gd.h" #include "hphp/runtime/ext/gd/libgd/gdfontt.h" /* 1 Tiny font */ #include "hphp/runtime/ext/gd/libgd/gdfonts.h" /* 2 Small font */ #include "hphp/runtime/ext/gd/libgd/gdfontmb.h" /* 3 Medium bold font */ #include "hphp/runtime/ext/gd/libgd/gdfontl.h" /* 4 Large font */ #include "hphp/runtime/ext/gd/libgd/gdfontg.h" /* 5 Giant font */ #include <zlib.h> #include <set> #include <folly/portability/Stdlib.h> #include <folly/portability/Unistd.h> /* Section Filters Declarations */ /* IMPORTANT NOTE FOR NEW FILTER * Do not forget to update: * IMAGE_FILTER_MAX: define the last filter index * IMAGE_FILTER_MAX_ARGS: define the biggest amount of arguments * image_filter array in PHP_FUNCTION(imagefilter) */ #define IMAGE_FILTER_NEGATE 0 #define IMAGE_FILTER_GRAYSCALE 1 #define IMAGE_FILTER_BRIGHTNESS 2 #define IMAGE_FILTER_CONTRAST 3 #define IMAGE_FILTER_COLORIZE 4 #define IMAGE_FILTER_EDGEDETECT 5 #define IMAGE_FILTER_EMBOSS 6 #define IMAGE_FILTER_GAUSSIAN_BLUR 7 #define IMAGE_FILTER_SELECTIVE_BLUR 8 #define IMAGE_FILTER_MEAN_REMOVAL 9 #define IMAGE_FILTER_SMOOTH 10 #define IMAGE_FILTER_PIXELATE 11 #define IMAGE_FILTER_MAX 11 #define IMAGE_FILTER_MAX_ARGS 6 #define IMAGE_TYPE_GIF 1 #define IMAGE_TYPE_JPEG 2 #define IMAGE_TYPE_PNG 4 #define IMAGE_TYPE_WBMP 8 #define IMAGE_TYPE_XPM 16 // #define IM_MEMORY_CHECK namespace HPHP { /////////////////////////////////////////////////////////////////////////////// #define HAS_GDIMAGESETANTIALIASED #if defined(HAS_GDIMAGEANTIALIAS) #define SetAntiAliased(gd, flag) gdImageAntialias(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #elif defined(HAS_GDIMAGESETANTIALIASED) #define SetAntiAliased(gd, flag) ((gd)->AA = (flag)) #define SetupAntiAliasedColor(gd, color) \ ((gd)->AA ? \ gdImageSetAntiAliased(im, color), gdAntiAliased : \ color) #else #define SetAntiAliased(gd, flag) #define SetupAntiAliasedColor(gd, color) (color) #endif /////////////////////////////////////////////////////////////////////////////// // sweep() { this->~Image(); } IMPLEMENT_RESOURCE_ALLOCATION(Image) void Image::reset() { if (m_gdImage) { gdImageDestroy(m_gdImage); m_gdImage = nullptr; } } Image::~Image() { reset(); } struct ImageMemoryAlloc final : RequestEventHandler { ImageMemoryAlloc() : m_mallocSize(0) {} void requestInit() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); #endif assertx(m_mallocSize == 0); m_mallocSize = 0; } void requestShutdown() override { #ifdef IM_MEMORY_CHECK void *ptrs[1000]; int n = 1000; if (m_mallocSize) imDump(ptrs, n); assertx(m_mallocSize == 0); #endif m_mallocSize = 0; } void *imMalloc(size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); if (m_mallocSize + size < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &size, sizeof(size)); m_mallocSize += size; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + size); if (!ptr) return nullptr; memcpy(ptr, &size, sizeof(size)); m_mallocSize += size; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void *imCalloc(size_t nmemb, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); size_t bytes = nmemb * size; if (m_mallocSize + bytes < (size_t)RuntimeOption::ImageMemoryMaxBytes) { #ifdef IM_MEMORY_CHECK void *ptr = local_malloc(sizeof(ln) + sizeof(size) + bytes); if (!ptr) return nullptr; memset(ptr, 0, sizeof(ln) + sizeof(size) + bytes); memcpy(ptr, &ln, sizeof(ln)); memcpy((char*)ptr + sizeof(ln), &bytes, sizeof(bytes)); m_mallocSize += bytes; m_alloced.insert(ptr); return ((char *)ptr + sizeof(ln) + sizeof(size)); #else void *ptr = local_malloc(sizeof(size) + bytes); if (!ptr) return nullptr; memcpy(ptr, &bytes, sizeof(bytes)); memset((char *)ptr + sizeof(size), 0, bytes); m_mallocSize += bytes; return ((char *)ptr + sizeof(size)); #endif } return nullptr; } void imFree(void *ptr #ifdef IM_MEMORY_CHECK , int ln #endif ) { size_t size; void *sizePtr = (char *)ptr - sizeof(size); memcpy(&size, sizePtr, sizeof(size)); m_mallocSize -= size; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); int count = m_alloced.erase((char*)sizePtr - sizeof(ln)); assertx(count == 1); // double free on failure assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(lnPtr); #else assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); local_free(sizePtr); #endif } // wrapper of realloc, the original buffer is freed on failure void *imRealloc(void *ptr, size_t size #ifdef IM_MEMORY_CHECK , int ln #endif ) { assertx(m_mallocSize < (size_t)RuntimeOption::ImageMemoryMaxBytes); #ifdef IM_MEMORY_CHECK if (!ptr) return imMalloc(size, ln); if (!size) { imFree(ptr, ln); return nullptr; } #else if (!ptr) return imMalloc(size); if (!size) { imFree(ptr); return nullptr; } #endif void *sizePtr = (char *)ptr - sizeof(size); size_t oldSize = 0; if (ptr) memcpy(&oldSize, sizePtr, sizeof(oldSize)); int diff = size - oldSize; void *tmp; #ifdef IM_MEMORY_CHECK void *lnPtr = (char *)sizePtr - sizeof(ln); if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(lnPtr, sizeof(ln) + sizeof(size) + size))) { int count = m_alloced.erase(ptr); assertx(count == 1); // double free on failure local_free(lnPtr); return nullptr; } memcpy(tmp, &ln, sizeof(ln)); memcpy((char*)tmp + sizeof(ln), &size, sizeof(size)); m_mallocSize += diff; if (tmp != lnPtr) { int count = m_alloced.erase(lnPtr); assertx(count == 1); m_alloced.insert(tmp); } return ((char *)tmp + sizeof(ln) + sizeof(size)); #else if (m_mallocSize + diff > (size_t)RuntimeOption::ImageMemoryMaxBytes || !(tmp = local_realloc(sizePtr, sizeof(size) + size))) { local_free(sizePtr); return nullptr; } memcpy(tmp, &size, sizeof(size)); m_mallocSize += diff; return ((char *)tmp + sizeof(size)); #endif } #ifdef IM_MEMORY_CHECK void imDump(void *ptrs[], int &n) { int i = 0; for (auto iter = m_alloced.begin(); iter != m_alloced.end(); ++i, ++iter) { void *p = *iter; assertx(p); if (i < n) ptrs[i] = p; int ln; size_t size; memcpy(&ln, p, sizeof(ln)); memcpy(&size, (char*)p + sizeof(ln), sizeof(size)); printf("%d: (%p, %lu)\n", ln, p, size); } n = (i < n) ? i : n; } #endif private: size_t m_mallocSize; #ifdef IM_MEMORY_CHECK std::set<void *> m_alloced; #endif }; IMPLEMENT_STATIC_REQUEST_LOCAL(ImageMemoryAlloc, s_ima); #ifdef IM_MEMORY_CHECK #define IM_MALLOC(size) s_ima->imMalloc((size), __LINE__) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size), __LINE__) #define IM_FREE(ptr) s_ima->imFree((ptr), __LINE__) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size), __LINE__) #else #define IM_MALLOC(size) s_ima->imMalloc((size)) #define IM_CALLOC(nmemb, size) s_ima->imCalloc((nmemb), (size)) #define IM_FREE(ptr) s_ima->imFree((ptr)) #define IM_REALLOC(ptr, size) s_ima->imRealloc((ptr), (size)) #endif #define CHECK_BUFFER(begin, end, size) \ do { \ if (((char*)end) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d)", \ __FUNCTION__, __LINE__, begin, end, size); \ return; \ } \ } while (0) #define CHECK_BUFFER_R(begin, end, size, retcod) \ do { \ if (((char*)(end)) - ((char*)(begin)) < (size)) { \ raise_warning("%s/%d: Buffer overrun (%p, %p, %d, %d)", \ __FUNCTION__, __LINE__, begin, end, size, retcod); \ return retcod; \ } \ } while (0) #define CHECK_ALLOC(ptr, size) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return; \ } \ } while (0) #define CHECK_ALLOC_R(ptr, size, retcod) \ do { \ if (!(ptr)) { \ raise_warning("%s/%d: failed to allocate %lu bytes", \ __FUNCTION__, __LINE__, ((size_t)(size))); \ return retcod; \ } \ } while (0) // original Zend name is _estrndup static char *php_strndup_impl(const char* s, uint32_t length #ifdef IM_MEMORY_CHECK , int ln #endif ) { char *p; #ifdef IM_MEMORY_CHECK p = (char *)s_ima->imMalloc((length+1), ln); #else p = (char *)s_ima->imMalloc((length+1)); #endif CHECK_ALLOC_R(p, length+1, nullptr); memcpy(p, s, length); p[length] = 0; return p; } static char *php_strdup_impl(const char* s #ifdef IM_MEMORY_CHECK , int ln #endif ) { #ifdef IM_MEMORY_CHECK return php_strndup_impl(s, strlen(s), ln); #else return php_strndup_impl(s, strlen(s)); #endif } #ifdef IM_MEMORY_CHECK #define PHP_STRNDUP(var, s, length) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strndup_impl((s), (length), __LINE__); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) s_ima->imFree((var), __LINE__); \ (var) = php_strdup_impl(s, __LINE__); \ } while (0) #else #define PHP_STRNDUP(var, s, length) \ do { \ if (var) IM_FREE(var); \ (var) = php_strndup_impl((s), (length)); \ } while (0) #define PHP_STRDUP(var, s) \ do { \ if (var) IM_FREE(var); \ (var) = php_strdup_impl(s); \ } while (0) #endif typedef enum { IMAGE_FILETYPE_UNKNOWN=0, IMAGE_FILETYPE_GIF=1, IMAGE_FILETYPE_JPEG, IMAGE_FILETYPE_PNG, IMAGE_FILETYPE_SWF, IMAGE_FILETYPE_PSD, IMAGE_FILETYPE_BMP, IMAGE_FILETYPE_TIFF_II, /* intel */ IMAGE_FILETYPE_TIFF_MM, /* motorola */ IMAGE_FILETYPE_JPC, IMAGE_FILETYPE_JP2, IMAGE_FILETYPE_JPX, IMAGE_FILETYPE_JB2, IMAGE_FILETYPE_SWC, IMAGE_FILETYPE_IFF, IMAGE_FILETYPE_WBMP, /* IMAGE_FILETYPE_JPEG2000 is a userland alias for IMAGE_FILETYPE_JPC */ IMAGE_FILETYPE_XBM, IMAGE_FILETYPE_ICO, IMAGE_FILETYPE_COUNT /* Must remain last */ } image_filetype; // PHP extension STANDARD: image.c /* file type markers */ static const char php_sig_gif[3] = {'G', 'I', 'F'}; static const char php_sig_psd[4] = {'8', 'B', 'P', 'S'}; static const char php_sig_bmp[2] = {'B', 'M'}; static const char php_sig_swf[3] = {'F', 'W', 'S'}; static const char php_sig_swc[3] = {'C', 'W', 'S'}; static const char php_sig_jpg[3] = {(char) 0xff, (char) 0xd8, (char) 0xff}; static const char php_sig_png[8] = {(char) 0x89, (char) 0x50, (char) 0x4e, (char) 0x47, (char) 0x0d, (char) 0x0a, (char) 0x1a, (char) 0x0a}; static const char php_sig_tif_ii[4] = {'I','I', (char)0x2A, (char)0x00}; static const char php_sig_tif_mm[4] = {'M','M', (char)0x00, (char)0x2A}; static const char php_sig_jpc[3] = {(char)0xff, (char)0x4f, (char)0xff}; static const char php_sig_jp2[12] = {(char)0x00, (char)0x00, (char)0x00, (char)0x0c, (char)0x6a, (char)0x50, (char)0x20, (char)0x20, (char)0x0d, (char)0x0a, (char)0x87, (char)0x0a}; static const char php_sig_iff[4] = {'F','O','R','M'}; static const char php_sig_ico[4] = {(char)0x00, (char)0x00, (char)0x01, (char)0x00}; static struct gfxinfo *php_handle_gif(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(3, SEEK_CUR)) return nullptr; String dim = stream->read(5); if (dim.length() != 5) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->width = (unsigned int)s[0] | (((unsigned int)s[1])<<8); result->height = (unsigned int)s[2] | (((unsigned int)s[3])<<8); result->bits = s[4]&0x80 ? ((((unsigned int)s[4])&0x07) + 1) : 0; result->channels = 3; /* always */ return result; } static struct gfxinfo *php_handle_psd(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(8); if (dim.length() != 8) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); result->height = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->width = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); return result; } static struct gfxinfo *php_handle_bmp(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int size; if (!stream->seek(11, SEEK_CUR)) return nullptr; String dim = stream->read(16); if (dim.length() != 16) return nullptr; s = (unsigned char *)dim.c_str(); size = (((unsigned int)s[3]) << 24) + (((unsigned int)s[2]) << 16) + (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (size == 12) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); result->bits = ((unsigned int)s[11]); } else if (size > 12 && (size <= 64 || size == 108 || size == 124)) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof(struct gfxinfo), nullptr); result->width = (((unsigned int)s[7]) << 24) + (((unsigned int)s[6]) << 16) + (((unsigned int)s[5]) << 8) + ((unsigned int)s[4]); result->height = (((unsigned int)s[11]) << 24) + (((unsigned int)s[10]) << 16) + (((unsigned int)s[9]) << 8) + ((unsigned int)s[8]); result->height = abs((int32_t)result->height); result->bits = (((unsigned int)s[15]) << 8) + ((unsigned int)s[14]); } else { return nullptr; } return result; } static unsigned long int php_swf_get_bits(unsigned char* buffer, unsigned int pos, unsigned int count) { unsigned int loop; unsigned long int result = 0; for (loop = pos; loop < pos + count; loop++) { result = result + ((((buffer[loop / 8]) >> (7 - (loop % 8))) & 0x01) << (count - (loop - pos) - 1)); } return result; } static struct gfxinfo *php_handle_swc(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned long len=64, szlength; int factor=1,maxfactor=16; int slength, status=0; unsigned char *b, *buf=nullptr; String bufz; String tmp; b = (unsigned char *)IM_CALLOC(1, len + 1); CHECK_ALLOC_R(b, (len + 1), nullptr); if (!stream->seek(5, SEEK_CUR)) { IM_FREE(b); return nullptr; } String a = stream->read(64); if (a.length() != 64) { IM_FREE(b); return nullptr; } if (uncompress((Bytef*)b, &len, (const Bytef*)a.c_str(), 64) != Z_OK) { /* failed to decompress the file, will try reading the rest of the file */ if (!stream->seek(8, SEEK_SET)) { IM_FREE(b); return nullptr; } while (!(tmp = stream->read(8192)).empty()) { bufz += tmp; } slength = bufz.length(); /* * zlib::uncompress() wants to know the output data length * if none was given as a parameter * we try from input length * 2 up to input length * 2^8 * doubling it whenever it wasn't big enough * that should be eneugh for all real life cases */ do { szlength=slength*(1<<factor++); buf = (unsigned char *) IM_REALLOC(buf,szlength); if (!buf) IM_FREE(b); CHECK_ALLOC_R(buf, szlength, nullptr); status = uncompress((Bytef*)buf, &szlength, (const Bytef*)bufz.c_str(), slength); } while ((status==Z_BUF_ERROR)&&(factor<maxfactor)); if (status == Z_OK) { memcpy(b, buf, len); } if (buf) { IM_FREE(buf); } } if (!status) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); if (!result) IM_FREE(b); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (b, 0, 5); result->width = (php_swf_get_bits (b, 5 + bits, bits) - php_swf_get_bits (b, 5, bits)) / 20; result->height = (php_swf_get_bits (b, 5 + (3 * bits), bits) - php_swf_get_bits (b, 5 + (2 * bits), bits)) / 20; } else { result = nullptr; } IM_FREE(b); return result; } static struct gfxinfo *php_handle_swf(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; long bits; unsigned char *a; if (!stream->seek(5, SEEK_CUR)) return nullptr; String str = stream->read(32); if (str.length() != 32) return nullptr; a = (unsigned char *)str.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof (struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); bits = php_swf_get_bits (a, 0, 5); result->width = (php_swf_get_bits (a, 5 + bits, bits) - php_swf_get_bits (a, 5, bits)) / 20; result->height = (php_swf_get_bits (a, 5 + (3 * bits), bits) - php_swf_get_bits (a, 5 + (2 * bits), bits)) / 20; result->bits = 0; result->channels = 0; return result; } static struct gfxinfo *php_handle_png(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; /* Width: 4 bytes * Height: 4 bytes * Bit depth: 1 byte * Color type: 1 byte * Compression method: 1 byte * Filter method: 1 byte * Interlace method: 1 byte */ if (!stream->seek(8, SEEK_CUR)) return nullptr; String dim = stream->read(9); if (dim.length() < 9) return nullptr; s = (unsigned char *)dim.c_str(); result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = (((unsigned int)s[0]) << 24) + (((unsigned int)s[1]) << 16) + (((unsigned int)s[2]) << 8) + ((unsigned int)s[3]); result->height = (((unsigned int)s[4]) << 24) + (((unsigned int)s[5]) << 16) + (((unsigned int)s[6]) << 8) + ((unsigned int)s[7]); result->bits = (unsigned int)s[8]; return result; } /* routines to handle JPEG data */ /* some defines for the different JPEG block types */ #define M_SOF0 0xC0 /* Start Of Frame N */ #define M_SOF1 0xC1 /* N indicates which compression process */ #define M_SOF2 0xC2 /* Only SOF0-SOF2 are now in common use */ #define M_SOF3 0xC3 #define M_SOF5 0xC5 /* NB: codes C4 and CC are NOT SOF markers */ #define M_SOF6 0xC6 #define M_SOF7 0xC7 #define M_SOF9 0xC9 #define M_SOF10 0xCA #define M_SOF11 0xCB #define M_SOF13 0xCD #define M_SOF14 0xCE #define M_SOF15 0xCF #define M_SOI 0xD8 #define M_EOI 0xD9 /* End Of Image (end of datastream) */ #define M_SOS 0xDA /* Start Of Scan (begins compressed data) */ #define M_APP0 0xe0 #define M_APP1 0xe1 #define M_APP2 0xe2 #define M_APP3 0xe3 #define M_APP4 0xe4 #define M_APP5 0xe5 #define M_APP6 0xe6 #define M_APP7 0xe7 #define M_APP8 0xe8 #define M_APP9 0xe9 #define M_APP10 0xea #define M_APP11 0xeb #define M_APP12 0xec #define M_APP13 0xed #define M_APP14 0xee #define M_APP15 0xef #define M_COM 0xFE /* COMment */ #define M_PSEUDO 0xFFD8 /* pseudo marker for start of image(byte 0) */ #define M_EXIF 0xE1 /* Exif Attribute Information */ static unsigned short php_read2(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(2); /* just return 0 if we hit the end-of-file */ if (str.length() != 2) return 0; a = (unsigned char *)str.c_str(); return (((unsigned short)a[0]) << 8) + ((unsigned short)a[1]); } static unsigned int php_next_marker(const req::ptr<File>& file, int /*last_marker*/, int ff_read) { int a=0, marker; // get marker byte, swallowing possible padding if (!ff_read) { size_t extraneous = 0; while ((marker = file->getc()) != 0xff) { if (marker == EOF) { return M_EOI;/* we hit EOF */ } extraneous++; } if (extraneous) { raise_warning("corrupt JPEG data: %zu extraneous bytes before marker", extraneous); } } a = 1; do { if ((marker = file->getc()) == EOF) { return M_EOI;/* we hit EOF */ } ++a; } while (marker == 0xff); if (a < 2) { return M_EOI; /* at least one 0xff is needed before marker code */ } return (unsigned int)marker; } static int php_skip_variable(const req::ptr<File>& stream) { off_t length = (unsigned int)php_read2(stream); if (length < 2) { return 0; } length = length - 2; stream->seek(length, SEEK_CUR); return 1; } static int php_read_APP(const req::ptr<File>& stream, unsigned int marker, Array& info) { unsigned short length; unsigned char markername[16]; length = php_read2(stream); if (length < 2) { return 0; } length -= 2; /* length includes itself */ String buffer = stream->read(length); if (buffer.empty()) { return 0; } snprintf((char*)markername, sizeof(markername), "APP%d", marker - M_APP0); if (!info.exists(String((const char *)markername))) { /* XXX we only catch the 1st tag of it's kind! */ info.set(String((char*)markername, CopyString), buffer); } return 1; } static struct gfxinfo *php_handle_jpeg(const req::ptr<File>& file, Array& info) { struct gfxinfo *result = nullptr; unsigned int marker = M_PSEUDO; unsigned short length, ff_read=1; for (;;) { marker = php_next_marker(file, marker, ff_read); ff_read = 0; switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if (result == nullptr) { /* handle SOFn block */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); length = php_read2(file); result->bits = file->getc(); result->height = php_read2(file); result->width = php_read2(file); result->channels = file->getc(); if (info.isNull() || length < 8) { /* if we don't want an extanded info -> return */ return result; } if (!file->seek(length - 8, SEEK_CUR)) { /* file error after info */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_APP0: case M_APP1: case M_APP2: case M_APP3: case M_APP4: case M_APP5: case M_APP6: case M_APP7: case M_APP8: case M_APP9: case M_APP10: case M_APP11: case M_APP12: case M_APP13: case M_APP14: case M_APP15: if (!info.isNull()) { if (!php_read_APP(file, marker, info)) { /* read all the app markes... */ return result; } } else { if (!php_skip_variable(file)) { return result; } } break; case M_SOS: case M_EOI: /* we're about to hit image data, or are at EOF. stop processing. */ return result; default: if (!php_skip_variable(file)) { /* anything else isn't interesting */ return result; } break; } } return result; /* perhaps image broken -> no info but size */ } static unsigned short php_read4(const req::ptr<File>& stream) { unsigned char *a; String str = stream->read(4); /* just return 0 if we hit the end-of-file */ if (str.length() != 4) return 0; a = (unsigned char *)str.c_str(); return (((unsigned int)a[0]) << 24) + (((unsigned int)a[1]) << 16) + (((unsigned int)a[2]) << 8) + (((unsigned int)a[3])); } /* JPEG 2000 Marker Codes */ #define JPEG2000_MARKER_PREFIX 0xFF /* All marker codes start with this */ #define JPEG2000_MARKER_SOC 0x4F /* Start of Codestream */ #define JPEG2000_MARKER_SOT 0x90 /* Start of Tile part */ #define JPEG2000_MARKER_SOD 0x93 /* Start of Data */ #define JPEG2000_MARKER_EOC 0xD9 /* End of Codestream */ #define JPEG2000_MARKER_SIZ 0x51 /* Image and tile size */ #define JPEG2000_MARKER_COD 0x52 /* Coding style default */ #define JPEG2000_MARKER_COC 0x53 /* Coding style component */ #define JPEG2000_MARKER_RGN 0x5E /* Region of interest */ #define JPEG2000_MARKER_QCD 0x5C /* Quantization default */ #define JPEG2000_MARKER_QCC 0x5D /* Quantization component */ #define JPEG2000_MARKER_POC 0x5F /* Progression order change */ #define JPEG2000_MARKER_TLM 0x55 /* Tile-part lengths */ #define JPEG2000_MARKER_PLM 0x57 /* Packet length, main header */ #define JPEG2000_MARKER_PLT 0x58 /* Packet length, tile-part header */ #define JPEG2000_MARKER_PPM 0x60 /* Packed packet headers, main header */ #define JPEG2000_MARKER_PPT 0x61 /* Packed packet headers, tile part header */ #define JPEG2000_MARKER_SOP 0x91 /* Start of packet */ #define JPEG2000_MARKER_EPH 0x92 /* End of packet header */ #define JPEG2000_MARKER_CRG 0x63 /* Component registration */ #define JPEG2000_MARKER_COM 0x64 /* Comment */ /* Main loop to parse JPEG2000 raw codestream structure */ static struct gfxinfo *php_handle_jpc(const req::ptr<File>& file) { struct gfxinfo *result = nullptr; int highest_bit_depth, bit_depth; unsigned char first_marker_id; unsigned int i; /* JPEG 2000 components can be vastly different from one another. Each component can be sampled at a different resolution, use a different colour space, have a separate colour depth, and be compressed totally differently! This makes giving a single "bit depth" answer somewhat problematic. For this implementation we'll use the highest depth encountered. */ /* Get the single byte that remains after the file type indentification */ first_marker_id = file->getc(); /* Ensure that this marker is SIZ (as is mandated by the standard) */ if (first_marker_id != JPEG2000_MARKER_SIZ) { raise_warning("JPEG2000 codestream corrupt(Expected SIZ marker " "not found after SOC)"); return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); php_read2(file); /* Lsiz */ php_read2(file); /* Rsiz */ result->width = php_read4(file); /* Xsiz */ result->height = php_read4(file); /* Ysiz */ #if MBO_0 php_read4(file); /* XOsiz */ php_read4(file); /* YOsiz */ php_read4(file); /* XTsiz */ php_read4(file); /* YTsiz */ php_read4(file); /* XTOsiz */ php_read4(file); /* YTOsiz */ #else if (!file->seek(24, SEEK_CUR)) { IM_FREE(result); return nullptr; } #endif result->channels = php_read2(file); /* Csiz */ if (result->channels > 256) { IM_FREE(result); return nullptr; } /* Collect bit depth info */ highest_bit_depth = bit_depth = 0; for (i = 0; i < result->channels; i++) { bit_depth = file->getc(); /* Ssiz[i] */ bit_depth++; if (bit_depth > highest_bit_depth) { highest_bit_depth = bit_depth; } file->getc(); /* XRsiz[i] */ file->getc(); /* YRsiz[i] */ } result->bits = highest_bit_depth; return result; } /* main loop to parse JPEG 2000 JP2 wrapper format structure */ static struct gfxinfo *php_handle_jp2(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; unsigned int box_length; unsigned int box_type; char jp2c_box_id[] = {(char)0x6a, (char)0x70, (char)0x32, (char)0x63}; /* JP2 is a wrapper format for JPEG 2000. Data is contained within "boxes". Boxes themselves can be contained within "super-boxes". Super-Boxes can contain super-boxes which provides us with a hierarchical storage system. It is valid for a JP2 file to contain multiple individual codestreams. We'll just look for the first codestream at the root of the box structure and handle that. */ for (;;) { box_length = php_read4(stream); /* LBox */ /* TBox */ String str = stream->read(sizeof(box_type)); if (str.length() != sizeof(box_type)) { /* Use this as a general "out of stream" error */ break; } memcpy(&box_type, str.c_str(), sizeof(box_type)); if (box_length == 1) { /* We won't handle XLBoxes */ return nullptr; } if (!memcmp(&box_type, jp2c_box_id, 4)) { /* Skip the first 3 bytes to emulate the file type examination */ stream->seek(3, SEEK_CUR); result = php_handle_jpc(stream); break; } /* Stop if this was the last box */ if ((int)box_length <= 0) { break; } /* Skip over LBox (Which includes both TBox and LBox itself */ if (!stream->seek(box_length - 8, SEEK_CUR)) { break; } } if (result == nullptr) { raise_warning("JP2 file has no codestreams at root level"); } return result; } /* tiff constants */ static const int php_tiff_bytes_per_format[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8, 1}; static int get_php_tiff_bytes_per_format(int format) { int size = sizeof(php_tiff_bytes_per_format)/sizeof(int); if (format >= size) { raise_warning("Invalid format %d", format); format = 0; } return php_tiff_bytes_per_format[format]; } /* uncompressed only */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 /* compressed images only */ #define TAG_COMP_IMAGEWIDTH 0xA002 #define TAG_COMP_IMAGEHEIGHT 0xA003 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 static int php_vspprintf(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, ...) ATTRIBUTE_PRINTF(3,4); static int php_vspprintf(char **pbuf, size_t max_len, const char *fmt, ...) { va_list arglist; char *buf; va_start(arglist, fmt); int len = vspprintf_ap(&buf, max_len, fmt, arglist); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } va_end(arglist); return len; } static int php_vspprintf_ap(char **pbuf, size_t max_len, ATTRIBUTE_PRINTF_STRING const char *fmt, va_list ap) ATTRIBUTE_PRINTF(3,0); static int php_vspprintf_ap(char **pbuf, size_t max_len, const char *fmt, va_list ap) { char *buf; int len = vspprintf_ap(&buf, max_len, fmt, ap); if (buf) { #ifdef IM_MEMORY_CHECK *pbuf = php_strndup_impl(buf, len, __LINE__); #else *pbuf = php_strndup_impl(buf, len); #endif free(buf); } return len; } /* Convert a 16 bit unsigned value from file's native byte order */ static int php_ifd_get16u(void *Short, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Short)[0] << 8) | ((unsigned char *)Short)[1]; } else { return (((unsigned char *)Short)[1] << 8) | ((unsigned char *)Short)[0]; } } /* Convert a 16 bit signed value from file's native byte order */ static signed short php_ifd_get16s(void *Short, int motorola_intel) { return (signed short)php_ifd_get16u(Short, motorola_intel); } /* Convert a 32 bit signed value from file's native byte order */ static int php_ifd_get32s(void *Long, int motorola_intel) { if (motorola_intel) { return (((unsigned char *)Long)[0] << 24) | (((unsigned char *)Long)[1] << 16) | (((unsigned char *)Long)[2] << 8) | (((unsigned char *)Long)[3] << 0); } else { return (((unsigned char *)Long)[3] << 24) | (((unsigned char *)Long)[2] << 16) | (((unsigned char *)Long)[1] << 8) | (((unsigned char *)Long)[0] << 0); } } /* Convert a 32 bit unsigned value from file's native byte order */ static unsigned php_ifd_get32u(void *Long, int motorola_intel) { return (unsigned)php_ifd_get32s(Long, motorola_intel) & 0xffffffff; } /* main loop to parse TIFF structure */ static struct gfxinfo *php_handle_tiff(const req::ptr<File>& stream, int motorola_intel) { struct gfxinfo *result = nullptr; int i, num_entries; unsigned char *dir_entry; size_t dir_size, entry_value, width=0, height=0, ifd_addr; int entry_tag , entry_type; String ifd_ptr = stream->read(4); if (ifd_ptr.length() != 4) return nullptr; ifd_addr = php_ifd_get32u((void*)ifd_ptr.c_str(), motorola_intel); if (!stream->seek(ifd_addr-8, SEEK_CUR)) return nullptr; String ifd_data = stream->read(2); if (ifd_data.length() != 2) return nullptr; num_entries = php_ifd_get16u((void*)ifd_data.c_str(), motorola_intel); dir_size = 2/*num dir entries*/ +12/*length of entry*/* num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; String ifd_data2 = stream->read(dir_size-2); if ((size_t)ifd_data2.length() != dir_size-2) return nullptr; ifd_data += ifd_data2; /* now we have the directory we can look how long it should be */ for(i=0;i<num_entries;i++) { dir_entry = (unsigned char*)ifd_data.c_str()+2+i*12; entry_tag = php_ifd_get16u(dir_entry+0, motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, motorola_intel); switch(entry_type) { case TAG_FMT_BYTE: case TAG_FMT_SBYTE: entry_value = (size_t)(dir_entry[8]); break; case TAG_FMT_USHORT: entry_value = php_ifd_get16u(dir_entry+8, motorola_intel); break; case TAG_FMT_SSHORT: entry_value = php_ifd_get16s(dir_entry+8, motorola_intel); break; case TAG_FMT_ULONG: entry_value = php_ifd_get32u(dir_entry+8, motorola_intel); break; case TAG_FMT_SLONG: entry_value = php_ifd_get32s(dir_entry+8, motorola_intel); break; default: continue; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGEWIDTH: width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGEHEIGHT: height = entry_value; break; } } if ( width && height) { /* not the same when in for-loop */ result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->height = height; result->width = width; result->bits = 0; result->channels = 0; return result; } return nullptr; } static struct gfxinfo *php_handle_iff(const req::ptr<File>& stream) { struct gfxinfo * result; char *a; int chunkId; int size; short width, height, bits; String str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); if (strncmp(a+4, "ILBM", 4) && strncmp(a+4, "PBM ", 4)) { return nullptr; } /* loop chunks to find BMHD chunk */ do { str = stream->read(8); if (str.length() != 8) return nullptr; a = (char *)str.c_str(); chunkId = php_ifd_get32s(a+0, 1); size = php_ifd_get32s(a+4, 1); if (size < 0) return nullptr; if ((size & 1) == 1) { size++; } if (chunkId == 0x424d4844) { /* BMHD chunk */ if (size < 9) return nullptr; str = stream->read(9); if (str.length() != 9) return nullptr; a = (char *)str.c_str(); width = php_ifd_get16s(a+0, 1); height = php_ifd_get16s(a+2, 1); bits = a[8] & 0xff; if (width > 0 && height > 0 && bits > 0 && bits < 33) { result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, sizeof (struct gfxinfo), nullptr); result->width = width; result->height = height; result->bits = bits; result->channels = 0; return result; } } else { if (!stream->seek(size, SEEK_CUR)) return nullptr; } } while (1); } /* * int WBMP file format type * byte Header Type * byte Extended Header * byte Header Data (type 00 = multibyte) * byte Header Data (type 11 = name/pairs) * int Number of columns * int Number of rows */ static int php_get_wbmp(const req::ptr<File>& file, struct gfxinfo **result, int check) { int i, width = 0, height = 0; if (!file->rewind()) { return 0; } /* get type */ if (file->getc() != 0) { return 0; } /* skip header */ do { i = file->getc(); if (i < 0) { return 0; } } while (i & 0x80); /* get width */ do { i = file->getc(); if (i < 0) { return 0; } width = (width << 7) | (i & 0x7f); } while (i & 0x80); /* get height */ do { i = file->getc(); if (i < 0) { return 0; } height = (height << 7) | (i & 0x7f); } while (i & 0x80); // maximum valid sizes for wbmp (although 127x127 may be a // more accurate one) if (!height || !width || height > 2048 || width > 2048) { return 0; } if (!check) { (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_WBMP; } static struct gfxinfo *php_handle_wbmp(const req::ptr<File>& stream) { struct gfxinfo *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); if (!php_get_wbmp(stream, &result, 0)) { IM_FREE(result); return nullptr; } return result; } static int php_get_xbm(const req::ptr<File>& stream, struct gfxinfo **result) { String fline; char *iname; char *type; int value; unsigned int width = 0, height = 0; if (result) { *result = nullptr; } if (!stream->rewind()) { return 0; } while (!(fline = HHVM_FN(fgets)(Resource(stream), 0).toString()).empty()) { iname = (char *)IM_MALLOC(fline.size() + 1); CHECK_ALLOC_R(iname, (fline.size() + 1), 0); if (sscanf(fline.c_str(), "#define %s %d", iname, &value) == 2) { if (!(type = strrchr(iname, '_'))) { type = iname; } else { type++; } if (!strcmp("width", type)) { width = (unsigned int)value; if (height) { IM_FREE(iname); break; } } if (!strcmp("height", type)) { height = (unsigned int)value; if (width) { IM_FREE(iname); break; } } } IM_FREE(iname); } if (width && height) { if (result) { *result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(*result, sizeof(struct gfxinfo), 0); (*result)->width = width; (*result)->height = height; } return IMAGE_FILETYPE_XBM; } return 0; } static struct gfxinfo *php_handle_xbm(const req::ptr<File>& stream) { struct gfxinfo *result; php_get_xbm(stream, &result); return result; } static struct gfxinfo *php_handle_ico(const req::ptr<File>& stream) { struct gfxinfo *result = nullptr; const unsigned char *s; int num_icons = 0; String dim = stream->read(2); if (dim.length() != 2) { return nullptr; } s = (unsigned char *)dim.c_str(); num_icons = (((unsigned int)s[1]) << 8) + ((unsigned int)s[0]); if (num_icons < 1 || num_icons > 255) { return nullptr; } result = (struct gfxinfo *)IM_CALLOC(1, sizeof(struct gfxinfo)); CHECK_ALLOC_R(result, (sizeof(struct gfxinfo)), nullptr); while (num_icons > 0) { dim = stream->read(16); if (dim.length() != 16) { break; } s = (unsigned char *)dim.c_str(); if ((((unsigned int)s[7]) << 8) + ((unsigned int)s[6]) >= result->bits) { result->width = (unsigned int)s[0]; result->height = (unsigned int)s[1]; result->bits = (((unsigned int)s[7]) << 8) + ((unsigned int)s[6]); } num_icons--; } return result; } /* Convert internal image_type to mime type */ static char *php_image_type_to_mime_type(int image_type) { switch( image_type) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } /* detect filetype from first bytes */ static int php_getimagetype(const req::ptr<File>& file) { String fileType = file->read(3); if (fileType.length() != 3) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 3 */ if (!memcmp(fileType.c_str(), php_sig_gif, 3)) { return IMAGE_FILETYPE_GIF; } else if (!memcmp(fileType.c_str(), php_sig_jpg, 3)) { return IMAGE_FILETYPE_JPEG; } else if (!memcmp(fileType.c_str(), php_sig_png, 3)) { String data = file->read(5); if (data.length() != 5) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } if (!memcmp((fileType + data).c_str(), php_sig_png, 8)) { return IMAGE_FILETYPE_PNG; } else { raise_warning("PNG file corrupted by ASCII conversion"); return IMAGE_FILETYPE_UNKNOWN; } } else if (!memcmp(fileType.c_str(), php_sig_swf, 3)) { return IMAGE_FILETYPE_SWF; } else if (!memcmp(fileType.c_str(), php_sig_swc, 3)) { return IMAGE_FILETYPE_SWC; } else if (!memcmp(fileType.c_str(), php_sig_psd, 3)) { return IMAGE_FILETYPE_PSD; } else if (!memcmp(fileType.c_str(), php_sig_bmp, 2)) { return IMAGE_FILETYPE_BMP; } else if (!memcmp(fileType.c_str(), php_sig_jpc, 3)) { return IMAGE_FILETYPE_JPC; } String data = file->read(1); if (data.length() != 1) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 4 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_tif_ii, 4)) { return IMAGE_FILETYPE_TIFF_II; } else if (!memcmp(fileType.c_str(), php_sig_tif_mm, 4)) { return IMAGE_FILETYPE_TIFF_MM; } else if (!memcmp(fileType.c_str(), php_sig_iff, 4)) { return IMAGE_FILETYPE_IFF; } else if (!memcmp(fileType.c_str(), php_sig_ico, 4)) { return IMAGE_FILETYPE_ICO; } data = file->read(8); if (data.length() != 8) { raise_notice("Read error!"); return IMAGE_FILETYPE_UNKNOWN; } /* BYTES READ: 12 */ fileType += data; if (!memcmp(fileType.c_str(), php_sig_jp2, 12)) { return IMAGE_FILETYPE_JP2; } /* AFTER ALL ABOVE FAILED */ if (php_get_wbmp(file, nullptr, 1)) { return IMAGE_FILETYPE_WBMP; } if (php_get_xbm(file, nullptr)) { return IMAGE_FILETYPE_XBM; } return IMAGE_FILETYPE_UNKNOWN; } String HHVM_FUNCTION(image_type_to_mime_type, int64_t imagetype) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return "image/gif"; case IMAGE_FILETYPE_JPEG: return "image/jpeg"; case IMAGE_FILETYPE_PNG: return "image/png"; case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return "application/x-shockwave-flash"; case IMAGE_FILETYPE_PSD: return "image/psd"; case IMAGE_FILETYPE_BMP: return "image/x-ms-bmp"; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return "image/tiff"; case IMAGE_FILETYPE_IFF: return "image/iff"; case IMAGE_FILETYPE_WBMP: return "image/vnd.wap.wbmp"; case IMAGE_FILETYPE_JPC: return "application/octet-stream"; case IMAGE_FILETYPE_JP2: return "image/jp2"; case IMAGE_FILETYPE_XBM: return "image/xbm"; case IMAGE_FILETYPE_ICO: return "image/vnd.microsoft.icon"; default: case IMAGE_FILETYPE_UNKNOWN: return "application/octet-stream"; /* suppose binary format */ } } Variant HHVM_FUNCTION(image_type_to_extension, int64_t imagetype, bool include_dot /*=true */) { switch (imagetype) { case IMAGE_FILETYPE_GIF: return include_dot ? String(".gif") : String("gif"); case IMAGE_FILETYPE_JPEG: return include_dot ? String(".jpeg") : String("jpeg"); case IMAGE_FILETYPE_PNG: return include_dot ? String(".png") : String("png"); case IMAGE_FILETYPE_SWF: case IMAGE_FILETYPE_SWC: return include_dot ? String(".swf") : String("swf"); case IMAGE_FILETYPE_PSD: return include_dot ? String(".psd") : String("psd"); case IMAGE_FILETYPE_BMP: case IMAGE_FILETYPE_WBMP: return include_dot ? String(".bmp") : String("bmp"); case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: return include_dot ? String(".tiff") : String("tiff"); case IMAGE_FILETYPE_IFF: return include_dot ? String(".iff") : String("iff"); case IMAGE_FILETYPE_JPC: return include_dot ? String(".jpc") : String("jpc"); case IMAGE_FILETYPE_JP2: return include_dot ? String(".jp2") : String("jp2"); case IMAGE_FILETYPE_JPX: return include_dot ? String(".jpx") : String("jpx"); case IMAGE_FILETYPE_JB2: return include_dot ? String(".jb2") : String("jb2"); case IMAGE_FILETYPE_XBM: return include_dot ? String(".xbm") : String("xbm"); case IMAGE_FILETYPE_ICO: return include_dot ? String(".ico") : String("ico"); default: return false; } } const StaticString s_bits("bits"), s_channels("channels"), s_mime("mime"), s_linespacing("linespacing"); gdImagePtr get_valid_image_resource(const Resource& image) { auto img_res = dyn_cast_or_null<Image>(image); if (!img_res || !img_res->get()) { raise_warning("supplied resource is not a valid Image resource"); return nullptr; } return img_res->get(); } Variant getImageSize(const req::ptr<File>& stream, VRefParam imageinfo) { int itype = 0; struct gfxinfo *result = nullptr; auto imageInfoPtr = imageinfo.getVariantOrNull(); if (imageInfoPtr) { *imageInfoPtr = Array::Create(); } itype = php_getimagetype(stream); switch( itype) { case IMAGE_FILETYPE_GIF: result = php_handle_gif(stream); break; case IMAGE_FILETYPE_JPEG: { Array infoArr; if (imageInfoPtr) { infoArr = Array::Create(); } result = php_handle_jpeg(stream, infoArr); if (imageInfoPtr) { *imageInfoPtr = infoArr; } } break; case IMAGE_FILETYPE_PNG: result = php_handle_png(stream); break; case IMAGE_FILETYPE_SWF: result = php_handle_swf(stream); break; case IMAGE_FILETYPE_SWC: result = php_handle_swc(stream); break; case IMAGE_FILETYPE_PSD: result = php_handle_psd(stream); break; case IMAGE_FILETYPE_BMP: result = php_handle_bmp(stream); break; case IMAGE_FILETYPE_TIFF_II: result = php_handle_tiff(stream, 0); break; case IMAGE_FILETYPE_TIFF_MM: result = php_handle_tiff(stream, 1); break; case IMAGE_FILETYPE_JPC: result = php_handle_jpc(stream); break; case IMAGE_FILETYPE_JP2: result = php_handle_jp2(stream); break; case IMAGE_FILETYPE_IFF: result = php_handle_iff(stream); break; case IMAGE_FILETYPE_WBMP: result = php_handle_wbmp(stream); break; case IMAGE_FILETYPE_XBM: result = php_handle_xbm(stream); break; case IMAGE_FILETYPE_ICO: result = php_handle_ico(stream); break; default: case IMAGE_FILETYPE_UNKNOWN: break; } if (result) { DArrayInit ret(7); ret.set(0, (int64_t)result->width); ret.set(1, (int64_t)result->height); ret.set(2, itype); char *temp; php_vspprintf(&temp, 0, "width=\"%d\" height=\"%d\"", result->width, result->height); ret.set(3, String(temp, CopyString)); if (temp) IM_FREE(temp); if (result->bits != 0) { ret.set(s_bits, (int64_t)result->bits); } if (result->channels != 0) { ret.set(s_channels, (int64_t)result->channels); } ret.set(s_mime, (char*)php_image_type_to_mime_type(itype)); IM_FREE(result); return ret.toVariant(); } else { return false; } } Variant HHVM_FUNCTION(getimagesize, const String& filename, VRefParam imageinfo /*=null */) { if (auto stream = File::Open(filename, "rb")) { return getImageSize(stream, imageinfo); } return false; } Variant HHVM_FUNCTION(getimagesizefromstring, const String& imagedata, VRefParam imageinfo /*=null */) { String data = "data://text/plain;base64,"; data += StringUtil::Base64Encode(imagedata); if (auto stream = File::Open(data, "r")) { return getImageSize(stream, imageinfo); } return false; } // PHP extension gd.c #define HAVE_GDIMAGECREATEFROMPNG 1 #if HAVE_LIBTTF|HAVE_LIBFREETYPE #ifndef ENABLE_GD_TTF #define ENABLE_GD_TTF #endif #endif #define PHP_GDIMG_TYPE_GIF 1 #define PHP_GDIMG_TYPE_PNG 2 #define PHP_GDIMG_TYPE_JPG 3 #define PHP_GDIMG_TYPE_WBM 4 #define PHP_GDIMG_TYPE_XBM 5 #define PHP_GDIMG_TYPE_XPM 6 #define PHP_GDIMG_CONVERT_WBM 7 #define PHP_GDIMG_TYPE_GD 8 #define PHP_GDIMG_TYPE_GD2 9 #define PHP_GDIMG_TYPE_GD2PART 10 #define PHP_GDIMG_TYPE_WEBP 11 #define PHP_GD_VERSION_STRING "bundled (2.0.34 compatible)" #define USE_GD_IOCTX 1 #define CTX_PUTC(c,ctx) ctx->putC(ctx, c) #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static req::ptr<File> php_open_plain_file(const String& filename, const char *mode, FILE **fpp) { auto file = File::Open(filename, mode); auto plain_file = dyn_cast_or_null<PlainFile>(file); if (!plain_file) return nullptr; if (FILE* fp = plain_file->getStream()) { if (fpp) *fpp = fp; return file; } file->close(); return nullptr; } static int php_write(void *buf, uint32_t size) { g_context->write((const char *)buf, size); return size; } static void _php_image_output_putc(struct gdIOCtx* /*ctx*/, int c) { /* without the following downcast, the write will fail * (i.e., will write a zero byte) for all * big endian architectures: */ unsigned char ch = (unsigned char) c; php_write(&ch, 1); } static int _php_image_output_putbuf(struct gdIOCtx* /*ctx*/, const void* buf, int len) { return php_write((void *)buf, len); } static void _php_image_output_ctxfree(struct gdIOCtx *ctx) { if (ctx) { IM_FREE(ctx); } } static bool _php_image_output_ctx(const Resource& image, const String& filename, int quality, int basefilter, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp = nullptr; int q = quality, i; int f = basefilter; gdIOCtx *ctx; /* The third (quality) parameter for Wbmp stands for the threshold when called from image2wbmp(). The third (quality) parameter for Wbmp and Xbm stands for the foreground color index when called from imagey<type>(). */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } ctx = gdNewFileCtx(fp); } else { ctx = (gdIOCtx *)IM_MALLOC(sizeof(gdIOCtx)); CHECK_ALLOC_R(ctx, sizeof(gdIOCtx), false); ctx->putC = _php_image_output_putc; ctx->putBuf = _php_image_output_putbuf; ctx->gd_free = _php_image_output_ctxfree; } switch(image_type) { case PHP_GDIMG_CONVERT_WBM: if (q<0||q>255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); } case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, gdIOCtx *, int))(func_p))(im, ctx, q); break; case PHP_GDIMG_TYPE_PNG: ((void(*)(gdImagePtr, gdIOCtx *, int, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_WEBP: ((void(*)(gdImagePtr, gdIOCtx *, int64_t, int))(func_p))(im, ctx, q, f); break; case PHP_GDIMG_TYPE_XBM: case PHP_GDIMG_TYPE_WBM: if (q == -1) { // argc < 3 for(i=0; i < gdImageColorsTotal(im); i++) { if (!gdImageRed(im, i) && !gdImageGreen(im, i) && !gdImageBlue(im, i)) break; } q = i; } if (image_type == PHP_GDIMG_TYPE_XBM) { ((void(*)(gdImagePtr, char *, int, gdIOCtx *))(func_p)) (im, (char*)filename.c_str(), q, ctx); } else { ((void(*)(gdImagePtr, int, gdIOCtx *))(func_p))(im, q, ctx); } break; default: ((void(*)(gdImagePtr, gdIOCtx *))(func_p))(im, ctx); break; } ctx->gd_free(ctx); if (fp) { fflush(fp); file->close(); } return true; } /* It converts a gd Image to bw using a threshold value */ static void _php_image_bw_convert(gdImagePtr im_org, gdIOCtx *out, int threshold) { gdImagePtr im_dest; int white, black; int color, color_org, median; int dest_height = gdImageSY(im_org); int dest_width = gdImageSX(im_org); int x, y; im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate temporary buffer"); return; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return; } if (im_org->trueColor) { gdImageTrueColorToPalette(im_org, 1, 256); } for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel(im_org, x, y); median = (im_org->red[color_org] + im_org->green[color_org] + im_org->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel (im_dest, x, y, color); } } gdImageWBMPCtx (im_dest, black, out); } /* * converts jpeg/png images to wbmp and resizes them as needed */ static bool _php_image_convert(const String& f_org, const String& f_dest, int dest_height, int dest_width, int threshold, int image_type) { gdImagePtr im_org, im_dest, im_tmp; req::ptr<File> org_file, dest_file; FILE *org, *dest; int org_height, org_width; int white, black; int color, color_org, median; int x, y; float x_ratio, y_ratio; #ifdef HAVE_GD_JPG // long ignore_warning; #endif /* Check threshold value */ if (threshold < 0 || threshold > 8) { raise_warning("Invalid threshold value '%d'", threshold); return false; } /* Open origin file */ org_file = php_open_plain_file(f_org, "rb", &org); if (!org_file) { return false; } /* Open destination file */ dest_file = php_open_plain_file(f_dest, "wb", &dest); if (!dest_file) { return false; } switch (image_type) { case PHP_GDIMG_TYPE_GIF: im_org = gdImageCreateFromGif(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid GIF file", f_org.c_str()); return false; } break; #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im_org = gdImageCreateFromJpeg(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid JPEG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_JPG */ #ifdef HAVE_GD_PNG case PHP_GDIMG_TYPE_PNG: im_org = gdImageCreateFromPng(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid PNG file", f_org.c_str()); return false; } break; #endif /* HAVE_GD_PNG */ #ifdef HAVE_LIBVPX case PHP_GDIMG_TYPE_WEBP: im_org = gdImageCreateFromWebp(org); if (im_org == nullptr) { raise_warning("Unable to open '%s' Not a valid webp file", f_org.c_str()); return false; } break; #endif /* HAVE_LIBVPX */ default: raise_warning("Format not supported"); return false; } org_width = gdImageSX (im_org); org_height = gdImageSY (im_org); x_ratio = (float) org_width / (float) dest_width; y_ratio = (float) org_height / (float) dest_height; if (x_ratio > 1 && y_ratio > 1) { if (y_ratio > x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width / x_ratio); dest_height = (int) (org_height / y_ratio); } else { x_ratio = (float) dest_width / (float) org_width; y_ratio = (float) dest_height / (float) org_height; if (y_ratio < x_ratio) { x_ratio = y_ratio; } else { y_ratio = x_ratio; } dest_width = (int) (org_width * x_ratio); dest_height = (int) (org_height * y_ratio); } im_tmp = gdImageCreate (dest_width, dest_height); if (im_tmp == nullptr) { raise_warning("Unable to allocate temporary buffer"); return false; } gdImageCopyResized (im_tmp, im_org, 0, 0, 0, 0, dest_width, dest_height, org_width, org_height); gdImageDestroy(im_org); org_file->close(); im_dest = gdImageCreate(dest_width, dest_height); if (im_dest == nullptr) { raise_warning("Unable to allocate destination buffer"); return false; } white = gdImageColorAllocate(im_dest, 255, 255, 255); if (white == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } black = gdImageColorAllocate(im_dest, 0, 0, 0); if (black == -1) { raise_warning("Unable to allocate the colors for " "the destination buffer"); return false; } threshold = threshold * 32; for (y = 0; y < dest_height; y++) { for (x = 0; x < dest_width; x++) { color_org = gdImageGetPixel (im_tmp, x, y); median = (im_tmp->red[color_org] + im_tmp->green[color_org] + im_tmp->blue[color_org]) / 3; if (median < threshold) { color = black; } else { color = white; } gdImageSetPixel(im_dest, x, y, color); } } gdImageDestroy(im_tmp); gdImageWBMP(im_dest, black , dest); fflush(dest); dest_file->close(); gdImageDestroy(im_dest); return true; } // For quality and type, -1 means that the argument does not exist static bool _php_image_output(const Resource& image, const String& filename, int quality, int type, int image_type, char* /*tn*/, void (*func_p)()) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; req::ptr<File> file; FILE *fp; int q = quality, i, t = type; /* The quality parameter for Wbmp stands for the threshold when called from image2wbmp() */ /* When called from imagewbmp() the quality parameter stands for the foreground color. Default: black. */ /* The quality parameter for gd2 stands for chunk size */ if (!filename.empty()) { file = php_open_plain_file(filename, "wb", &fp); if (!file) { raise_warning("Unable to open '%s' for writing", filename.c_str()); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, fp); break; case PHP_GDIMG_TYPE_JPG: { // gdImageJpeg ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, fp, q); break; } case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) break; } // gdImageWBMP ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, i, fp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } // gdImageGd ((void(*)(gdImagePtr, FILE *))(func_p))(im, fp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } // gdImageGd2 ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; default: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, fp, q, t); break; } fflush(fp); file->close(); } else { int b; FILE *tmp; char buf[4096]; char path[PATH_MAX]; // open a temporary file snprintf(path, sizeof(path), "/tmp/XXXXXX"); int fd = mkstemp(path); if (fd == -1 || (tmp = fdopen(fd, "r+b")) == nullptr) { if (fd != -1) close(fd); raise_warning("Unable to open temporary file"); return false; } switch (image_type) { case PHP_GDIMG_CONVERT_WBM: if (q == -1) { q = 0; } else if (q < 0 || q > 255) { raise_warning("Invalid threshold value '%d'. " "It must be between 0 and 255", q); q = 0; } gdImageWBMP(im, q, tmp); break; case PHP_GDIMG_TYPE_JPG: ((void(*)(gdImagePtr, FILE *, int))(func_p))(im, tmp, q); break; case PHP_GDIMG_TYPE_WBM: for (i = 0; i < gdImageColorsTotal(im); i++) { if (gdImageRed(im, i) == 0) { break; } } ((void(*)(gdImagePtr, int, FILE *))(func_p))(im, q, tmp); break; case PHP_GDIMG_TYPE_GD: if (im->trueColor) { gdImageTrueColorToPalette(im,1,256); } ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; case PHP_GDIMG_TYPE_GD2: if (q == -1) { q = 128; } ((void(*)(gdImagePtr, FILE *, int, int))(func_p))(im, tmp, q, t); break; default: ((void(*)(gdImagePtr, FILE *))(func_p))(im, tmp); break; } fseek(tmp, 0, SEEK_SET); while ((b = fread(buf, 1, sizeof(buf), tmp)) > 0) { g_context->write(buf, b); } fclose(tmp); /* make sure that the temporary file is removed */ unlink((const char *)path); } return true; } static gdImagePtr _php_image_create_from(const String& filename, int srcX, int srcY, int width, int height, int image_type, char *tn, gdImagePtr(*func_p)(), gdImagePtr(*ioctx_func_p)()) { VMRegAnchor _; gdImagePtr im = nullptr; #ifdef HAVE_GD_JPG // long ignore_warning; #endif if (image_type == PHP_GDIMG_TYPE_GD2PART) { if (width < 1 || height < 1) { raise_warning("Zero width or height not allowed"); return nullptr; } } auto file = File::Open(filename, "rb"); if (!file) { raise_warning("failed to open stream: %s", filename.c_str()); return nullptr; } FILE *fp = nullptr; auto plain_file = dyn_cast<PlainFile>(file); if (plain_file) { fp = plain_file->getStream(); } else if (ioctx_func_p) { /* we can create an io context */ gdIOCtx* io_ctx; // copy all String buff = file->read(8192); String str; do { str = file->read(8192); buff += str; } while (!str.empty()); if (buff.empty()) { raise_warning("Cannot read image data"); return nullptr; } io_ctx = gdNewDynamicCtxEx(buff.length(), (char *)buff.c_str(), 0); if (!io_ctx) { raise_warning("Cannot allocate GD IO context"); return nullptr; } if (image_type == PHP_GDIMG_TYPE_GD2PART) { im = ((gdImagePtr(*)(gdIOCtx *, int, int, int, int))(ioctx_func_p)) (io_ctx, srcX, srcY, width, height); } else { im = ((gdImagePtr(*)(gdIOCtx *))(ioctx_func_p))(io_ctx); } io_ctx->gd_free(io_ctx); } else { /* TODO: try and force the stream to be FILE* */ assertx(false); } if (!im && fp) { switch (image_type) { case PHP_GDIMG_TYPE_GD2PART: im = ((gdImagePtr(*)(FILE *, int, int, int, int))(func_p)) (fp, srcX, srcY, width, height); break; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) case PHP_GDIMG_TYPE_XPM: im = gdImageCreateFromXpm(filename); break; #endif #ifdef HAVE_GD_JPG case PHP_GDIMG_TYPE_JPG: im = gdImageCreateFromJpeg(fp); break; #endif default: im = ((gdImagePtr(*)(FILE*))(func_p))(fp); break; } fflush(fp); } if (im) { file->close(); return im; } raise_warning("'%s' is not a valid %s file", filename.c_str(), tn); file->close(); return nullptr; } static const char php_sig_gd2[3] = {'g', 'd', '2'}; /* getmbi ** ------ ** Get a multibyte integer from a generic getin function ** 'getin' can be getc, with in = NULL ** you can find getin as a function just above the main function ** This way you gain a lot of flexibilty about how this package ** reads a wbmp file. */ static int getmbi(gdIOCtx *ctx) { int i, mbi = 0; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); mbi = (mbi << 7) | (i & 0x7f); } while (i & 0x80); return (mbi); } /* skipheader ** ---------- ** Skips the ExtHeader. Not needed for the moment ** */ int skipheader (gdIOCtx *ctx) { int i; do { i = (ctx->getC)(ctx); if (i < 0) return (-1); } while (i & 0x80); return (0); } static int _php_image_type (char data[8]) { if (data == nullptr) { return -1; } if (!memcmp(data, php_sig_gd2, 3)) { return PHP_GDIMG_TYPE_GD2; } else if (!memcmp(data, php_sig_jpg, 3)) { return PHP_GDIMG_TYPE_JPG; } else if (!memcmp(data, php_sig_png, 3)) { if (!memcmp(data, php_sig_png, 8)) { return PHP_GDIMG_TYPE_PNG; } } else if (!memcmp(data, php_sig_gif, 3)) { return PHP_GDIMG_TYPE_GIF; } else { gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(8, data, 0); if (io_ctx) { if (getmbi(io_ctx) == 0 && skipheader(io_ctx) == 0 ) { io_ctx->gd_free(io_ctx); return PHP_GDIMG_TYPE_WBM; } else { io_ctx->gd_free(io_ctx); } } } return -1; } gdImagePtr _php_image_create_from_string(const String& image, char *tn, gdImagePtr (*ioctx_func_p)()) { VMRegAnchor _; gdIOCtx *io_ctx; io_ctx = gdNewDynamicCtxEx(image.length(), (char *)image.c_str(), 0); if (!io_ctx) { return nullptr; } gdImagePtr im = (*(gdImagePtr (*)(gdIOCtx *))ioctx_func_p)(io_ctx); if (!im) { raise_warning("Passed data is not in '%s' format", tn); io_ctx->gd_free(io_ctx); return nullptr; } io_ctx->gd_free(io_ctx); return im; } static gdFontPtr php_find_gd_font(int size) { gdFontPtr font; switch (size) { case 1: font = gdFontTiny; break; case 2: font = gdFontSmall; break; case 3: font = gdFontMediumBold; break; case 4: font = gdFontLarge; break; case 5: font = gdFontGiant; break; default: raise_warning("Unsupported font: %d", size); // font = zend_list_find(size - 5, &ind_type); // if (!font || ind_type != le_gd_font) { if (size < 1) { font = gdFontTiny; } else { font = gdFontGiant; } break; } return font; } /* workaround for a bug in gd 1.2 */ static void php_gdimagecharup(gdImagePtr im, gdFontPtr f, int x, int y, int c, int color) { int cx, cy, px, py, fline; cx = 0; cy = 0; if ((c < f->offset) || (c >= (f->offset + f->nchars))) { return; } fline = (c - f->offset) * f->h * f->w; for (py = y; (py > (y - f->w)); py--) { for (px = x; (px < (x + f->h)); px++) { if (f->data[fline + cy * f->w + cx]) { gdImageSetPixel(im, px, py, color); } cy++; } cy = 0; cx++; } } /* * arg = 0 ImageChar * arg = 1 ImageCharUp * arg = 2 ImageString * arg = 3 ImageStringUp */ static bool php_imagechar(const Resource& image, int size, int x, int y, const String& c, int color, int mode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ch = 0; gdFontPtr font; if (mode < 2) { ch = (int)((unsigned char)(c.charAt(0))); } font = php_find_gd_font(size); switch (mode) { case 0: gdImageChar(im, font, x, y, ch, color); break; case 1: php_gdimagecharup(im, font, x, y, ch, color); break; case 2: for (int i = 0; (i < c.length()); i++) { gdImageChar(im, font, x, y, (int)((unsigned char)c.charAt(i)), color); x += font->w; } break; case 3: for (int i = 0; (i < c.length()); i++) { gdImageCharUp(im, font, x, y, (int)c.charAt(i), color); y -= font->w; } break; } return true; } /* arg = 0 normal polygon arg = 1 filled polygon */ static bool php_imagepolygon(const Resource& image, const Array& points, int num_points, int color, int filled) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdPointPtr pts; int nelem, i; nelem = points.size(); if (nelem < 6) { raise_warning("You must have at least 3 points in your array"); return false; } if (nelem < num_points * 2) { raise_warning("Trying to use %d points in array with only %d points", num_points, nelem/2); return false; } pts = (gdPointPtr)IM_MALLOC(num_points * sizeof(gdPoint)); CHECK_ALLOC_R(pts, (num_points * sizeof(gdPoint)), false); for (i = 0; i < num_points; i++) { if (points.exists(i * 2)) { pts[i].x = points[i * 2].toInt32(); } if (points.exists(i * 2 + 1)) { pts[i].y = points[i * 2 + 1].toInt32(); } } if (filled) { gdImageFilledPolygon(im, pts, num_points, color); } else { color = SetupAntiAliasedColor(im, color); gdImagePolygon(im, pts, num_points, color); } IM_FREE(pts); return true; } static bool php_image_filter_negate(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageNegate(im) == 1; } static bool php_image_filter_grayscale(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGrayScale(im) == 1; } static bool php_image_filter_brightness(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int brightness = arg1; return gdImageBrightness(im, brightness) == 1; } static bool php_image_filter_contrast(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int contrast = arg1; return gdImageContrast(im, contrast) == 1; } static bool php_image_filter_colorize(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int arg3 /* = 0 */, int /*arg4*/ /* = 0 */) { int r = arg1; int g = arg2; int b = arg3; int a = arg1; return gdImageColor(im, r, g, b, a) == 1; } static bool php_image_filter_edgedetect(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEdgeDetectQuick(im) == 1; } static bool php_image_filter_emboss(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageEmboss(im) == 1; } static bool php_image_filter_gaussian_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageGaussianBlur(im) == 1; } static bool php_image_filter_selective_blur(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageSelectiveBlur(im) == 1; } static bool php_image_filter_mean_removal(gdImagePtr im, int /*arg1*/ /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { return gdImageMeanRemoval(im) == 1; } static bool php_image_filter_smooth(gdImagePtr im, int arg1 /* = 0 */, int /*arg2*/ /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int weight = arg1; return gdImageSmooth(im, weight) == 1; } static bool php_image_filter_pixelate(gdImagePtr im, int arg1 /* = 0 */, int arg2 /* = 0 */, int /*arg3*/ /* = 0 */, int /*arg4*/ /* = 0 */) { int blocksize = arg1; unsigned mode = arg2; return gdImagePixelate(im, blocksize, mode) == 1; } /* * arg = 0 ImageFontWidth * arg = 1 ImageFontHeight */ static int php_imagefontsize(int size, int arg) { gdFontPtr font = php_find_gd_font(size); return (arg ? font->h : font->w); } #ifdef ENABLE_GD_TTF #define TTFTEXT_DRAW 0 #define TTFTEXT_BBOX 1 #endif #ifdef ENABLE_GD_TTF static Variant php_imagettftext_common(int mode, int extended, const Variant& arg1, const Variant& arg2, const Variant& arg3, const Variant& arg4, const Variant& arg5 = uninit_variant, const Variant& arg6 = uninit_variant, const Variant& arg7 = uninit_variant, const Variant& arg8 = uninit_variant, const Variant& arg9 = uninit_variant) { gdImagePtr im=nullptr; long col = -1, x = -1, y = -1; int brect[8]; double ptsize, angle; String str; String fontname; Array extrainfo; char *error = nullptr; gdFTStringExtra strex = {0}; if (mode == TTFTEXT_BBOX) { ptsize = arg1.toDouble(); angle = arg2.toDouble(); fontname = arg3.toString(); str = arg4.toString(); extrainfo = arg5; } else { Resource image = arg1.toResource(); ptsize = arg2.toDouble(); angle = arg3.toDouble(); x = arg4.toInt64(); y = arg5.toInt64(); col = arg6.toInt64(); fontname = arg7.toString(); str = arg8.toString(); extrainfo = arg9; im = get_valid_image_resource(image); if (!im) return false; } /* convert angle to radians */ angle = angle * (M_PI/180); if (extended && !extrainfo.empty()) { /* parse extended info */ /* walk the assoc array */ for (ArrayIter iter(extrainfo); iter; ++iter) { Variant key = iter.first(); if (!key.isString()) continue; Variant item = iter.second(); if (equal(key, s_linespacing)) { strex.flags |= gdFTEX_LINESPACE; strex.linespacing = item.toDouble(); } } } FILE *fp = nullptr; if (!RuntimeOption::FontPath.empty()) { fontname = String(RuntimeOption::FontPath.c_str()) + HHVM_FN(basename)(fontname); } auto stream = php_open_plain_file(fontname, "rb", &fp); if (!stream) { raise_warning("Invalid font filename %s", fontname.c_str()); return false; } stream->close(); #ifdef USE_GD_IMGSTRTTF if (extended) { error = gdImageStringFTEx(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str(), &strex); } else { error = gdImageStringFT(im, brect, col, (char*)fontname.c_str(), ptsize, angle, x, y, (char*)str.c_str()); } #else /* !USE_GD_IMGSTRTTF */ error = gdttf(im, brect, col, fontname.c_str(), ptsize, angle, x, y, str.c_str()); #endif if (error) { raise_warning("%s", error); return false; } /* return array with the text's bounding box */ Array ret = Array::CreateDArray(); for (int i = 0; i < 8; i++) { ret.set(i, brect[i]); } return ret; } #endif /* ENABLE_GD_TTF */ const StaticString s_GD_Version("GD Version"), s_FreeType_Support("FreeType Support"), s_FreeType_Linkage("FreeType Linkage"), s_with_freetype("with freetype"), s_with_TTF_library("with TTF library"), s_with_unknown_library("with unknown library"), s_T1Lib_Support("T1Lib_Support"), s_GIF_Read_Support("GIF Read Support"), s_GIF_Create_Support("GIF Create Support"), s_JPG_Support("JPEG Support"), s_PNG_Support("PNG Support"), s_WBMP_Support("WBMP Support"), s_XPM_Support("XPM Support"), s_XBM_Support("XBM Support"), s_JIS_mapped_Japanese_Font_Support("JIS-mapped Japanese Font Support"); Array HHVM_FUNCTION(gd_info) { Array ret = Array::CreateDArray(); ret.set(s_GD_Version, PHP_GD_VERSION_STRING); #ifdef ENABLE_GD_TTF ret.set(s_FreeType_Support, true); #if HAVE_LIBFREETYPE ret.set(s_FreeType_Linkage, s_with_freetype); #elif HAVE_LIBTTF ret.set(s_FreeType_Linkage, s_with_TTF_library); #else ret.set(s_FreeType_Linkage, s_with_unknown_library); #endif #else ret.set(s_FreeType_Support, false); #endif #ifdef HAVE_LIBT1 ret.set(s_T1Lib_Support, true); #else ret.set(s_T1Lib_Support, false); #endif ret.set(s_GIF_Read_Support, true); ret.set(s_GIF_Create_Support, true); #ifdef HAVE_GD_JPG ret.set(s_JPG_Support, true); #else ret.set(s_JPG_Support, false); #endif #ifdef HAVE_GD_PNG ret.set(s_PNG_Support, true); #else ret.set(s_PNG_Support, false); #endif ret.set(s_WBMP_Support, true); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret.set(s_XPM_Support, true); #else ret.set(s_XPM_Support, false); #endif ret.set(s_XBM_Support, true); #if defined(USE_GD_JISX0208) && defined(HAVE_GD_BUNDLED) ret.set(s_JIS_mapped_Japanese_Font_Support, true); #else ret.set(s_JIS_mapped_Japanese_Font_Support, false); #endif return ret; } #define FLIPWORD(a) (((a & 0xff000000) >> 24) | \ ((a & 0x00ff0000) >> 8) | \ ((a & 0x0000ff00) << 8) | \ ((a & 0x000000ff) << 24)) Variant HHVM_FUNCTION(imageloadfont, const String& /*file*/) { // TODO: ind = 5 + zend_list_insert(font, le_gd_font); throw_not_supported(__func__, "NYI"); #ifdef NEVER Variant stream; zval **file; int hdr_size = sizeof(gdFont) - sizeof(char *); int ind, body_size, n = 0, b, i, body_size_check; gdFontPtr font; php_stream *stream; stream = File::Open(file, "rb"); if (!stream) { raise_warning("failed to open file: %s", file.c_str()); return false; } /* Only supports a architecture-dependent binary dump format * at the moment. * The file format is like this on machines with 32-byte integers: * * byte 0-3: (int) number of characters in the font * byte 4-7: (int) value of first character in the font (often 32, space) * byte 8-11: (int) pixel width of each character * byte 12-15: (int) pixel height of each character * bytes 16-: (char) array with character data, one byte per pixel * in each character, for a total of * (nchars*width*height) bytes. */ font = (gdFontPtr) IM_MALLOC(sizeof(gdFont)); CHECK_ALLOC_R(font, sizeof(gdFont), false); b = 0; String hdr = stream->read(hdr_size); if (hdr.length() < hdr_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading header"); } else { raise_warning("Error while reading header"); } stream->close(); return false; } memcpy((void*)font, hdr.c_str(), hdr.length()); i = int64_t(f_tell(stream)); stream->seek(0, SEEK_END); body_size_check = int64_t(f_tell(stream)) - hdr_size; stream->seek(i, SEEK_SET); body_size = font->w * font->h * font->nchars; if (body_size != body_size_check) { font->w = FLIPWORD(font->w); font->h = FLIPWORD(font->h); font->nchars = FLIPWORD(font->nchars); body_size = font->w * font->h * font->nchars; } if (font->nchars <= 0 || font->h <= 0 || font->nchars >= INT_MAX || font->h >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if ((font->nchars * font->h) <= 0 || font->w <= 0 || (font->nchars * font->h) >= INT_MAX || font->w >= INT_MAX) { raise_warning("Error reading font, invalid font header"); IM_FREE(font); stream->close(); return false; } if (body_size != body_size_check) { raise_warning("Error reading font"); IM_FREE(font); stream->close(); return false; } String body = stream->read(body_size); if (body.length() < body_size) { IM_FREE(font); if (stream->eof()) { raise_warning("End of file while reading body"); } else { raise_warning("Error while reading body"); } stream->close(); return false; } font->data = IM_MALLOC(body_size); CHECK_ALLOC_R(font->data, body_size, false); memcpy((void*)font->data, body.c_str(), body.length()); stream->close(); /* Adding 5 to the font index so we will never have font indices * that overlap with the old fonts (with indices 1-5). The first * list index given out is always 1. */ // ind = 5 + zend_list_insert(font, le_gd_font); return ind; #endif } bool HHVM_FUNCTION(imagesetstyle, const Resource& image, const Array& style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int *stylearr; int index; size_t malloc_size = sizeof(int) * style.size(); stylearr = (int *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(stylearr, malloc_size, false); index = 0; for (ArrayIter iter(style); iter; ++iter) { stylearr[index++] = cellToInt(tvToCell(iter.secondVal())); } gdImageSetStyle(im, stylearr, index); IM_FREE(stylearr); return true; } const StaticString s_x("x"), s_y("y"), s_width("width"), s_height("height"); Variant HHVM_FUNCTION(imagecrop, const Resource& image, const Array& rect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; gdRect gdrect; if (rect.exists(s_x)) { gdrect.x = rect[s_x].toInt64(); } else { raise_warning("imagecrop(): Missing x position"); return false; } if (rect.exists(s_y)) { gdrect.y = rect[s_y].toInt64(); } else { raise_warning("imagecrop(): Missing y position"); return false; } if (rect.exists(s_width)) { gdrect.width = rect[s_width].toInt64(); } else { raise_warning("imagecrop(): Missing width position"); return false; } if (rect.exists(s_height)) { gdrect.height = rect[s_height].toInt64(); } else { raise_warning("imagecrop(): Missing height position"); return false; } imcropped = gdImageCrop(im, &gdrect); if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecropauto, const Resource& image, int64_t mode /* = -1 */, double threshold /* = 0.5f */, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imcropped = nullptr; switch (mode) { case -1: mode = GD_CROP_DEFAULT; case GD_CROP_DEFAULT: case GD_CROP_TRANSPARENT: case GD_CROP_BLACK: case GD_CROP_WHITE: case GD_CROP_SIDES: imcropped = gdImageCropAuto(im, mode); break; case GD_CROP_THRESHOLD: if (color < 0) { raise_warning("imagecropauto(): Color argument missing " "with threshold mode"); return false; } imcropped = gdImageCropThreshold(im, color, (float) threshold); break; default: raise_warning("imagecropauto(): Unknown crop mode"); return false; } if (!imcropped) { return false; } return Variant(req::make<Image>(imcropped)); } Variant HHVM_FUNCTION(imagecreatetruecolor, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreateTrueColor(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } bool f_imageistruecolor(const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return im->trueColor; } Variant HHVM_FUNCTION(imagetruecolortopalette, const Resource& image, bool dither, int64_t ncolors) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (ncolors <= 0 || ncolors >= INT_MAX) { raise_warning("Number of colors has to be greater than zero"); return false; } gdImageTrueColorToPalette(im, dither, ncolors); return true; } Variant HHVM_FUNCTION(imagecolormatch, const Resource& image1, const Resource& image2) { gdImagePtr im1 = get_valid_image_resource(image1); if (!im1) return false; gdImagePtr im2 = get_valid_image_resource(image2); if (!im2) return false; int result; result = gdImageColorMatch(im1, im2); switch (result) { case -1: raise_warning("Image1 must be TrueColor"); return false; case -2: raise_warning("Image2 must be Palette"); return false; case -3: raise_warning("Image1 and Image2 must be the same size"); return false; case -4: raise_warning("Image2 must have at least one color"); return false; } return true; } bool HHVM_FUNCTION(imagesetthickness, const Resource& image, int64_t thickness) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetThickness(im, thickness); return true; } bool HHVM_FUNCTION(imagefilledellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledEllipse(im, cx, cy, width, height, color); return true; } bool HHVM_FUNCTION(imagefilledarc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color, int64_t style) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; gdImageFilledArc(im, cx, cy, width, height, start, end, color, style); return true; } Variant HHVM_FUNCTION(imageaffine, const Resource& image, const Array& affine /* = Array() */, const Array& clip /* = Array() */) { gdImagePtr src = get_valid_image_resource(image); if (!src) return false; gdImagePtr dst = nullptr; gdRect rect; gdRectPtr pRect = nullptr; int nelem = affine.size(); int i; double daffine[6]; if (nelem != 6) { raise_warning("imageaffine(): Affine array must have six elements"); return false; } for (i = 0; i < nelem; i++) { if (affine[i].isInteger()) { daffine[i] = affine[i].toInt64(); } else if (affine[i].isDouble() || affine[i].isString()) { daffine[i] = affine[i].toDouble(); } else { raise_warning("imageaffine(): Invalid type for element %i", i); return false; } } if (!clip.empty()) { if (clip.exists(s_x)) { rect.x = clip[s_x].toInt64(); } else { raise_warning("imageaffine(): Missing x position"); return false; } if (clip.exists(s_y)) { rect.y = clip[s_y].toInt64(); } else { raise_warning("imageaffine(): Missing y position"); return false; } if (clip.exists(s_width)) { rect.width = clip[s_width].toInt64(); } else { raise_warning("imageaffine(): Missing width position"); return false; } if (clip.exists(s_height)) { rect.height = clip[s_height].toInt64(); } else { raise_warning("imageaffine(): Missing height position"); return false; } pRect = &rect; } else { rect.x = -1; rect.y = -1; rect.width = gdImageSX(src); rect.height = gdImageSY(src); pRect = nullptr; } if (gdTransformAffineGetImage(&dst, src, pRect, daffine) != GD_TRUE) { return false; } return Variant(req::make<Image>(dst)); } Variant HHVM_FUNCTION(imageaffinematrixconcat, const Array& m1, const Array& m2) { int nelem1 = m1.size(); int nelem2 = m2.size(); int i; double dm1[6]; double dm2[6]; double dmr[6]; Array ret = Array::Create(); if (nelem1 != 6 || nelem2 != 6) { raise_warning("imageaffinematrixconcat(): Affine array must " "have six elements"); return false; } for (i = 0; i < 6; i++) { if (m1[i].isInteger()) { dm1[i] = m1[i].toInt64(); } else if (m1[i].isDouble() || m1[i].isString()) { dm1[i] = m1[i].toDouble(); } else { raise_warning("imageaffinematrixconcat(): Invalid type for " "element %i", i); return false; } if (m2[i].isInteger()) { dm2[i] = m2[i].toInt64(); } else if (m2[i].isDouble() || m2[i].isString()) { dm2[i] = m2[i].toDouble(); } else { raise_warning("imageaffinematrixconcat():Invalid type for" "element %i", i); return false; } } if (gdAffineConcat(dmr, dm1, dm2) != GD_TRUE) { return false; } for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), dmr[i]); } return ret; } Variant HHVM_FUNCTION(imageaffinematrixget, int64_t type, const Variant& options /* = Array() */) { Array ret = Array::Create(); double affine[6]; int res = GD_FALSE, i; switch((gdAffineStandardMatrix)type) { case GD_AFFINE_TRANSLATE: case GD_AFFINE_SCALE: { double x, y; Array aoptions = options.toArray(); if (aoptions.empty()) { raise_warning("imageaffinematrixget(): Array expected as options"); return false; } if (aoptions.exists(s_x)) { x = aoptions[s_x].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (aoptions.exists(s_y)) { y = aoptions[s_y].toDouble(); } else { raise_warning("imageaffinematrixget(): Missing x position"); return false; } if (type == GD_AFFINE_TRANSLATE) { res = gdAffineTranslate(affine, x, y); } else { res = gdAffineScale(affine, x, y); } break; } case GD_AFFINE_ROTATE: case GD_AFFINE_SHEAR_HORIZONTAL: case GD_AFFINE_SHEAR_VERTICAL: { double angle; double doptions = options.toDouble(); if (!doptions) { raise_warning("imageaffinematrixget(): Number is expected as option"); return false; } angle = doptions; if (type == GD_AFFINE_SHEAR_HORIZONTAL) { res = gdAffineShearHorizontal(affine, angle); } else if (type == GD_AFFINE_SHEAR_VERTICAL) { res = gdAffineShearVertical(affine, angle); } else { res = gdAffineRotate(affine, angle); } break; } default: raise_warning("imageaffinematrixget():Invalid type for " "element %" PRId64, type); return false; } if (res == GD_FALSE) { return false; } else { for (i = 0; i < 6; i++) { ret.set(String(i, CopyString), affine[i]); } } return ret; } bool HHVM_FUNCTION(imagealphablending, const Resource& image, bool blendmode) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, blendmode); return true; } bool HHVM_FUNCTION(imagesavealpha, const Resource& image, bool saveflag) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSaveAlpha(im, saveflag); return true; } bool HHVM_FUNCTION(imagelayereffect, const Resource& image, int64_t effect) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageAlphaBlending(im, effect); return true; } Variant HHVM_FUNCTION(imagecolorallocatealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocateAlpha(im, red, green, blue, alpha); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagecolorresolvealpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolveAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorclosestalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestAlpha(im, red, green, blue, alpha); } Variant HHVM_FUNCTION(imagecolorexactalpha, const Resource& image, int64_t red, int64_t green, int64_t blue, int64_t alpha) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExactAlpha(im, red, green, blue, alpha); } bool HHVM_FUNCTION(imagecopyresampled, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = get_valid_image_resource(src_im); if (!im_src) return false; gdImagePtr im_dst = get_valid_image_resource(dst_im); if (!im_dst) return false; gdImageCopyResampled(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagerotate, const Resource& source_image, double angle, int64_t bgd_color, int64_t /*ignore_transparent*/ /* = 0 */) { gdImagePtr im_src = get_valid_image_resource(source_image); if (!im_src) return false; gdImagePtr im_dst = gdImageRotateInterpolated(im_src, angle, bgd_color); if (!im_dst) return false; return Variant(req::make<Image>(im_dst)); } bool HHVM_FUNCTION(imagesettile, const Resource& image, const Resource& tile) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr til = get_valid_image_resource(tile); if (!til) return false; gdImageSetTile(im, til); return true; } bool HHVM_FUNCTION(imagesetbrush, const Resource& image, const Resource& brush) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr tile = get_valid_image_resource(brush); if (!tile) return false; gdImageSetBrush(im, tile); return true; } bool HHVM_FUNCTION(imagesetinterpolation, const Resource& image, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (method == -1) method = GD_BILINEAR_FIXED; return gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method); } Variant HHVM_FUNCTION(imagecreate, int64_t width, int64_t height) { gdImagePtr im; if (width <= 0 || height <= 0 || width >= INT_MAX || height >= INT_MAX) { raise_warning("Invalid image dimensions"); return false; } im = gdImageCreate(width, height); if (!im) { return false; } return Variant(req::make<Image>(im)); } int64_t HHVM_FUNCTION(imagetypes) { int ret=0; ret = IMAGE_TYPE_GIF; #ifdef HAVE_GD_JPG ret |= IMAGE_TYPE_JPEG; #endif #ifdef HAVE_GD_PNG ret |= IMAGE_TYPE_PNG; #endif ret |= IMAGE_TYPE_WBMP; #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) ret |= IMAGE_TYPE_XPM; #endif return ret; } Variant HHVM_FUNCTION(imagecreatefromstring, const String& data) { gdImagePtr im; int imtype; char sig[8]; if (data.length() < 8) { raise_warning("Empty string or invalid image"); return false; } memcpy(sig, data.c_str(), 8); imtype = _php_image_type(sig); switch (imtype) { case PHP_GDIMG_TYPE_JPG: #ifdef HAVE_GD_JPG im = _php_image_create_from_string(data, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpegCtx); #else raise_warning("No JPEG support"); return false; #endif break; case PHP_GDIMG_TYPE_PNG: #ifdef HAVE_GD_PNG im = _php_image_create_from_string(data, "PNG", (gdImagePtr(*)())gdImageCreateFromPngCtx); #else raise_warning("No PNG support"); return false; #endif break; case PHP_GDIMG_TYPE_WEBP: #ifdef HAVE_LIBVPX im = _php_image_create_from_string(data, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebpCtx); #else raise_warning("No webp support (libvpx is needed)"); return false; #endif break; case PHP_GDIMG_TYPE_GIF: im = _php_image_create_from_string(data, "GIF", (gdImagePtr(*)())gdImageCreateFromGifCtx); break; case PHP_GDIMG_TYPE_WBM: im = _php_image_create_from_string(data, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMPCtx); break; case PHP_GDIMG_TYPE_GD2: im = _php_image_create_from_string(data, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Ctx); break; default: raise_warning("Data is not in a recognized format"); return false; } if (!im) { raise_warning("Couldn't create GD Image Stream out of Data"); return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgif, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (gdImagePtr(*)())gdImageCreateFromGif, (gdImagePtr(*)())gdImageCreateFromGifCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #ifdef HAVE_GD_JPG Variant HHVM_FUNCTION(imagecreatefromjpeg, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (gdImagePtr(*)())gdImageCreateFromJpeg, (gdImagePtr(*)())gdImageCreateFromJpegCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_GD_PNG Variant HHVM_FUNCTION(imagecreatefrompng, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_PNG, "PNG", (gdImagePtr(*)())gdImageCreateFromPng, (gdImagePtr(*)())gdImageCreateFromPngCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif #ifdef HAVE_LIBVPX Variant HHVM_FUNCTION(imagecreatefromwebp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (gdImagePtr(*)())gdImageCreateFromWebp, (gdImagePtr(*)())gdImageCreateFromWebpCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromxbm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XBM, "XBM", (gdImagePtr(*)())gdImageCreateFromXbm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) Variant HHVM_FUNCTION(imagecreatefromxpm, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_XPM, "XPM", (gdImagePtr(*)())gdImageCreateFromXpm, (gdImagePtr(*)())nullptr); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } #endif Variant HHVM_FUNCTION(imagecreatefromwbmp, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (gdImagePtr(*)())gdImageCreateFromWBMP, (gdImagePtr(*)())gdImageCreateFromWBMPCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (gdImagePtr(*)())gdImageCreateFromGd, (gdImagePtr(*)())gdImageCreateFromGdCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2, const String& filename) { gdImagePtr im = _php_image_create_from(filename, -1, -1, -1, -1, PHP_GDIMG_TYPE_GD2, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2, (gdImagePtr(*)())gdImageCreateFromGd2Ctx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } Variant HHVM_FUNCTION(imagecreatefromgd2part, const String& filename, int64_t srcx, int64_t srcy, int64_t width, int64_t height) { gdImagePtr im = _php_image_create_from(filename, srcx, srcy, width, height, PHP_GDIMG_TYPE_GD2PART, "GD2", (gdImagePtr(*)())gdImageCreateFromGd2Part, (gdImagePtr(*)())gdImageCreateFromGd2PartCtx); if (im == nullptr) { return false; } return Variant(req::make<Image>(im)); } bool HHVM_FUNCTION(imagegif, const Resource& image, const String& filename /* = null_string */) { return _php_image_output_ctx(image, filename, -1, -1, PHP_GDIMG_TYPE_GIF, "GIF", (void (*)())gdImageGifCtx); } #ifdef HAVE_GD_PNG bool HHVM_FUNCTION(imagepng, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */, int64_t filters /* = -1 */) { return _php_image_output_ctx(image, filename, quality, filters, PHP_GDIMG_TYPE_PNG, "PNG", (void (*)())gdImagePngCtxEx); } #endif #ifdef HAVE_LIBVPX bool HHVM_FUNCTION(imagewebp, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = 80 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_WEBP, "WEBP", (void (*)())gdImageWebpCtx); } #endif #ifdef HAVE_GD_JPG bool HHVM_FUNCTION(imagejpeg, const Resource& image, const String& filename /* = null_string */, int64_t quality /* = -1 */) { return _php_image_output_ctx(image, filename, quality, -1, PHP_GDIMG_TYPE_JPG, "JPEG", (void (*)())gdImageJpegCtx); } #endif bool HHVM_FUNCTION(imagewbmp, const Resource& image, const String& filename /* = null_string */, int64_t foreground /* = -1 */) { return _php_image_output_ctx(image, filename, foreground, -1, PHP_GDIMG_TYPE_WBM, "WBMP", (void (*)())gdImageWBMPCtx); } bool HHVM_FUNCTION(imagegd, const Resource& image, const String& filename /* = null_string */) { return _php_image_output(image, filename, -1, -1, PHP_GDIMG_TYPE_GD, "GD", (void (*)())gdImageGd); } bool HHVM_FUNCTION(imagegd2, const Resource& image, const String& filename /* = null_string */, int64_t chunk_size /* = 0 */, int64_t type /* = 0 */) { return _php_image_output(image, filename, chunk_size, type, PHP_GDIMG_TYPE_GD2, "GD2", (void (*)())gdImageGd2); } bool HHVM_FUNCTION(imagedestroy, const Resource& image) { auto img_res = cast<Image>(image); gdImagePtr im = img_res->get(); if (!im) return false; img_res->reset(); return true; } Variant HHVM_FUNCTION(imagecolorallocate, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; int ct = gdImageColorAllocate(im, red, green, blue); if (ct < 0) { return false; } return ct; } Variant HHVM_FUNCTION(imagepalettecopy, const Resource& dst, const Resource& src) { gdImagePtr dstim = cast<Image>(dst)->get(); gdImagePtr srcim = cast<Image>(src)->get(); if (!dstim || !srcim) return false; gdImagePaletteCopy(dstim, srcim); return true; } Variant HHVM_FUNCTION(imagecolorat, const Resource& image, int64_t x, int64_t y) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (gdImageTrueColor(im)) { if (im->tpixels && gdImageBoundsSafe(im, x, y)) { return gdImageTrueColorPixel(im, x, y); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } else { if (im->pixels && gdImageBoundsSafe(im, x, y)) { return (im->pixels[y][x]); } else { raise_notice("%" PRId64 ",%" PRId64 " is out of bounds", x, y); return false; } } } Variant HHVM_FUNCTION(imagecolorclosest, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosest(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorclosesthwb, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorClosestHWB(im, red, green, blue); } bool HHVM_FUNCTION(imagecolordeallocate, const Resource& image, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; /* We can return right away for a truecolor image as deallocating colours is meaningless here */ if (gdImageTrueColor(im)) return true; if (color >= 0 && color < gdImageColorsTotal(im)) { gdImageColorDeallocate(im, color); return true; } else { raise_warning("Color index %" PRId64 " out of range", color); return false; } } Variant HHVM_FUNCTION(imagecolorresolve, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorResolve(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorexact, const Resource& image, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageColorExact(im, red, green, blue); } Variant HHVM_FUNCTION(imagecolorset, const Resource& image, int64_t index, int64_t red, int64_t green, int64_t blue) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && index < gdImageColorsTotal(im)) { im->red[index] = red; im->green[index] = green; im->blue[index] = blue; return true; } else { return false; } } const StaticString s_red("red"), s_green("green"), s_blue("blue"), s_alpha("alpha"); Variant HHVM_FUNCTION(imagecolorsforindex, const Resource& image, int64_t index) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (index >= 0 && (gdImageTrueColor(im) || index < gdImageColorsTotal(im))) { return make_map_array( s_red, gdImageRed(im,index), s_green, gdImageGreen(im,index), s_blue, gdImageBlue(im,index), s_alpha, gdImageAlpha(im,index) ); } raise_warning("Color index %" PRId64 " out of range", index); return false; } bool HHVM_FUNCTION(imagegammacorrect, const Resource& image, double inputgamma, double outputgamma) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (inputgamma <= 0.0 || outputgamma <= 0.0) { raise_warning("Gamma values should be positive"); return false; } if (gdImageTrueColor(im)) { int x, y, c; for (y = 0; y < gdImageSY(im); y++) { for (x = 0; x < gdImageSX(im); x++) { c = gdImageGetPixel(im, x, y); gdImageSetPixel(im, x, y, gdTrueColor((int)((pow((pow((gdTrueColorGetRed(c)/255.0), inputgamma)),1.0/outputgamma)*255) + .5), (int)((pow((pow((gdTrueColorGetGreen(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5), (int)((pow((pow((gdTrueColorGetBlue(c)/255.0), inputgamma)),1.0/outputgamma) * 255) + .5))); } } return true; } for (int i = 0; i < gdImageColorsTotal(im); i++) { im->red[i] = (int)((pow((pow((im->red[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->green[i] = (int)((pow((pow((im->green[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); im->blue[i] = (int)((pow((pow((im->blue[i]/255.0), inputgamma)), 1.0/outputgamma)*255) + .5); } return true; } bool HHVM_FUNCTION(imagesetpixel, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageSetPixel(im, x, y, color); return true; } bool HHVM_FUNCTION(imageline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagedashedline, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageDashedLine(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagerectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagefilledrectangle, const Resource& image, int64_t x1, int64_t y1, int64_t x2, int64_t y2, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFilledRectangle(im, x1, y1, x2, y2, color); return true; } bool HHVM_FUNCTION(imagearc, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t start, int64_t end, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (end < 0) end %= 360; if (start < 0) start %= 360; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, start, end, color); return true; } bool HHVM_FUNCTION(imageellipse, const Resource& image, int64_t cx, int64_t cy, int64_t width, int64_t height, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; color = SetupAntiAliasedColor(im, color); gdImageArc(im, cx, cy, width, height, 0, 360, color); return true; } bool HHVM_FUNCTION(imagefilltoborder, const Resource& image, int64_t x, int64_t y, int64_t border, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFillToBorder(im, x, y, border, color); return true; } bool HHVM_FUNCTION(imagefill, const Resource& image, int64_t x, int64_t y, int64_t color) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImageFill(im, x, y, color); return true; } Variant HHVM_FUNCTION(imagecolorstotal, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return (gdImageColorsTotal(im)); } Variant HHVM_FUNCTION(imagecolortransparent, const Resource& image, int64_t color /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (color != -1) { // has color argument gdImageColorTransparent(im, color); } return gdImageGetTransparent(im); } TypedValue HHVM_FUNCTION(imageinterlace, const Resource& image, TypedValue interlace /* = 0 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return make_tv<KindOfBoolean>(false); if (!tvIsNull(interlace)) { // has interlace argument gdImageInterlace(im, tvAssertInt(interlace)); } return make_tv<KindOfInt64>(gdImageGetInterlaced(im)); } bool HHVM_FUNCTION(imagepolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 0); } bool HHVM_FUNCTION(imagefilledpolygon, const Resource& image, const Array& points, int64_t num_points, int64_t color) { return php_imagepolygon(image, points, num_points, color, 1); } int64_t HHVM_FUNCTION(imagefontwidth, int64_t font) { return php_imagefontsize(font, 0); } int64_t HHVM_FUNCTION(imagefontheight, int64_t font) { return php_imagefontsize(font, 1); } bool HHVM_FUNCTION(imagechar, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 0); } bool HHVM_FUNCTION(imagecharup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& c, int64_t color) { return php_imagechar(image, font, x, y, c, color, 1); } bool HHVM_FUNCTION(imagestring, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 2); } bool HHVM_FUNCTION(imagestringup, const Resource& image, int64_t font, int64_t x, int64_t y, const String& str, int64_t color) { return php_imagechar(image, font, x, y, str, color, 3); } bool HHVM_FUNCTION(imagecopy, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopy(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h); return true; } bool HHVM_FUNCTION(imagecopymerge, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMerge(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopymergegray, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t src_w, int64_t src_h, int64_t pct) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; gdImageCopyMergeGray(im_dst, im_src, dst_x, dst_y, src_x, src_y, src_w, src_h, pct); return true; } bool HHVM_FUNCTION(imagecopyresized, const Resource& dst_im, const Resource& src_im, int64_t dst_x, int64_t dst_y, int64_t src_x, int64_t src_y, int64_t dst_w, int64_t dst_h, int64_t src_w, int64_t src_h) { gdImagePtr im_src = cast<Image>(src_im)->get(); if (!im_src) return false; gdImagePtr im_dst = cast<Image>(dst_im)->get(); if (!im_dst) return false; if (dst_w <= 0 || dst_h <= 0 || src_w <= 0 || src_h <= 0) { raise_warning("Invalid image dimensions"); return false; } gdImageCopyResized(im_dst, im_src, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h); return true; } Variant HHVM_FUNCTION(imagesx, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSX(im); } Variant HHVM_FUNCTION(imagesy, const Resource& image) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; return gdImageSY(im); } #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE Variant HHVM_FUNCTION(imageftbbox, double size, double angle, const String& font_file, const String& text, const Array& extrainfo /*=[] */) { return php_imagettftext_common(TTFTEXT_BBOX, 1, size, angle, font_file, text, extrainfo); } Variant HHVM_FUNCTION(imagefttext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t col, const String& font_file, const String& text, const Array& extrainfo) { return php_imagettftext_common(TTFTEXT_DRAW, 1, image, size, angle, x, y, col, font_file, text, extrainfo); } #endif #ifdef ENABLE_GD_TTF Variant HHVM_FUNCTION(imagettfbbox, double size, double angle, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_BBOX, 0, size, angle, fontfile, text); } Variant HHVM_FUNCTION(imagettftext, const Resource& image, const Variant& size, const Variant& angle, int64_t x, int64_t y, int64_t color, const String& fontfile, const String& text) { return php_imagettftext_common(TTFTEXT_DRAW, 0, image, size.toDouble(), angle.toDouble(), x, y, color, fontfile, text); } #endif bool HHVM_FUNCTION(image2wbmp, const Resource& image, const String& filename /* = null_string */, int64_t threshold /* = -1 */) { return _php_image_output(image, filename, threshold, -1, PHP_GDIMG_CONVERT_WBM, "WBMP", (void (*)())_php_image_bw_convert); } bool HHVM_FUNCTION(jpeg2wbmp, const String& jpegname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(jpegname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_JPG); } bool HHVM_FUNCTION(png2wbmp, const String& pngname, const String& wbmpname, int64_t dest_height, int64_t dest_width, int64_t threshold) { return _php_image_convert(pngname, wbmpname, dest_height, dest_width, threshold, PHP_GDIMG_TYPE_PNG); } bool HHVM_FUNCTION(imagefilter, const Resource& res, int64_t filtertype, const Variant& arg1 /*=0*/, const Variant& arg2 /*=0*/, const Variant& arg3 /*=0*/, const Variant& arg4 /*=0*/) { gdImagePtr im = get_valid_image_resource(res); if (!im) return false; /* Exists purely to mirror PHP5's invalid arg logic for this function */ #define IMFILT_TYPECHK(n) \ if (!arg##n.isBoolean() && !arg##n.isNumeric(true)) { \ raise_warning("imagefilter() expected boolean/numeric for argument %d", \ (n+2)); \ return false; \ } IMFILT_TYPECHK(1) IMFILT_TYPECHK(2) IMFILT_TYPECHK(3) IMFILT_TYPECHK(4) #undef IMFILT_TYPECHECK using image_filter = bool (*)(gdImagePtr, int, int, int, int); image_filter filters[] = { php_image_filter_negate, php_image_filter_grayscale, php_image_filter_brightness, php_image_filter_contrast, php_image_filter_colorize, php_image_filter_edgedetect, php_image_filter_emboss, php_image_filter_gaussian_blur, php_image_filter_selective_blur, php_image_filter_mean_removal, php_image_filter_smooth, php_image_filter_pixelate, }; auto const num_filters = sizeof(filters) / sizeof(image_filter); if (filtertype >= 0 && filtertype < num_filters) { return filters[filtertype](im, arg1.toInt64(), arg2.toInt64(), arg3.toInt64(), arg4.toInt64()); } return false; } bool HHVM_FUNCTION(imageflip, const Resource& image, int64_t mode /* = -1 */) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; if (mode == -1) mode = GD_FLIP_HORINZONTAL; switch (mode) { case GD_FLIP_VERTICAL: gdImageFlipVertical(im); break; case GD_FLIP_HORINZONTAL: gdImageFlipHorizontal(im); break; case GD_FLIP_BOTH: gdImageFlipBoth(im); break; default: raise_warning("imageflip(): Unknown flip mode"); return false; } return true; } // gdImageConvolution does not exist in our libgd.a, copied from // php's libgd/gd.c /* Filters function added on 2003/12 * by Pierre-Alain Joye (pajoye@pearfr.org) **/ static int hphp_gdImageConvolution(gdImagePtr src, float filter[3][3], float filter_div, float offset) { int x, y, i, j, new_a; float new_r, new_g, new_b; int new_pxl, pxl=0; gdImagePtr srcback; if (src==nullptr) { return 0; } /* We need the orinal image with each safe neoghb. pixel */ srcback = gdImageCreateTrueColor (src->sx, src->sy); gdImageCopy(srcback, src,0,0,0,0,src->sx,src->sy); if (srcback==nullptr) { return 0; } for ( y=0; y<src->sy; y++) { for(x=0; x<src->sx; x++) { new_r = new_g = new_b = 0; new_a = gdImageAlpha(srcback, pxl); for (j=0; j<3; j++) { int yv = std::min(std::max(y - 1 + j, 0), src->sy - 1); for (i=0; i<3; i++) { pxl = gdImageGetPixel(srcback, std::min(std::max(x - 1 + i, 0), src->sx - 1), yv); new_r += (float)gdImageRed(srcback, pxl) * filter[j][i]; new_g += (float)gdImageGreen(srcback, pxl) * filter[j][i]; new_b += (float)gdImageBlue(srcback, pxl) * filter[j][i]; } } new_r = (new_r/filter_div)+offset; new_g = (new_g/filter_div)+offset; new_b = (new_b/filter_div)+offset; new_r = (new_r > 255.0f)? 255.0f : ((new_r < 0.0f)? 0.0f:new_r); new_g = (new_g > 255.0f)? 255.0f : ((new_g < 0.0f)? 0.0f:new_g); new_b = (new_b > 255.0f)? 255.0f : ((new_b < 0.0f)? 0.0f:new_b); new_pxl = gdImageColorAllocateAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); if (new_pxl == -1) { new_pxl = gdImageColorClosestAlpha(src, (int)new_r, (int)new_g, (int)new_b, new_a); } gdImageSetPixel (src, x, y, new_pxl); } } gdImageDestroy(srcback); return 1; } bool HHVM_FUNCTION(imageconvolution, const Resource& image, const Array& matrix, double div, double offset) { gdImagePtr im_src = cast<Image>(image)->get(); if (!im_src) return false; int nelem = matrix.size(); int i, j; float mtx[3][3] = {{0,0,0}, {0,0,0}, {0,0,0}}; Variant v; Array row; if (nelem != 3) { raise_warning("You must have 3x3 array"); return false; } for (i=0; i<3; i++) { if (matrix.exists(i) && (v = matrix[i]).isArray()) { if ((row = v.toArray()).size() != 3) { raise_warning("You must have 3x3 array"); return false; } for (j=0; j<3; j++) { if (row.exists(j)) { mtx[i][j] = row[j].toDouble(); } else { raise_warning("You must have a 3x3 matrix"); return false; } } } } if (hphp_gdImageConvolution(im_src, mtx, div, offset)) { return true; } else { return false; } } bool HHVM_FUNCTION(imageantialias, const Resource& image, bool on) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; SetAntiAliased(im, on); return true; } Variant HHVM_FUNCTION(imagescale, const Resource& image, int64_t newwidth, int64_t newheight /* =-1 */, int64_t method /*=GD_BILINEAR_FIXED*/) { gdImagePtr im = get_valid_image_resource(image); if (!im) return false; gdImagePtr imscaled = nullptr; gdInterpolationMethod old_method; if (method == -1) method = GD_BILINEAR_FIXED; if (newheight < 0) { /* preserve ratio */ long src_x, src_y; src_x = gdImageSX(im); src_y = gdImageSY(im); if (src_x) { newheight = newwidth * src_y / src_x; } } if (newheight <= 0 || newheight > INT_MAX || newwidth <= 0 || newwidth > INT_MAX) { return false; } old_method = im->interpolation_id; if (gdImageSetInterpolationMethod(im, (gdInterpolationMethod) method)) { imscaled = gdImageScale(im, newwidth, newheight); } gdImageSetInterpolationMethod(im, old_method); if (imscaled == nullptr) { return false; } return Variant(req::make<Image>(imscaled)); } namespace { // PHP extension STANDARD: iptc.c inline int php_iptc_put1(req::ptr<File> /*file*/, int spool, unsigned char c, unsigned char** spoolbuf) { if (spool > 0) { g_context->write((const char *)&c, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_get1(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; char cc; c = file->getc(); if (c == EOF) return EOF; if (spool > 0) { cc = c; g_context->write((const char *)&cc, 1); } if (spoolbuf) *(*spoolbuf)++ = c; return c; } inline int php_iptc_read_remaining(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { while (php_iptc_get1(file, spool, spoolbuf) != EOF) continue; return M_EOI; } int php_iptc_skip_variable(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { unsigned int length; int c1, c2; if ((c1 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; if ((c2 = php_iptc_get1(file, spool, spoolbuf)) == EOF) return M_EOI; length = (((unsigned char) c1) << 8) + ((unsigned char) c2); length -= 2; while (length--) { if (php_iptc_get1(file, spool, spoolbuf) == EOF) return M_EOI; } return 0; } int php_iptc_next_marker(const req::ptr<File>& file, int spool, unsigned char **spoolbuf) { int c; /* skip unimportant stuff */ c = php_iptc_get1(file, spool, spoolbuf); if (c == EOF) return M_EOI; while (c != 0xff) { if ((c = php_iptc_get1(file, spool, spoolbuf)) == EOF) { return M_EOI; /* we hit EOF */ } } /* get marker byte, swallowing possible padding */ do { c = php_iptc_get1(file, 0, 0); if (c == EOF) return M_EOI; /* we hit EOF */ else if (c == 0xff) php_iptc_put1(file, spool, (unsigned char)c, spoolbuf); } while (c == 0xff); return (unsigned int) c; } } const StaticString s_size("size"); Variant HHVM_FUNCTION(iptcembed, const String& iptcdata, const String& jpeg_file_name, int64_t spool /* = 0 */) { char psheader[] = "\xFF\xED\0\0Photoshop 3.0\08BIM\x04\x04\0\0\0"; static_assert(sizeof(psheader) == 28, "psheader must be 28 bytes"); unsigned int iptcdata_len = iptcdata.length(); unsigned int marker, inx; unsigned char *spoolbuf = nullptr, *poi = nullptr; bool done = false; bool written = false; auto file = File::Open(jpeg_file_name, "rb"); if (!file) { raise_warning("failed to open file: %s", jpeg_file_name.c_str()); return false; } if (spool < 2) { auto stat = HHVM_FN(fstat)(Resource(file)); // TODO(t7561579) until we can properly handle non-file streams here, don't // pretend we can and crash. if (!stat.isArray()) { raise_warning("unable to stat input"); return false; } auto& stat_arr = stat.toCArrRef(); auto st_size = stat_arr[s_size].toInt64(); if (st_size < 0) { raise_warning("unsupported stream type"); return false; } if (iptcdata_len >= (INT64_MAX - sizeof(psheader) - st_size - 1024 - 1)) { raise_warning("iptcdata too long"); return false; } auto malloc_size = iptcdata_len + sizeof(psheader) + st_size + 1024 + 1; poi = spoolbuf = (unsigned char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(poi, malloc_size, false); memset(poi, 0, malloc_size); } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xFF) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } if (php_iptc_get1(file, spool, poi?&poi:0) != 0xD8) { file->close(); if (spoolbuf) { IM_FREE(spoolbuf); } return false; } while (!done) { marker = php_iptc_next_marker(file, spool, poi?&poi:0); if (marker == M_EOI) { /* EOF */ break; } else if (marker != M_APP13) { php_iptc_put1(file, spool, (unsigned char)marker, poi?&poi:0); } switch (marker) { case M_APP13: /* we are going to write a new APP13 marker, so don't output the old one */ php_iptc_skip_variable(file, 0, 0); php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; case M_APP0: /* APP0 is in each and every JPEG, so when we hit APP0 we insert our new APP13! */ case M_APP1: if (written) { /* don't try to write the data twice */ break; } written = true; php_iptc_skip_variable(file, spool, poi?&poi:0); if (iptcdata_len & 1) { iptcdata_len++; /* make the length even */ } psheader[2] = (iptcdata_len + sizeof(psheader)) >> 8; psheader[3] = (iptcdata_len + sizeof(psheader)) & 0xff; for (inx = 0; inx < sizeof(psheader); inx++) { php_iptc_put1(file, spool, psheader[inx], poi ? &poi : 0); } php_iptc_put1(file, spool, (unsigned char)(iptcdata_len>>8), poi?&poi:0); php_iptc_put1(file, spool, (unsigned char)(iptcdata_len&0xff), poi?&poi:0); for (inx = 0; inx < iptcdata_len; inx++) { php_iptc_put1(file, spool, iptcdata.c_str()[inx], poi?&poi:0); } break; case M_SOS: /* we hit data, no more marker-inserting can be done! */ php_iptc_read_remaining(file, spool, poi?&poi:0); done = true; break; default: php_iptc_skip_variable(file, spool, poi?&poi:0); break; } } file->close(); if (spool < 2) { return String((char *)spoolbuf, poi - spoolbuf, AttachString); } return true; } Variant HHVM_FUNCTION(iptcparse, const String& iptcblock) { unsigned int inx = 0, len, tagsfound = 0; unsigned char *buffer, recnum, dataset, key[16]; unsigned int str_len = iptcblock.length(); Array ret; buffer = (unsigned char *)iptcblock.c_str(); while (inx < str_len) { /* find 1st tag */ if ((buffer[inx] == 0x1c) && ((buffer[inx+1] == 0x01) || (buffer[inx+1] == 0x02))) { break; } else { inx++; } } while (inx < str_len) { if (buffer[ inx++ ] != 0x1c) { /* we ran against some data which does not conform to IPTC - stop parsing! */ break; } if ((inx + 4) >= str_len) break; dataset = buffer[inx++]; recnum = buffer[inx++]; if (buffer[inx] & (unsigned char) 0x80) { /* long tag */ if (inx + 6 >= str_len) break; len = (((long)buffer[inx + 2]) << 24) + (((long)buffer[inx + 3]) << 16) + (((long)buffer[inx + 4]) << 8) + (((long)buffer[inx + 5])); inx += 6; } else { /* short tag */ len = (((unsigned short)buffer[inx])<<8) | (unsigned short)buffer[inx+1]; inx += 2; } snprintf((char *)key, sizeof(key), "%d#%03d", (unsigned int)dataset, (unsigned int)recnum); if ((len > str_len) || (inx + len) > str_len) { break; } String skey((const char *)key, CopyString); if (!ret.exists(skey)) { ret.set(skey, Array::CreateVArray()); } auto const lval = ret.lvalAt(skey); forceToArray(lval).append( String((const char *)(buffer+inx), len, CopyString)); inx += len; tagsfound++; } if (!tagsfound) { return false; } return ret; } // PHP extension exif.c #define NUM_FORMATS 13 #define TAG_FMT_BYTE 1 #define TAG_FMT_STRING 2 #define TAG_FMT_USHORT 3 #define TAG_FMT_ULONG 4 #define TAG_FMT_URATIONAL 5 #define TAG_FMT_SBYTE 6 #define TAG_FMT_UNDEFINED 7 #define TAG_FMT_SSHORT 8 #define TAG_FMT_SLONG 9 #define TAG_FMT_SRATIONAL 10 #define TAG_FMT_SINGLE 11 #define TAG_FMT_DOUBLE 12 #define TAG_FMT_IFD 13 /* Describes tag values */ #define TAG_GPS_VERSION_ID 0x0000 #define TAG_GPS_LATITUDE_REF 0x0001 #define TAG_GPS_LATITUDE 0x0002 #define TAG_GPS_LONGITUDE_REF 0x0003 #define TAG_GPS_LONGITUDE 0x0004 #define TAG_GPS_ALTITUDE_REF 0x0005 #define TAG_GPS_ALTITUDE 0x0006 #define TAG_GPS_TIME_STAMP 0x0007 #define TAG_GPS_SATELLITES 0x0008 #define TAG_GPS_STATUS 0x0009 #define TAG_GPS_MEASURE_MODE 0x000A #define TAG_GPS_DOP 0x000B #define TAG_GPS_SPEED_REF 0x000C #define TAG_GPS_SPEED 0x000D #define TAG_GPS_TRACK_REF 0x000E #define TAG_GPS_TRACK 0x000F #define TAG_GPS_IMG_DIRECTION_REF 0x0010 #define TAG_GPS_IMG_DIRECTION 0x0011 #define TAG_GPS_MAP_DATUM 0x0012 #define TAG_GPS_DEST_LATITUDE_REF 0x0013 #define TAG_GPS_DEST_LATITUDE 0x0014 #define TAG_GPS_DEST_LONGITUDE_REF 0x0015 #define TAG_GPS_DEST_LONGITUDE 0x0016 #define TAG_GPS_DEST_BEARING_REF 0x0017 #define TAG_GPS_DEST_BEARING 0x0018 #define TAG_GPS_DEST_DISTANCE_REF 0x0019 #define TAG_GPS_DEST_DISTANCE 0x001A #define TAG_GPS_PROCESSING_METHOD 0x001B #define TAG_GPS_AREA_INFORMATION 0x001C #define TAG_GPS_DATE_STAMP 0x001D #define TAG_GPS_DIFFERENTIAL 0x001E #define TAG_TIFF_COMMENT 0x00FE /* SHOUDLNT HAPPEN */ #define TAG_NEW_SUBFILE 0x00FE /* New version of subfile tag */ #define TAG_SUBFILE_TYPE 0x00FF /* Old version of subfile tag */ #define TAG_IMAGEWIDTH 0x0100 #define TAG_IMAGEHEIGHT 0x0101 #define TAG_BITS_PER_SAMPLE 0x0102 #define TAG_COMPRESSION 0x0103 #define TAG_PHOTOMETRIC_INTERPRETATION 0x0106 #define TAG_TRESHHOLDING 0x0107 #define TAG_CELL_WIDTH 0x0108 #define TAG_CELL_HEIGHT 0x0109 #define TAG_FILL_ORDER 0x010A #define TAG_DOCUMENT_NAME 0x010D #define TAG_IMAGE_DESCRIPTION 0x010E #define TAG_MAKE 0x010F #define TAG_MODEL 0x0110 #define TAG_STRIP_OFFSETS 0x0111 #define TAG_ORIENTATION 0x0112 #define TAG_SAMPLES_PER_PIXEL 0x0115 #define TAG_ROWS_PER_STRIP 0x0116 #define TAG_STRIP_BYTE_COUNTS 0x0117 #define TAG_MIN_SAMPPLE_VALUE 0x0118 #define TAG_MAX_SAMPLE_VALUE 0x0119 #define TAG_X_RESOLUTION 0x011A #define TAG_Y_RESOLUTION 0x011B #define TAG_PLANAR_CONFIGURATION 0x011C #define TAG_PAGE_NAME 0x011D #define TAG_X_POSITION 0x011E #define TAG_Y_POSITION 0x011F #define TAG_FREE_OFFSETS 0x0120 #define TAG_FREE_BYTE_COUNTS 0x0121 #define TAG_GRAY_RESPONSE_UNIT 0x0122 #define TAG_GRAY_RESPONSE_CURVE 0x0123 #define TAG_RESOLUTION_UNIT 0x0128 #define TAG_PAGE_NUMBER 0x0129 #define TAG_TRANSFER_FUNCTION 0x012D #define TAG_SOFTWARE 0x0131 #define TAG_DATETIME 0x0132 #define TAG_ARTIST 0x013B #define TAG_HOST_COMPUTER 0x013C #define TAG_PREDICTOR 0x013D #define TAG_WHITE_POINT 0x013E #define TAG_PRIMARY_CHROMATICITIES 0x013F #define TAG_COLOR_MAP 0x0140 #define TAG_HALFTONE_HINTS 0x0141 #define TAG_TILE_WIDTH 0x0142 #define TAG_TILE_LENGTH 0x0143 #define TAG_TILE_OFFSETS 0x0144 #define TAG_TILE_BYTE_COUNTS 0x0145 #define TAG_SUB_IFD 0x014A #define TAG_INK_SETMPUTER 0x014C #define TAG_INK_NAMES 0x014D #define TAG_NUMBER_OF_INKS 0x014E #define TAG_DOT_RANGE 0x0150 #define TAG_TARGET_PRINTER 0x0151 #define TAG_EXTRA_SAMPLE 0x0152 #define TAG_SAMPLE_FORMAT 0x0153 #define TAG_S_MIN_SAMPLE_VALUE 0x0154 #define TAG_S_MAX_SAMPLE_VALUE 0x0155 #define TAG_TRANSFER_RANGE 0x0156 #define TAG_JPEG_TABLES 0x015B #define TAG_JPEG_PROC 0x0200 #define TAG_JPEG_INTERCHANGE_FORMAT 0x0201 #define TAG_JPEG_INTERCHANGE_FORMAT_LEN 0x0202 #define TAG_JPEG_RESTART_INTERVAL 0x0203 #define TAG_JPEG_LOSSLESS_PREDICTOR 0x0205 #define TAG_JPEG_POINT_TRANSFORMS 0x0206 #define TAG_JPEG_Q_TABLES 0x0207 #define TAG_JPEG_DC_TABLES 0x0208 #define TAG_JPEG_AC_TABLES 0x0209 #define TAG_YCC_COEFFICIENTS 0x0211 #define TAG_YCC_SUB_SAMPLING 0x0212 #define TAG_YCC_POSITIONING 0x0213 #define TAG_REFERENCE_BLACK_WHITE 0x0214 /* 0x0301 - 0x0302 */ /* 0x0320 */ /* 0x0343 */ /* 0x5001 - 0x501B */ /* 0x5021 - 0x503B */ /* 0x5090 - 0x5091 */ /* 0x5100 - 0x5101 */ /* 0x5110 - 0x5113 */ /* 0x80E3 - 0x80E6 */ /* 0x828d - 0x828F */ #define TAG_COPYRIGHT 0x8298 #define TAG_EXPOSURETIME 0x829A #define TAG_FNUMBER 0x829D #define TAG_EXIF_IFD_POINTER 0x8769 #define TAG_ICC_PROFILE 0x8773 #define TAG_EXPOSURE_PROGRAM 0x8822 #define TAG_SPECTRAL_SENSITY 0x8824 #define TAG_GPS_IFD_POINTER 0x8825 #define TAG_ISOSPEED 0x8827 #define TAG_OPTOELECTRIC_CONVERSION_F 0x8828 /* 0x8829 - 0x882b */ #define TAG_EXIFVERSION 0x9000 #define TAG_DATE_TIME_ORIGINAL 0x9003 #define TAG_DATE_TIME_DIGITIZED 0x9004 #define TAG_COMPONENT_CONFIG 0x9101 #define TAG_COMPRESSED_BITS_PER_PIXEL 0x9102 #define TAG_SHUTTERSPEED 0x9201 #define TAG_APERTURE 0x9202 #define TAG_BRIGHTNESS_VALUE 0x9203 #define TAG_EXPOSURE_BIAS_VALUE 0x9204 #define TAG_MAX_APERTURE 0x9205 #define TAG_SUBJECT_DISTANCE 0x9206 #define TAG_METRIC_MODULE 0x9207 #define TAG_LIGHT_SOURCE 0x9208 #define TAG_FLASH 0x9209 #define TAG_FOCAL_LENGTH 0x920A /* 0x920B - 0x920D */ /* 0x9211 - 0x9216 */ #define TAG_SUBJECT_AREA 0x9214 #define TAG_MAKER_NOTE 0x927C #define TAG_USERCOMMENT 0x9286 #define TAG_SUB_SEC_TIME 0x9290 #define TAG_SUB_SEC_TIME_ORIGINAL 0x9291 #define TAG_SUB_SEC_TIME_DIGITIZED 0x9292 /* 0x923F */ /* 0x935C */ #define TAG_XP_TITLE 0x9C9B #define TAG_XP_COMMENTS 0x9C9C #define TAG_XP_AUTHOR 0x9C9D #define TAG_XP_KEYWORDS 0x9C9E #define TAG_XP_SUBJECT 0x9C9F #define TAG_FLASH_PIX_VERSION 0xA000 #define TAG_COLOR_SPACE 0xA001 #define TAG_COMP_IMAGE_WIDTH 0xA002 /* compressed images only */ #define TAG_COMP_IMAGE_HEIGHT 0xA003 #define TAG_RELATED_SOUND_FILE 0xA004 #define TAG_INTEROP_IFD_POINTER 0xA005 /* IFD pointer */ #define TAG_FLASH_ENERGY 0xA20B #define TAG_SPATIAL_FREQUENCY_RESPONSE 0xA20C #define TAG_FOCALPLANE_X_RES 0xA20E #define TAG_FOCALPLANE_Y_RES 0xA20F #define TAG_FOCALPLANE_RESOLUTION_UNIT 0xA210 #define TAG_SUBJECT_LOCATION 0xA214 #define TAG_EXPOSURE_INDEX 0xA215 #define TAG_SENSING_METHOD 0xA217 #define TAG_FILE_SOURCE 0xA300 #define TAG_SCENE_TYPE 0xA301 #define TAG_CFA_PATTERN 0xA302 #define TAG_CUSTOM_RENDERED 0xA401 #define TAG_EXPOSURE_MODE 0xA402 #define TAG_WHITE_BALANCE 0xA403 #define TAG_DIGITAL_ZOOM_RATIO 0xA404 #define TAG_FOCAL_LENGTH_IN_35_MM_FILM 0xA405 #define TAG_SCENE_CAPTURE_TYPE 0xA406 #define TAG_GAIN_CONTROL 0xA407 #define TAG_CONTRAST 0xA408 #define TAG_SATURATION 0xA409 #define TAG_SHARPNESS 0xA40A #define TAG_DEVICE_SETTING_DESCRIPTION 0xA40B #define TAG_SUBJECT_DISTANCE_RANGE 0xA40C #define TAG_IMAGE_UNIQUE_ID 0xA420 /* Olympus specific tags */ #define TAG_OLYMPUS_SPECIALMODE 0x0200 #define TAG_OLYMPUS_JPEGQUAL 0x0201 #define TAG_OLYMPUS_MACRO 0x0202 #define TAG_OLYMPUS_DIGIZOOM 0x0204 #define TAG_OLYMPUS_SOFTWARERELEASE 0x0207 #define TAG_OLYMPUS_PICTINFO 0x0208 #define TAG_OLYMPUS_CAMERAID 0x0209 /* end Olympus specific tags */ /* Internal */ #define TAG_NONE -1 /* note that -1 <> 0xFFFF */ #define TAG_COMPUTED_VALUE -2 #define TAG_END_OF_LIST 0xFFFD /* Values for TAG_PHOTOMETRIC_INTERPRETATION */ #define PMI_BLACK_IS_ZERO 0 #define PMI_WHITE_IS_ZERO 1 #define PMI_RGB 2 #define PMI_PALETTE_COLOR 3 #define PMI_TRANSPARENCY_MASK 4 #define PMI_SEPARATED 5 #define PMI_YCBCR 6 #define PMI_CIELAB 8 typedef const struct { unsigned short Tag; char *Desc; } tag_info_type; typedef tag_info_type tag_info_array[]; typedef tag_info_type *tag_table_type; #define TAG_TABLE_END \ {((unsigned short)TAG_NONE), "No tag value"},\ {((unsigned short)TAG_COMPUTED_VALUE), "Computed value"},\ {TAG_END_OF_LIST, ""} /* Important for exif_get_tagname() IF value != "" function result is != false */ static const tag_info_array tag_table_IFD = { { 0x000B, "ACDComment"}, { 0x00FE, "NewSubFile"}, /* better name it 'ImageType' ? */ { 0x00FF, "SubFile"}, { 0x0100, "ImageWidth"}, { 0x0101, "ImageLength"}, { 0x0102, "BitsPerSample"}, { 0x0103, "Compression"}, { 0x0106, "PhotometricInterpretation"}, { 0x010A, "FillOrder"}, { 0x010D, "DocumentName"}, { 0x010E, "ImageDescription"}, { 0x010F, "Make"}, { 0x0110, "Model"}, { 0x0111, "StripOffsets"}, { 0x0112, "Orientation"}, { 0x0115, "SamplesPerPixel"}, { 0x0116, "RowsPerStrip"}, { 0x0117, "StripByteCounts"}, { 0x0118, "MinSampleValue"}, { 0x0119, "MaxSampleValue"}, { 0x011A, "XResolution"}, { 0x011B, "YResolution"}, { 0x011C, "PlanarConfiguration"}, { 0x011D, "PageName"}, { 0x011E, "XPosition"}, { 0x011F, "YPosition"}, { 0x0120, "FreeOffsets"}, { 0x0121, "FreeByteCounts"}, { 0x0122, "GrayResponseUnit"}, { 0x0123, "GrayResponseCurve"}, { 0x0124, "T4Options"}, { 0x0125, "T6Options"}, { 0x0128, "ResolutionUnit"}, { 0x0129, "PageNumber"}, { 0x012D, "TransferFunction"}, { 0x0131, "Software"}, { 0x0132, "DateTime"}, { 0x013B, "Artist"}, { 0x013C, "HostComputer"}, { 0x013D, "Predictor"}, { 0x013E, "WhitePoint"}, { 0x013F, "PrimaryChromaticities"}, { 0x0140, "ColorMap"}, { 0x0141, "HalfToneHints"}, { 0x0142, "TileWidth"}, { 0x0143, "TileLength"}, { 0x0144, "TileOffsets"}, { 0x0145, "TileByteCounts"}, { 0x014A, "SubIFD"}, { 0x014C, "InkSet"}, { 0x014D, "InkNames"}, { 0x014E, "NumberOfInks"}, { 0x0150, "DotRange"}, { 0x0151, "TargetPrinter"}, { 0x0152, "ExtraSample"}, { 0x0153, "SampleFormat"}, { 0x0154, "SMinSampleValue"}, { 0x0155, "SMaxSampleValue"}, { 0x0156, "TransferRange"}, { 0x0157, "ClipPath"}, { 0x0158, "XClipPathUnits"}, { 0x0159, "YClipPathUnits"}, { 0x015A, "Indexed"}, { 0x015B, "JPEGTables"}, { 0x015F, "OPIProxy"}, { 0x0200, "JPEGProc"}, { 0x0201, "JPEGInterchangeFormat"}, { 0x0202, "JPEGInterchangeFormatLength"}, { 0x0203, "JPEGRestartInterval"}, { 0x0205, "JPEGLosslessPredictors"}, { 0x0206, "JPEGPointTransforms"}, { 0x0207, "JPEGQTables"}, { 0x0208, "JPEGDCTables"}, { 0x0209, "JPEGACTables"}, { 0x0211, "YCbCrCoefficients"}, { 0x0212, "YCbCrSubSampling"}, { 0x0213, "YCbCrPositioning"}, { 0x0214, "ReferenceBlackWhite"}, { 0x02BC, "ExtensibleMetadataPlatform"}, /* XAP: Extensible Authoring Publishing, obsoleted by XMP: Extensible Metadata Platform */ { 0x0301, "Gamma"}, { 0x0302, "ICCProfileDescriptor"}, { 0x0303, "SRGBRenderingIntent"}, { 0x0320, "ImageTitle"}, { 0x5001, "ResolutionXUnit"}, { 0x5002, "ResolutionYUnit"}, { 0x5003, "ResolutionXLengthUnit"}, { 0x5004, "ResolutionYLengthUnit"}, { 0x5005, "PrintFlags"}, { 0x5006, "PrintFlagsVersion"}, { 0x5007, "PrintFlagsCrop"}, { 0x5008, "PrintFlagsBleedWidth"}, { 0x5009, "PrintFlagsBleedWidthScale"}, { 0x500A, "HalftoneLPI"}, { 0x500B, "HalftoneLPIUnit"}, { 0x500C, "HalftoneDegree"}, { 0x500D, "HalftoneShape"}, { 0x500E, "HalftoneMisc"}, { 0x500F, "HalftoneScreen"}, { 0x5010, "JPEGQuality"}, { 0x5011, "GridSize"}, { 0x5012, "ThumbnailFormat"}, { 0x5013, "ThumbnailWidth"}, { 0x5014, "ThumbnailHeight"}, { 0x5015, "ThumbnailColorDepth"}, { 0x5016, "ThumbnailPlanes"}, { 0x5017, "ThumbnailRawBytes"}, { 0x5018, "ThumbnailSize"}, { 0x5019, "ThumbnailCompressedSize"}, { 0x501A, "ColorTransferFunction"}, { 0x501B, "ThumbnailData"}, { 0x5020, "ThumbnailImageWidth"}, { 0x5021, "ThumbnailImageHeight"}, { 0x5022, "ThumbnailBitsPerSample"}, { 0x5023, "ThumbnailCompression"}, { 0x5024, "ThumbnailPhotometricInterp"}, { 0x5025, "ThumbnailImageDescription"}, { 0x5026, "ThumbnailEquipMake"}, { 0x5027, "ThumbnailEquipModel"}, { 0x5028, "ThumbnailStripOffsets"}, { 0x5029, "ThumbnailOrientation"}, { 0x502A, "ThumbnailSamplesPerPixel"}, { 0x502B, "ThumbnailRowsPerStrip"}, { 0x502C, "ThumbnailStripBytesCount"}, { 0x502D, "ThumbnailResolutionX"}, { 0x502E, "ThumbnailResolutionY"}, { 0x502F, "ThumbnailPlanarConfig"}, { 0x5030, "ThumbnailResolutionUnit"}, { 0x5031, "ThumbnailTransferFunction"}, { 0x5032, "ThumbnailSoftwareUsed"}, { 0x5033, "ThumbnailDateTime"}, { 0x5034, "ThumbnailArtist"}, { 0x5035, "ThumbnailWhitePoint"}, { 0x5036, "ThumbnailPrimaryChromaticities"}, { 0x5037, "ThumbnailYCbCrCoefficients"}, { 0x5038, "ThumbnailYCbCrSubsampling"}, { 0x5039, "ThumbnailYCbCrPositioning"}, { 0x503A, "ThumbnailRefBlackWhite"}, { 0x503B, "ThumbnailCopyRight"}, { 0x5090, "LuminanceTable"}, { 0x5091, "ChrominanceTable"}, { 0x5100, "FrameDelay"}, { 0x5101, "LoopCount"}, { 0x5110, "PixelUnit"}, { 0x5111, "PixelPerUnitX"}, { 0x5112, "PixelPerUnitY"}, { 0x5113, "PaletteHistogram"}, { 0x1000, "RelatedImageFileFormat"}, { 0x800D, "ImageID"}, { 0x80E3, "Matteing"}, /* obsoleted by ExtraSamples */ { 0x80E4, "DataType"}, /* obsoleted by SampleFormat */ { 0x80E5, "ImageDepth"}, { 0x80E6, "TileDepth"}, { 0x828D, "CFARepeatPatternDim"}, { 0x828E, "CFAPattern"}, { 0x828F, "BatteryLevel"}, { 0x8298, "Copyright"}, { 0x829A, "ExposureTime"}, { 0x829D, "FNumber"}, { 0x83BB, "IPTC/NAA"}, { 0x84E3, "IT8RasterPadding"}, { 0x84E5, "IT8ColorTable"}, { 0x8649, "ImageResourceInformation"}, /* PhotoShop */ { 0x8769, "Exif_IFD_Pointer"}, { 0x8773, "ICC_Profile"}, { 0x8822, "ExposureProgram"}, { 0x8824, "SpectralSensity"}, { 0x8828, "OECF"}, { 0x8825, "GPS_IFD_Pointer"}, { 0x8827, "ISOSpeedRatings"}, { 0x8828, "OECF"}, { 0x9000, "ExifVersion"}, { 0x9003, "DateTimeOriginal"}, { 0x9004, "DateTimeDigitized"}, { 0x9101, "ComponentsConfiguration"}, { 0x9102, "CompressedBitsPerPixel"}, { 0x9201, "ShutterSpeedValue"}, { 0x9202, "ApertureValue"}, { 0x9203, "BrightnessValue"}, { 0x9204, "ExposureBiasValue"}, { 0x9205, "MaxApertureValue"}, { 0x9206, "SubjectDistance"}, { 0x9207, "MeteringMode"}, { 0x9208, "LightSource"}, { 0x9209, "Flash"}, { 0x920A, "FocalLength"}, { 0x920B, "FlashEnergy"}, /* 0xA20B in JPEG */ { 0x920C, "SpatialFrequencyResponse"}, /* 0xA20C - - */ { 0x920D, "Noise"}, { 0x920E, "FocalPlaneXResolution"}, /* 0xA20E - - */ { 0x920F, "FocalPlaneYResolution"}, /* 0xA20F - - */ { 0x9210, "FocalPlaneResolutionUnit"}, /* 0xA210 - - */ { 0x9211, "ImageNumber"}, { 0x9212, "SecurityClassification"}, { 0x9213, "ImageHistory"}, { 0x9214, "SubjectLocation"}, /* 0xA214 - - */ { 0x9215, "ExposureIndex"}, /* 0xA215 - - */ { 0x9216, "TIFF/EPStandardID"}, { 0x9217, "SensingMethod"}, /* 0xA217 - - */ { 0x923F, "StoNits"}, { 0x927C, "MakerNote"}, { 0x9286, "UserComment"}, { 0x9290, "SubSecTime"}, { 0x9291, "SubSecTimeOriginal"}, { 0x9292, "SubSecTimeDigitized"}, { 0x935C, "ImageSourceData"}, /* "Adobe Photoshop Document Data Block": 8BIM... */ { 0x9c9b, "Title" }, /* Win XP specific, Unicode */ { 0x9c9c, "Comments" }, /* Win XP specific, Unicode */ { 0x9c9d, "Author" }, /* Win XP specific, Unicode */ { 0x9c9e, "Keywords" }, /* Win XP specific, Unicode */ { 0x9c9f, "Subject" }, /* Win XP specific, Unicode, not to be confused with SubjectDistance and SubjectLocation */ { 0xA000, "FlashPixVersion"}, { 0xA001, "ColorSpace"}, { 0xA002, "ExifImageWidth"}, { 0xA003, "ExifImageLength"}, { 0xA004, "RelatedSoundFile"}, { 0xA005, "InteroperabilityOffset"}, { 0xA20B, "FlashEnergy"}, /* 0x920B in TIFF/EP */ { 0xA20C, "SpatialFrequencyResponse"}, /* 0x920C - - */ { 0xA20D, "Noise"}, { 0xA20E, "FocalPlaneXResolution"}, /* 0x920E - - */ { 0xA20F, "FocalPlaneYResolution"}, /* 0x920F - - */ { 0xA210, "FocalPlaneResolutionUnit"}, /* 0x9210 - - */ { 0xA211, "ImageNumber"}, { 0xA212, "SecurityClassification"}, { 0xA213, "ImageHistory"}, { 0xA214, "SubjectLocation"}, /* 0x9214 - - */ { 0xA215, "ExposureIndex"}, /* 0x9215 - - */ { 0xA216, "TIFF/EPStandardID"}, { 0xA217, "SensingMethod"}, /* 0x9217 - - */ { 0xA300, "FileSource"}, { 0xA301, "SceneType"}, { 0xA302, "CFAPattern"}, { 0xA401, "CustomRendered"}, { 0xA402, "ExposureMode"}, { 0xA403, "WhiteBalance"}, { 0xA404, "DigitalZoomRatio"}, { 0xA405, "FocalLengthIn35mmFilm"}, { 0xA406, "SceneCaptureType"}, { 0xA407, "GainControl"}, { 0xA408, "Contrast"}, { 0xA409, "Saturation"}, { 0xA40A, "Sharpness"}, { 0xA40B, "DeviceSettingDescription"}, { 0xA40C, "SubjectDistanceRange"}, { 0xA420, "ImageUniqueID"}, TAG_TABLE_END }; static const tag_info_array tag_table_GPS = { { 0x0000, "GPSVersion"}, { 0x0001, "GPSLatitudeRef"}, { 0x0002, "GPSLatitude"}, { 0x0003, "GPSLongitudeRef"}, { 0x0004, "GPSLongitude"}, { 0x0005, "GPSAltitudeRef"}, { 0x0006, "GPSAltitude"}, { 0x0007, "GPSTimeStamp"}, { 0x0008, "GPSSatellites"}, { 0x0009, "GPSStatus"}, { 0x000A, "GPSMeasureMode"}, { 0x000B, "GPSDOP"}, { 0x000C, "GPSSpeedRef"}, { 0x000D, "GPSSpeed"}, { 0x000E, "GPSTrackRef"}, { 0x000F, "GPSTrack"}, { 0x0010, "GPSImgDirectionRef"}, { 0x0011, "GPSImgDirection"}, { 0x0012, "GPSMapDatum"}, { 0x0013, "GPSDestLatitudeRef"}, { 0x0014, "GPSDestLatitude"}, { 0x0015, "GPSDestLongitudeRef"}, { 0x0016, "GPSDestLongitude"}, { 0x0017, "GPSDestBearingRef"}, { 0x0018, "GPSDestBearing"}, { 0x0019, "GPSDestDistanceRef"}, { 0x001A, "GPSDestDistance"}, { 0x001B, "GPSProcessingMode"}, { 0x001C, "GPSAreaInformation"}, { 0x001D, "GPSDateStamp"}, { 0x001E, "GPSDifferential"}, TAG_TABLE_END }; static const tag_info_array tag_table_IOP = { { 0x0001, "InterOperabilityIndex"}, /* should be 'R98' or 'THM' */ { 0x0002, "InterOperabilityVersion"}, { 0x1000, "RelatedFileFormat"}, { 0x1001, "RelatedImageWidth"}, { 0x1002, "RelatedImageHeight"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CANON = { { 0x0001, "ModeArray"}, /* guess */ { 0x0004, "ImageInfo"}, /* guess */ { 0x0006, "ImageType"}, { 0x0007, "FirmwareVersion"}, { 0x0008, "ImageNumber"}, { 0x0009, "OwnerName"}, { 0x000C, "Camera"}, { 0x000F, "CustomFunctions"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_CASIO = { { 0x0001, "RecordingMode"}, { 0x0002, "Quality"}, { 0x0003, "FocusingMode"}, { 0x0004, "FlashMode"}, { 0x0005, "FlashIntensity"}, { 0x0006, "ObjectDistance"}, { 0x0007, "WhiteBalance"}, { 0x000A, "DigitalZoom"}, { 0x000B, "Sharpness"}, { 0x000C, "Contrast"}, { 0x000D, "Saturation"}, { 0x0014, "CCDSensitivity"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_FUJI = { { 0x0000, "Version"}, { 0x1000, "Quality"}, { 0x1001, "Sharpness"}, { 0x1002, "WhiteBalance"}, { 0x1003, "Color"}, { 0x1004, "Tone"}, { 0x1010, "FlashMode"}, { 0x1011, "FlashStrength"}, { 0x1020, "Macro"}, { 0x1021, "FocusMode"}, { 0x1030, "SlowSync"}, { 0x1031, "PictureMode"}, { 0x1100, "ContTake"}, { 0x1300, "BlurWarning"}, { 0x1301, "FocusWarning"}, { 0x1302, "AEWarning "}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON = { { 0x0003, "Quality"}, { 0x0004, "ColorMode"}, { 0x0005, "ImageAdjustment"}, { 0x0006, "CCDSensitivity"}, { 0x0007, "WhiteBalance"}, { 0x0008, "Focus"}, { 0x000a, "DigitalZoom"}, { 0x000b, "Converter"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_NIKON_990 = { { 0x0001, "Version"}, { 0x0002, "ISOSetting"}, { 0x0003, "ColorMode"}, { 0x0004, "Quality"}, { 0x0005, "WhiteBalance"}, { 0x0006, "ImageSharpening"}, { 0x0007, "FocusMode"}, { 0x0008, "FlashSetting"}, { 0x000F, "ISOSelection"}, { 0x0080, "ImageAdjustment"}, { 0x0082, "AuxiliaryLens"}, { 0x0085, "ManualFocusDistance"}, { 0x0086, "DigitalZoom"}, { 0x0088, "AFFocusPosition"}, { 0x0010, "DataDump"}, TAG_TABLE_END }; static const tag_info_array tag_table_VND_OLYMPUS = { { 0x0200, "SpecialMode"}, { 0x0201, "JPEGQuality"}, { 0x0202, "Macro"}, { 0x0204, "DigitalZoom"}, { 0x0207, "SoftwareRelease"}, { 0x0208, "PictureInfo"}, { 0x0209, "CameraId"}, { 0x0F00, "DataDump"}, TAG_TABLE_END }; typedef enum mn_byte_order_t { MN_ORDER_INTEL = 0, MN_ORDER_MOTOROLA = 1, MN_ORDER_NORMAL } mn_byte_order_t; typedef enum mn_offset_mode_t { MN_OFFSET_NORMAL, MN_OFFSET_MAKER, MN_OFFSET_GUESS } mn_offset_mode_t; typedef struct { tag_table_type tag_table; char *make; char *model; char *id_string; int id_string_len; int offset; mn_byte_order_t byte_order; mn_offset_mode_t offset_mode; } maker_note_type; static const maker_note_type maker_note_array[] = { { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_INTEL, MN_OFFSET_NORMAL}, /* { tag_table_VND_CANON, "Canon", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL},*/ { tag_table_VND_CASIO, "CASIO", nullptr, nullptr, 0, 0, MN_ORDER_MOTOROLA, MN_OFFSET_NORMAL}, { tag_table_VND_FUJI, "FUJIFILM", nullptr, "FUJIFILM\x0C\x00\x00\x00", 12, 12, MN_ORDER_INTEL, MN_OFFSET_MAKER}, { tag_table_VND_NIKON, "NIKON", nullptr, "Nikon\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_NIKON_990, "NIKON", nullptr, nullptr, 0, 0, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, { tag_table_VND_OLYMPUS, "OLYMPUS OPTICAL CO.,LTD", nullptr, "OLYMP\x00\x01\x00", 8, 8, MN_ORDER_NORMAL, MN_OFFSET_NORMAL}, }; /* Get headername for tag_num or nullptr if not defined */ static char * exif_get_tagname(int tag_num, char *ret, int len, tag_table_type tag_table) { int i, t; char tmp[32]; for (i = 0; (t = tag_table[i].Tag) != TAG_END_OF_LIST; i++) { if (t == tag_num) { if (ret && len) { string_copy(ret, tag_table[i].Desc, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return tag_table[i].Desc; } } if (ret && len) { snprintf(tmp, sizeof(tmp), "UndefinedTag:0x%04X", tag_num); string_copy(ret, tmp, abs(len)); if (len < 0) { memset(ret + strlen(ret), ' ', -len - strlen(ret) - 1); ret[-len - 1] = '\0'; } return ret; } return ""; } #define MAX_IFD_NESTING_LEVEL 100 #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif typedef struct { int num; int den; } signed_rational; typedef struct { unsigned int num; unsigned int den; } unsigned_rational; typedef union _image_info_value { char *s; unsigned u; int i; float f; double d; signed_rational sr; unsigned_rational ur; union _image_info_value *list; } image_info_value; typedef struct { WORD tag; WORD format; DWORD length; DWORD dummy; /* value ptr of tiff directory entry */ char *name; image_info_value value; } image_info_data; typedef struct { int count; image_info_data *list; } image_info_list; #define SECTION_FILE 0 #define SECTION_COMPUTED 1 #define SECTION_ANY_TAG 2 #define SECTION_IFD0 3 #define SECTION_THUMBNAIL 4 #define SECTION_COMMENT 5 #define SECTION_APP0 6 #define SECTION_EXIF 7 #define SECTION_FPIX 8 #define SECTION_GPS 9 #define SECTION_INTEROP 10 #define SECTION_APP12 11 #define SECTION_WINXP 12 #define SECTION_MAKERNOTE 13 #define SECTION_COUNT 14 #define FOUND_FILE (1<<SECTION_FILE) #define FOUND_COMPUTED (1<<SECTION_COMPUTED) #define FOUND_ANY_TAG (1<<SECTION_ANY_TAG) #define FOUND_IFD0 (1<<SECTION_IFD0) #define FOUND_THUMBNAIL (1<<SECTION_THUMBNAIL) #define FOUND_COMMENT (1<<SECTION_COMMENT) #define FOUND_APP0 (1<<SECTION_APP0) #define FOUND_EXIF (1<<SECTION_EXIF) #define FOUND_FPIX (1<<SECTION_FPIX) #define FOUND_GPS (1<<SECTION_GPS) #define FOUND_INTEROP (1<<SECTION_INTEROP) #define FOUND_APP12 (1<<SECTION_APP12) #define FOUND_WINXP (1<<SECTION_WINXP) #define FOUND_MAKERNOTE (1<<SECTION_MAKERNOTE) const StaticString s_FILE("FILE"), s_COMPUTED("COMPUTED"), s_ANY_TAG("ANY_TAG"), s_IFD0("IFD0"), s_THUMBNAIL("THUMBNAIL"), s_COMMENT("COMMENT"), s_APP0("APP0"), s_EXIF("EXIF"), s_FPIX("FPIX"), s_GPS("GPS"), s_INTEROP("INTEROP"), s_APP12("APP12"), s_WINXP("WINXP"), s_MAKERNOTE("MAKERNOTE"); static String exif_get_sectionname(int section) { switch(section) { case SECTION_FILE: return s_FILE; case SECTION_COMPUTED: return s_COMPUTED; case SECTION_ANY_TAG: return s_ANY_TAG; case SECTION_IFD0: return s_IFD0; case SECTION_THUMBNAIL: return s_THUMBNAIL; case SECTION_COMMENT: return s_COMMENT; case SECTION_APP0: return s_APP0; case SECTION_EXIF: return s_EXIF; case SECTION_FPIX: return s_FPIX; case SECTION_GPS: return s_GPS; case SECTION_INTEROP: return s_INTEROP; case SECTION_APP12: return s_APP12; case SECTION_WINXP: return s_WINXP; case SECTION_MAKERNOTE: return s_MAKERNOTE; } return empty_string(); } static tag_table_type exif_get_tag_table(int section) { switch(section) { case SECTION_FILE: return &tag_table_IFD[0]; case SECTION_COMPUTED: return &tag_table_IFD[0]; case SECTION_ANY_TAG: return &tag_table_IFD[0]; case SECTION_IFD0: return &tag_table_IFD[0]; case SECTION_THUMBNAIL: return &tag_table_IFD[0]; case SECTION_COMMENT: return &tag_table_IFD[0]; case SECTION_APP0: return &tag_table_IFD[0]; case SECTION_EXIF: return &tag_table_IFD[0]; case SECTION_FPIX: return &tag_table_IFD[0]; case SECTION_GPS: return &tag_table_GPS[0]; case SECTION_INTEROP: return &tag_table_IOP[0]; case SECTION_APP12: return &tag_table_IFD[0]; case SECTION_WINXP: return &tag_table_IFD[0]; } return &tag_table_IFD[0]; } /* Return list of sectionnames specified by sectionlist. Return value must be freed */ static char *exif_get_sectionlist(int sectionlist) { int i, len, ml = 0; char *sections; for(i=0; i<SECTION_COUNT; i++) { ml += exif_get_sectionname(i).size() + 2; } sections = (char *)IM_MALLOC(ml + 1); CHECK_ALLOC_R(sections, ml + 1, nullptr); sections[0] = '\0'; len = 0; for(i=0; i<SECTION_COUNT; i++) { if (sectionlist&(1<<i)) { snprintf(sections+len, ml-len, "%s, ", exif_get_sectionname(i).c_str()); len = strlen(sections); } } if (len>2) { sections[len-2] = '\0'; } return sections; } /* This structure stores Exif header image elements in a simple manner Used to store camera data as extracted from the various ways that it can be stored in a nexif header */ typedef struct { int type; size_t size; unsigned char *data; } file_section; typedef struct { int count; file_section *list; } file_section_list; typedef struct { image_filetype filetype; size_t width, height; size_t size; size_t offset; char *data; } thumbnail_data; typedef struct { char *value; size_t size; int tag; } xp_field_type; typedef struct { int count; xp_field_type *list; } xp_field_list; /* This structure is used to store a section of a Jpeg file. */ typedef struct { req::ptr<File> infile; String FileName; time_t FileDateTime; size_t FileSize; image_filetype FileType; int Height, Width; int IsColor; char *make; char *model; float ApertureFNumber; float ExposureTime; double FocalplaneUnits; float CCDWidth; double FocalplaneXRes; size_t ExifImageWidth; float FocalLength; float Distance; int motorola_intel; /* 1 Motorola; 0 Intel */ char *UserComment; int UserCommentLength; char *UserCommentEncoding; char *encode_unicode; char *decode_unicode_be; char *decode_unicode_le; char *encode_jis; char *decode_jis_be; char *decode_jis_le; /* EXIF standard defines Copyright as "<Photographer> [ '\0' <Editor> ] ['\0']" */ char *Copyright; char *CopyrightPhotographer; char *CopyrightEditor; xp_field_list xp_fields; thumbnail_data Thumbnail; /* other */ int sections_found; /* FOUND_<marker> */ image_info_list info_list[SECTION_COUNT]; /* for parsing */ bool read_thumbnail; bool read_all; int ifd_nesting_level; /* internal */ file_section_list file; } image_info_type; typedef struct { int bits_per_sample; size_t width; size_t height; int num_components; } jpeg_sof_info; /* forward declarations */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index); static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table); /* Add a file_section to image_info returns the used block or -1. if size>0 and data == nullptr buffer of size is allocated */ static int exif_file_sections_add(image_info_type *ImageInfo, int type, size_t size, unsigned char *data) { file_section *tmp; int count = ImageInfo->file.count; size_t realloc_size = (count+1) * sizeof(file_section); tmp = (file_section *)IM_REALLOC(ImageInfo->file.list, realloc_size); CHECK_ALLOC_R(tmp, realloc_size, -1); ImageInfo->file.list = tmp; ImageInfo->file.list[count].type = 0xFFFF; ImageInfo->file.list[count].data = nullptr; ImageInfo->file.list[count].size = 0; ImageInfo->file.count = count+1; if (!size) { data = nullptr; } else if (data == nullptr) { data = (unsigned char *)IM_MALLOC(size); if (data == nullptr) IM_FREE(tmp); CHECK_ALLOC_R(data, size, -1); } ImageInfo->file.list[count].type = type; ImageInfo->file.list[count].data = data; ImageInfo->file.list[count].size = size; return count; } /* get length of string if buffer if less than buffer size or buffer size */ static size_t php_strnlen(char* str, size_t maxlen) { size_t len = 0; if (str && maxlen && *str) { do { len++; } while (--maxlen && *(++str)); } return len; } /* Add a value to image_info */ static void exif_iif_add_value(image_info_type *image_info, int section_index, char *name, int tag, int format, int length, void* value, int motorola_intel) { size_t idex; void *vptr; image_info_value *info_value; image_info_data *info_data; image_info_data *list; if (length < 0) { return; } size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data*) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = tag; info_data->format = format; info_data->length = length; PHP_STRDUP(info_data->name, name); info_value = &info_data->value; switch (format) { case TAG_FMT_STRING: if (value) { length = php_strnlen((char*)value, length); // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ info_data->tag = TAG_FMT_UNDEFINED;/* otherwise not freed from memory */ case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (!length) break; case TAG_FMT_UNDEFINED: if (value) { /* do not recompute length here */ // TODO // if (PG(magic_quotes_runtime)) { // info_value->s = php_addslashes(value, length, &length, 0); // } else { PHP_STRNDUP(info_value->s, (const char *)value, length); // } info_data->length = (info_value->s ? length : 0); } else { info_data->length = 0; PHP_STRDUP(info_value->s, ""); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: if (length==0) { break; } else if (length>1) { info_value->list = (image_info_value*)IM_CALLOC(length, sizeof(image_info_value)); CHECK_ALLOC(info_value->list, sizeof(image_info_value)); } else { info_value = &info_data->value; } for (idex=0,vptr=value; idex<(size_t)length; idex++,vptr=(char *) vptr + get_php_tiff_bytes_per_format(format)) { if (length>1) { info_value = &info_data->value.list[idex]; } switch (format) { case TAG_FMT_USHORT: info_value->u = php_ifd_get16u(vptr, motorola_intel); break; case TAG_FMT_ULONG: info_value->u = php_ifd_get32u(vptr, motorola_intel); break; case TAG_FMT_URATIONAL: info_value->ur.num = php_ifd_get32u(vptr, motorola_intel); info_value->ur.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SSHORT: info_value->i = php_ifd_get16s(vptr, motorola_intel); break; case TAG_FMT_SLONG: info_value->i = php_ifd_get32s(vptr, motorola_intel); break; case TAG_FMT_SRATIONAL: info_value->sr.num = php_ifd_get32u(vptr, motorola_intel); info_value->sr.den = php_ifd_get32u(4+(char *)vptr, motorola_intel); break; case TAG_FMT_SINGLE: info_value->f = *(float *)value; case TAG_FMT_DOUBLE: info_value->d = *(double *)value; break; } } } image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a tag from IFD to image_info */ static void exif_iif_add_tag(image_info_type *image_info, int section_index, char *name, int tag, int format, size_t length, void* value) { exif_iif_add_value(image_info, section_index, name, tag, format, (int)length, value, image_info->motorola_intel); } /* Evaluate number, be it int, rational, or float from directory. */ static double exif_convert_any_format(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return (double)php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (double)php_ifd_get32s(value, motorola_intel) / s_den; } case TAG_FMT_SSHORT: return (signed short)php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (double)*(float *)value; case TAG_FMT_DOUBLE: return *(double *)value; } return 0; } /* Evaluate number, be it int, rational, or float from directory. */ static size_t exif_convert_any_to_int(void *value, int format, int motorola_intel) { int s_den; unsigned u_den; switch(format) { case TAG_FMT_SBYTE: return *(signed char *)value; case TAG_FMT_BYTE: return *(unsigned char *)value; case TAG_FMT_USHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_ULONG: return php_ifd_get32u(value, motorola_intel); case TAG_FMT_URATIONAL: u_den = php_ifd_get32u(4+(char *)value, motorola_intel); if (u_den == 0) { return 0; } else { return php_ifd_get32u(value, motorola_intel) / u_den; } case TAG_FMT_SRATIONAL: s_den = php_ifd_get32s(4+(char *)value, motorola_intel); if (s_den == 0) { return 0; } else { return (size_t)((double)php_ifd_get32s(value, motorola_intel) / s_den); } case TAG_FMT_SSHORT: return php_ifd_get16u(value, motorola_intel); case TAG_FMT_SLONG: return php_ifd_get32s(value, motorola_intel); /* Not sure if this is correct (never seen float used in Exif format) */ case TAG_FMT_SINGLE: return (size_t)*(float *)value; case TAG_FMT_DOUBLE: return (size_t)*(double *)value; } return 0; } /* Get 16 bits motorola order (always) for jpeg header stuff. */ static int php_jpg_get16(void *value) { return (((unsigned char *)value)[0] << 8) | ((unsigned char *)value)[1]; } /* Write 16 bit unsigned value to data */ static void php_ifd_set16u(char *data, unsigned int value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF00) >> 8; data[1] = (value & 0x00FF); } else { data[1] = (value & 0xFF00) >> 8; data[0] = (value & 0x00FF); } } /* Convert a 32 bit unsigned value from file's native byte order */ static void php_ifd_set32u(char *data, size_t value, int motorola_intel) { if (motorola_intel) { data[0] = (value & 0xFF000000) >> 24; data[1] = (value & 0x00FF0000) >> 16; data[2] = (value & 0x0000FF00) >> 8; data[3] = (value & 0x000000FF); } else { data[3] = (value & 0xFF000000) >> 24; data[2] = (value & 0x00FF0000) >> 16; data[1] = (value & 0x0000FF00) >> 8; data[0] = (value & 0x000000FF); } } /* Create a value for an ifd from an info_data pointer */ static void* exif_ifd_make_value(image_info_data *info_data, int motorola_intel) { size_t byte_count; char *value_ptr, *data_ptr; size_t i; image_info_value *info_value; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; size_t malloc_size = byte_count > 4 ? byte_count : 4; value_ptr = (char *)IM_MALLOC(malloc_size); CHECK_ALLOC_R(value_ptr, malloc_size, nullptr); memset(value_ptr, 0, 4); if (!info_data->length) { return value_ptr; } if (info_data->format == TAG_FMT_UNDEFINED || info_data->format == TAG_FMT_STRING || (byte_count>1 && (info_data->format == TAG_FMT_BYTE || info_data->format == TAG_FMT_SBYTE))) { memmove(value_ptr, info_data->value.s, byte_count); return value_ptr; } else if (info_data->format == TAG_FMT_BYTE) { *value_ptr = info_data->value.u; return value_ptr; } else if (info_data->format == TAG_FMT_SBYTE) { *value_ptr = info_data->value.i; return value_ptr; } else { data_ptr = value_ptr; for(i=0; i<info_data->length; i++) { if (info_data->length==1) { info_value = &info_data->value; } else { info_value = &info_data->value.list[i]; } switch(info_data->format) { case TAG_FMT_USHORT: php_ifd_set16u(data_ptr, info_value->u, motorola_intel); data_ptr += 2; break; case TAG_FMT_ULONG: php_ifd_set32u(data_ptr, info_value->u, motorola_intel); data_ptr += 4; break; case TAG_FMT_SSHORT: php_ifd_set16u(data_ptr, info_value->i, motorola_intel); data_ptr += 2; break; case TAG_FMT_SLONG: php_ifd_set32u(data_ptr, info_value->i, motorola_intel); data_ptr += 4; break; case TAG_FMT_URATIONAL: php_ifd_set32u(data_ptr, info_value->sr.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->sr.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SRATIONAL: php_ifd_set32u(data_ptr, info_value->ur.num, motorola_intel); php_ifd_set32u(data_ptr+4, info_value->ur.den, motorola_intel); data_ptr += 8; break; case TAG_FMT_SINGLE: memmove(data_ptr, &info_value->f, 4); data_ptr += 4; break; case TAG_FMT_DOUBLE: memmove(data_ptr, &info_value->d, 8); data_ptr += 8; break; } } } return value_ptr; } /* Process a COM marker. We want to print out the marker contents as legible text; we must guard against random junk and varying newline representations. */ static void exif_process_COM(image_info_type *image_info, char *value, size_t length) { exif_iif_add_tag(image_info, SECTION_COMMENT, "Comment", TAG_COMPUTED_VALUE, TAG_FMT_STRING, length-2, value+2); } /* Check and build thumbnail */ static void exif_thumbnail_build(image_info_type *ImageInfo) { size_t new_size, new_move, new_value; char *new_data; void *value_ptr; int i, byte_count; image_info_list *info_list; image_info_data *info_data; if (!ImageInfo->read_thumbnail || !ImageInfo->Thumbnail.offset || !ImageInfo->Thumbnail.size) { return; /* ignore this call */ } switch(ImageInfo->Thumbnail.filetype) { default: case IMAGE_FILETYPE_JPEG: /* done */ break; case IMAGE_FILETYPE_TIFF_II: case IMAGE_FILETYPE_TIFF_MM: info_list = &ImageInfo->info_list[SECTION_THUMBNAIL]; new_size = 8 + 2 + info_list->count * 12 + 4; new_value= new_size; /* offset for ifd values outside ifd directory */ for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (byte_count > 4) { new_size += byte_count; } } new_move = new_size; new_data = (char *)IM_REALLOC(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size + new_size); CHECK_ALLOC(new_data, ImageInfo->Thumbnail.size + new_size); ImageInfo->Thumbnail.data = new_data; memmove(ImageInfo->Thumbnail.data + new_move, ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size); ImageInfo->Thumbnail.size += new_size; /* fill in data */ if (ImageInfo->motorola_intel) { memmove(new_data, "MM\x00\x2a\x00\x00\x00\x08", 8); } else { memmove(new_data, "II\x2a\x00\x08\x00\x00\x00", 8); } new_data += 8; php_ifd_set16u(new_data, info_list->count, ImageInfo->motorola_intel); new_data += 2; for (i=0; i<info_list->count; i++) { info_data = &info_list->list[i]; byte_count = get_php_tiff_bytes_per_format(info_data->format) * info_data->length; if (info_data->tag==TAG_STRIP_OFFSETS || info_data->tag==TAG_JPEG_INTERCHANGE_FORMAT) { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, TAG_FMT_ULONG, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, 1, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 8, new_move, ImageInfo->motorola_intel); } else { php_ifd_set16u(new_data + 0, info_data->tag, ImageInfo->motorola_intel); php_ifd_set16u(new_data + 2, info_data->format, ImageInfo->motorola_intel); php_ifd_set32u(new_data + 4, info_data->length, ImageInfo->motorola_intel); value_ptr = exif_ifd_make_value(info_data, ImageInfo->motorola_intel); if (byte_count <= 4) { memmove(new_data+8, value_ptr, 4); } else { php_ifd_set32u(new_data+8, new_value, ImageInfo->motorola_intel); memmove(ImageInfo->Thumbnail.data+new_value, value_ptr, byte_count); new_value += byte_count; } if (value_ptr) IM_FREE(value_ptr); } new_data += 12; } memset(new_data, 0, 4); /* next ifd pointer */ break; } } /* Grab the thumbnail, corrected */ static void exif_thumbnail_extract(image_info_type *ImageInfo, char *offset, size_t length) { if (ImageInfo->Thumbnail.data) { raise_warning("Multiple possible thumbnails"); return; /* Should not happen */ } if (!ImageInfo->read_thumbnail) { return; /* ignore this call */ } /* according to exif2.1, the thumbnail is not supposed to be greater than 64K */ if (ImageInfo->Thumbnail.size >= 65536 || ImageInfo->Thumbnail.size <= 0 || ImageInfo->Thumbnail.offset <= 0) { raise_warning("Illegal thumbnail size/offset"); return; } /* Check to make sure we are not going to go past the ExifLength */ if ((ImageInfo->Thumbnail.offset + ImageInfo->Thumbnail.size) > length) { raise_warning("Thumbnail goes IFD boundary or end of file reached"); return; } PHP_STRNDUP(ImageInfo->Thumbnail.data, offset + ImageInfo->Thumbnail.offset, ImageInfo->Thumbnail.size); exif_thumbnail_build(ImageInfo); } /* Copy a string/buffer in Exif header to a character string and return length of allocated buffer if any. */ static int exif_process_undefined(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ if (byte_count) { PHP_STRNDUP((*result), value, byte_count); /* NULL @ byte_count!!! */ if (*result) return byte_count+1; } return 0; } /* Copy a string in Exif header to a character string returns length of allocated buffer if any. */ #if !EXIF_USE_MBSTRING static int exif_process_string_raw(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we have to copy NUL * chars up to byte_count, we also have to add a single NUL character to * force end of string. */ *result = 0; if (byte_count) { (*result) = (char*)IM_MALLOC(byte_count + 1); CHECK_ALLOC_R((*result), byte_count + 1, 0); memcpy(*result, value, byte_count); (*result)[byte_count] = '\0'; return byte_count+1; } return 0; } #endif /* * Copy a string in Exif header to a character string and return length of allocated buffer if any. In contrast to exif_process_string this function does always return a string buffer */ static int exif_process_string(char **result, char *value, size_t byte_count) { /* we cannot use strlcpy - here the problem is that we cannot use strlen to * determin length of string and we cannot use strlcpy with len=byte_count+1 * because then we might get into an EXCEPTION if we exceed an allocated * memory page...so we use php_strnlen in conjunction with memcpy and add * the NUL char. */ if ((byte_count=php_strnlen(value, byte_count)) > 0) { return exif_process_undefined(result, value, byte_count); } PHP_STRNDUP((*result), "", 1); /* force empty string */ if (*result) return byte_count+1; return 0; } /* Process UserComment in IFD. */ static int exif_process_user_comment(image_info_type* /*ImageInfo*/, char** pszInfoPtr, char** pszEncoding, char* szValuePtr, int ByteCount) { int a; #if EXIF_USE_MBSTRING char *decode; size_t len; #endif *pszEncoding = nullptr; /* Copy the comment */ if (ByteCount>=8) { if (!memcmp(szValuePtr, "UNICODE\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING /* First try to detect BOM: ZERO WIDTH NOBREAK SPACE (FEFF 16) * since we have no encoding support for the BOM yet we skip that. */ if (!memcmp(szValuePtr, "\xFE\xFF", 2)) { decode = "UCS-2BE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (!memcmp(szValuePtr, "\xFF\xFE", 2)) { decode = "UCS-2LE"; szValuePtr = szValuePtr+2; ByteCount -= 2; } else if (ImageInfo->motorola_intel) { decode = ImageInfo->decode_unicode_be; } else { decode = ImageInfo->decode_unicode_le; } *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, decode, &len); return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "ASCII\0\0\0", 8)) { PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; } else if (!memcmp(szValuePtr, "JIS\0\0\0\0\0", 8)) { /* JIS should be tanslated to MB or we leave it to the user */ PHP_STRDUP(*pszEncoding, (const char*)szValuePtr); szValuePtr = szValuePtr+8; ByteCount -= 8; #if EXIF_USE_MBSTRING if (ImageInfo->motorola_intel) { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_be, &len); } else { *pszInfoPtr = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_jis, ImageInfo->decode_jis_le, &len); } return len; #else return exif_process_string_raw(pszInfoPtr, szValuePtr, ByteCount); #endif } else if (!memcmp(szValuePtr, "\0\0\0\0\0\0\0\0", 8)) { /* 8 NULL means undefined and should be ASCII... */ PHP_STRDUP(*pszEncoding, "UNDEFINED"); szValuePtr = szValuePtr+8; ByteCount -= 8; } } /* Olympus has this padded with trailing spaces. Remove these first. */ if (ByteCount>0) { for (a=ByteCount-1;a && szValuePtr[a]==' ';a--) { (szValuePtr)[a] = '\0'; } } /* normal text without encoding */ exif_process_string(pszInfoPtr, szValuePtr, ByteCount); return strlen(*pszInfoPtr); } /* Process unicode field in IFD. */ static int exif_process_unicode(image_info_type* /*ImageInfo*/, xp_field_type* xp_field, int tag, char* szValuePtr, int ByteCount) { xp_field->tag = tag; xp_field->value = nullptr; /* Copy the comment */ #if EXIF_USE_MBSTRING xp_field->value = php_mb_convert_encoding(szValuePtr, ByteCount, ImageInfo->encode_unicode, ImageInfo->decode_unicode_le, &xp_field->size); return xp_field->size; #else xp_field->size = exif_process_string_raw(&xp_field->value, szValuePtr, ByteCount); return xp_field->size; #endif } /* Process nested IFDs directories in Maker Note. */ static int exif_process_IFD_in_MAKERNOTE(image_info_type *ImageInfo, char * value_ptr, int value_len, char *offset_base, size_t IFDlength, size_t displacement) { int de, section_index = SECTION_MAKERNOTE; int NumDirEntries, old_motorola_intel, offset_diff; const maker_note_type *maker_note; char *dir_start; char *value_end = value_ptr + value_len; for (unsigned int i=0; i<=sizeof(maker_note_array)/sizeof(maker_note_type); i++) { if (i==sizeof(maker_note_array)/sizeof(maker_note_type)) return 0; maker_note = maker_note_array+i; if (maker_note->make && (!ImageInfo->make || strcmp(maker_note->make, ImageInfo->make))) { continue; } if (maker_note->model && (!ImageInfo->model || strcmp(maker_note->model, ImageInfo->model))) { continue; } if (maker_note->id_string && strncmp(maker_note->id_string, value_ptr, (maker_note->id_string_len < value_len ? maker_note->id_string_len : value_len))) { continue; } break; } if (maker_note->offset >= value_len) return 0; dir_start = value_ptr + maker_note->offset; ImageInfo->sections_found |= FOUND_MAKERNOTE; old_motorola_intel = ImageInfo->motorola_intel; switch (maker_note->byte_order) { case MN_ORDER_INTEL: ImageInfo->motorola_intel = 0; break; case MN_ORDER_MOTOROLA: ImageInfo->motorola_intel = 1; break; default: case MN_ORDER_NORMAL: break; } if (value_end - dir_start < 2) return 0; NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); switch (maker_note->offset_mode) { case MN_OFFSET_MAKER: offset_base = value_ptr; break; case MN_OFFSET_GUESS: if (value_end - (dir_start+10) < 4) return 0; offset_diff = 2 + NumDirEntries*12 + 4 - php_ifd_get32u(dir_start+10, ImageInfo->motorola_intel); if (offset_diff < 0 || offset_diff >= value_len) return 0; offset_base = value_ptr + offset_diff; break; default: case MN_OFFSET_NORMAL: break; } if ((2+NumDirEntries*12) > value_len) { raise_warning("Illegal IFD size: 2 + x%04X*12 = x%04X > x%04X", NumDirEntries, 2+NumDirEntries*12, value_len); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, value_end, IFDlength, displacement, section_index, 0, maker_note->tag_table)) { return 0; } } ImageInfo->motorola_intel = old_motorola_intel; return 0; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_TAG(image_info_type *ImageInfo, char *dir_entry, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index, int ReadNextIFD, tag_table_type tag_table) { size_t length; int tag, format, components; char *value_ptr, tagname[64], cbuf[32], *outside=nullptr; size_t byte_count, offset_val, fpos, fgot; int64_t byte_count_signed; xp_field_type *tmp_xp; /* Protect against corrupt headers */ if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { raise_warning("corrupt EXIF header: maximum directory " "nesting level reached"); return 0; } ImageInfo->ifd_nesting_level++; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); tag = php_ifd_get16u(dir_entry, ImageInfo->motorola_intel); format = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); components = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel); if (!format || format > NUM_FORMATS) { /* (-1) catches illegal zero case as unsigned underflows to positive large. */ raise_warning("Process tag(x%04X=%s): Illegal format code 0x%04X, " "suppose BYTE", tag, exif_get_tagname(tag, tagname, -12, tag_table), format); format = TAG_FMT_BYTE; /*return TRUE;*/ } if (components < 0) { raise_warning("Process tag(x%04X=%s): Illegal components(%d)", tag, exif_get_tagname(tag, tagname, -12, tag_table), components); return 1; } byte_count_signed = (int64_t)components * get_php_tiff_bytes_per_format(format); if (byte_count_signed < 0 || (byte_count_signed > 2147483648)) { raise_warning("Process tag(x%04X=%s): Illegal byte_count(%ld)", tag, exif_get_tagname(tag, tagname, -12, tag_table), byte_count_signed); return 1; // ignore that field, but don't abort parsing } byte_count = (size_t)byte_count_signed; if (byte_count > 4) { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); offset_val = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* If its bigger than 4 bytes, the dir entry contains an offset. */ value_ptr = offset_base+offset_val; if (byte_count > IFDlength || offset_val > IFDlength-byte_count || value_ptr < dir_entry || offset_val < (size_t)(dir_entry-offset_base)) { /* // It is important to check for IMAGE_FILETYPE_TIFF // JPEG does not use absolute pointers instead // its pointers are relative to the start // of the TIFF header in APP1 section. */ if (byte_count > ImageInfo->FileSize || offset_val>ImageInfo->FileSize-byte_count || (ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_II && ImageInfo->FileType!=IMAGE_FILETYPE_TIFF_MM && ImageInfo->FileType!=IMAGE_FILETYPE_JPEG)) { if (value_ptr < dir_entry) { /* we can read this if offset_val > 0 */ /* some files have their values in other parts of the file */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX < %04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, dir_entry-offset_base); } else { /* this is for sure not allowed */ /* exception are IFD pointers */ raise_warning("Process tag(x%04X=%s): Illegal pointer offset" "(x%04lX + x%04lX = x%04lX > x%04lX)", tag, exif_get_tagname(tag, tagname, -12, tag_table), offset_val, byte_count, offset_val+byte_count, IFDlength); } return 0; } if (byte_count>sizeof(cbuf)) { /* mark as outside range and get buffer */ value_ptr = (char *)IM_MALLOC(byte_count); CHECK_ALLOC_R(value_ptr, byte_count, 0); outside = value_ptr; } else { /* // in most cases we only access a small range so // it is faster to use a static buffer there // BUT it offers also the possibility to have // pointers read without the need to free them // explicitley before returning. */ memset(&cbuf, 0, sizeof(cbuf)); value_ptr = cbuf; } fpos = ImageInfo->infile->tell(); ImageInfo->infile->seek(displacement+offset_val, SEEK_SET); fgot = ImageInfo->infile->tell(); if (fgot!=displacement+offset_val) { if (outside) IM_FREE(outside); raise_warning("Wrong file pointer: 0x%08lX != 0x%08lX", fgot, displacement+offset_val); return 0; } String str = ImageInfo->infile->read(byte_count); fgot = str.length(); memcpy(value_ptr, str.c_str(), fgot); ImageInfo->infile->seek(fpos, SEEK_SET); if (fgot<byte_count) { if (outside) IM_FREE(outside); raise_warning("Unexpected end of file reached"); return 0; } } } else { /* 4 bytes or less and value is in the dir entry itself */ value_ptr = dir_entry+8; offset_val= value_ptr-offset_base; } ImageInfo->sections_found |= FOUND_ANY_TAG; if (section_index==SECTION_THUMBNAIL) { if (!ImageInfo->Thumbnail.data) { switch(tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Thumbnail.width = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Thumbnail.height = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_OFFSETS: case TAG_JPEG_INTERCHANGE_FORMAT: /* accept both formats */ ImageInfo->Thumbnail.offset = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_STRIP_BYTE_COUNTS: if (ImageInfo->FileType == IMAGE_FILETYPE_TIFF_II || ImageInfo->FileType == IMAGE_FILETYPE_TIFF_MM) { ImageInfo->Thumbnail.filetype = ImageInfo->FileType; } else { /* motorola is easier to read */ ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_TIFF_MM; } ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_JPEG_INTERCHANGE_FORMAT_LEN: if (ImageInfo->Thumbnail.filetype == IMAGE_FILETYPE_UNKNOWN) { ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_JPEG; ImageInfo->Thumbnail.size = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); } break; } } } else { if (section_index==SECTION_IFD0 || section_index==SECTION_EXIF) switch(tag) { case TAG_COPYRIGHT: /* check for "<photographer> NUL <editor> NUL" */ if (byte_count>1 && (length=php_strnlen(value_ptr, byte_count)) > 0) { if (length<byte_count-1) { /* When there are any characters after the first NUL */ PHP_STRDUP(ImageInfo->CopyrightPhotographer, value_ptr); PHP_STRNDUP( ImageInfo->CopyrightEditor, value_ptr + length + 1, byte_count - length - 1 ); if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); php_vspprintf(&ImageInfo->Copyright, 0, "%s, %s", value_ptr, ImageInfo->CopyrightEditor); /* format = TAG_FMT_UNDEFINED; this musn't be ASCII */ /* but we are not supposed to change this */ /* keep in mind that image_info does not store editor value */ } else { PHP_STRNDUP(ImageInfo->Copyright, value_ptr, byte_count); } } break; case TAG_USERCOMMENT: ImageInfo->UserCommentLength = exif_process_user_comment(ImageInfo, &(ImageInfo->UserComment), &(ImageInfo->UserCommentEncoding), value_ptr, byte_count); break; case TAG_XP_TITLE: case TAG_XP_COMMENTS: case TAG_XP_AUTHOR: case TAG_XP_KEYWORDS: case TAG_XP_SUBJECT: { size_t realloc_size = (ImageInfo->xp_fields.count+1) * sizeof(xp_field_type); tmp_xp = (xp_field_type*) IM_REALLOC(ImageInfo->xp_fields.list, realloc_size); if (!tmp_xp) { if (outside) IM_FREE(outside); } CHECK_ALLOC_R(tmp_xp, realloc_size, 0); ImageInfo->sections_found |= FOUND_WINXP; ImageInfo->xp_fields.list = tmp_xp; ImageInfo->xp_fields.count++; exif_process_unicode(ImageInfo, &(ImageInfo->xp_fields.list[ImageInfo->xp_fields.count-1]), tag, value_ptr, byte_count); break; } case TAG_FNUMBER: /* Simplest way of expressing aperture, so I trust it the most. (overwrite previously computed value if there is one) */ ImageInfo->ApertureFNumber = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_APERTURE: case TAG_MAX_APERTURE: /* More relevant info always comes earlier, so only use this field if we don't have appropriate aperture information yet. */ if (ImageInfo->ApertureFNumber == 0) { ImageInfo->ApertureFNumber = (float)exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2)*0.5); } break; case TAG_SHUTTERSPEED: /* More complicated way of expressing exposure time, so only use this value if we don't already have it from somewhere else. SHUTTERSPEED comes after EXPOSURE TIME */ if (ImageInfo->ExposureTime == 0) { ImageInfo->ExposureTime = (float)(1/exp(exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)*log(2))); } break; case TAG_EXPOSURETIME: ImageInfo->ExposureTime = -1; break; case TAG_COMP_IMAGE_WIDTH: ImageInfo->ExifImageWidth = exif_convert_any_to_int(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_X_RES: ImageInfo->FocalplaneXRes = exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_SUBJECT_DISTANCE: /* Inidcates the distacne the autofocus camera is focused to. Tends to be less accurate as distance increases. */ ImageInfo->Distance = (float)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel); break; case TAG_FOCALPLANE_RESOLUTION_UNIT: switch((int)exif_convert_any_format(value_ptr, format, ImageInfo->motorola_intel)) { case 1: ImageInfo->FocalplaneUnits = 25.4; break; /* inch */ case 2: /* According to the information I was using, 2 measn meters. But looking at the Cannon powershot's files, inches is the only sensible value. */ ImageInfo->FocalplaneUnits = 25.4; break; case 3: ImageInfo->FocalplaneUnits = 10; break; /* centimeter */ case 4: ImageInfo->FocalplaneUnits = 1; break; /* milimeter */ case 5: ImageInfo->FocalplaneUnits = .001; break; /* micrometer */ } break; case TAG_SUB_IFD: if (format==TAG_FMT_IFD) { /* If this is called we are either in a TIFFs thumbnail or a JPEG where we cannot handle it */ /* TIFF thumbnail: our data structure cannot store a thumbnail of a thumbnail */ /* JPEG do we have the data area and what to do with it */ raise_notice("Skip SUB IFD"); } break; case TAG_MAKE: PHP_STRNDUP(ImageInfo->make, value_ptr, byte_count); break; case TAG_MODEL: PHP_STRNDUP(ImageInfo->model, value_ptr, byte_count); break; case TAG_MAKER_NOTE: exif_process_IFD_in_MAKERNOTE(ImageInfo, value_ptr, byte_count, offset_base, IFDlength, displacement); break; case TAG_EXIF_IFD_POINTER: case TAG_GPS_IFD_POINTER: case TAG_INTEROP_IFD_POINTER: if (ReadNextIFD) { char *Subdir_start; int sub_section_index = 0; switch(tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; } CHECK_BUFFER_R(value_ptr, end, 4, 0); Subdir_start = offset_base + php_ifd_get32u(value_ptr, ImageInfo->motorola_intel); if (Subdir_start < offset_base || Subdir_start > offset_base+IFDlength) { raise_warning("Illegal IFD Pointer"); return 0; } if (!exif_process_IFD_in_JPEG(ImageInfo, Subdir_start, offset_base, end, IFDlength, displacement, sub_section_index)) { return 0; } } } } exif_iif_add_tag(ImageInfo, section_index, exif_get_tagname(tag, tagname, sizeof(tagname), tag_table), tag, format, components, value_ptr); if (outside) IM_FREE(outside); return 1; } /* Process one of the nested IFDs directories. */ static int exif_process_IFD_in_JPEG(image_info_type *ImageInfo, char *dir_start, char *offset_base, char *end, size_t IFDlength, size_t displacement, int section_index) { int de; int NumDirEntries; int NextDirOffset; ImageInfo->sections_found |= FOUND_IFD0; CHECK_BUFFER_R(dir_start, end, 2, 0); NumDirEntries = php_ifd_get16u(dir_start, ImageInfo->motorola_intel); if ((dir_start+2+NumDirEntries*12) > (offset_base+IFDlength)) { raise_warning("Illegal IFD size: x%04X + 2 + x%04X*12 = x%04X > x%04lX", (int)((size_t)dir_start+2-(size_t)offset_base), NumDirEntries, (int)((size_t)dir_start+2+ NumDirEntries*12-(size_t)offset_base), IFDlength); return 0; } for (de=0;de<NumDirEntries;de++) { if (!exif_process_IFD_TAG(ImageInfo, dir_start + 2 + 12 * de, offset_base, end, IFDlength, displacement, section_index, 1, exif_get_tag_table(section_index))) { return 0; } } /* * Ignore IFD2 if it purportedly exists */ if (section_index == SECTION_THUMBNAIL) { return true; } /* * Hack to make it process IDF1 I hope * There are 2 IDFs, the second one holds the keys (0x0201 and 0x0202) * to the thumbnail */ CHECK_BUFFER_R(dir_start+2+12*de, end, 4, 0); NextDirOffset = php_ifd_get32u(dir_start+2+12*de, ImageInfo->motorola_intel); if (NextDirOffset) { /* the next line seems false but here IFDlength means length of all IFDs */ if (offset_base + NextDirOffset < offset_base || offset_base + NextDirOffset > offset_base+IFDlength) { raise_warning("Illegal IFD offset"); return 0; } /* That is the IFD for the first thumbnail */ if (exif_process_IFD_in_JPEG(ImageInfo, offset_base + NextDirOffset, offset_base, end, IFDlength, displacement, SECTION_THUMBNAIL)) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { exif_thumbnail_extract(ImageInfo, offset_base, IFDlength); } return 1; } else { return 0; } } return 1; } /* Process a TIFF header in a JPEG file */ static void exif_process_TIFF_in_JPEG(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { char *end = CharBuf + length; unsigned exif_value_2a, offset_of_ifd; /* set the thumbnail stuff to nothing so we can test to see if they get set up */ CHECK_BUFFER(CharBuf, end, 2); if (memcmp(CharBuf, "II", 2) == 0) { ImageInfo->motorola_intel = 0; } else if (memcmp(CharBuf, "MM", 2) == 0) { ImageInfo->motorola_intel = 1; } else { raise_warning("Invalid TIFF a lignment marker"); return; } /* Check the next two values for correctness. */ CHECK_BUFFER(CharBuf+4, end, 4); exif_value_2a = php_ifd_get16u(CharBuf+2, ImageInfo->motorola_intel); offset_of_ifd = php_ifd_get32u(CharBuf+4, ImageInfo->motorola_intel); if ( exif_value_2a != 0x2a || offset_of_ifd < 0x08) { raise_warning("Invalid TIFF start (1)"); return; } if (offset_of_ifd > length) { raise_warning("Invalid IFD start"); return; } ImageInfo->sections_found |= FOUND_IFD0; /* First directory starts at offset 8. Offsets starts at 0. */ exif_process_IFD_in_JPEG(ImageInfo, CharBuf+offset_of_ifd, CharBuf, end, length/* -14*/, displacement, SECTION_IFD0); /* Compute the CCD width, in milimeters. */ if (ImageInfo->FocalplaneXRes != 0) { ImageInfo->CCDWidth = (float)(ImageInfo->ExifImageWidth * ImageInfo->FocalplaneUnits / ImageInfo->FocalplaneXRes); } } /* Process an JPEG APP1 block marker Describes all the drivel that most digital cameras include... */ static void exif_process_APP1(image_info_type *ImageInfo, char *CharBuf, size_t length, size_t displacement) { /* Check the APP1 for Exif Identifier Code */ char *end = CharBuf + length; static const unsigned char ExifHeader[] = {0x45, 0x78, 0x69, 0x66, 0x00, 0x00}; CHECK_BUFFER(CharBuf+2, end, 6); if (length <= 8 || memcmp(CharBuf+2, ExifHeader, 6)) { raise_warning("Incorrect APP1 Exif Identifier Code"); return; } exif_process_TIFF_in_JPEG(ImageInfo, CharBuf + 8, length - 8, displacement+8); } /* Process an JPEG APP12 block marker used by OLYMPUS */ static void exif_process_APP12(image_info_type *ImageInfo, char *buffer, size_t length) { size_t l1, l2=0; if ((l1 = php_strnlen(buffer+2, length-2)) > 0) { exif_iif_add_tag(ImageInfo, SECTION_APP12, "Company", TAG_NONE, TAG_FMT_STRING, l1, buffer+2); if (length > 2+l1+1) { l2 = php_strnlen(buffer+2+l1+1, length-2-l1+1); exif_iif_add_tag(ImageInfo, SECTION_APP12, "Info", TAG_NONE, TAG_FMT_STRING, l2, buffer+2+l1+1); } } } /* Process a SOFn marker. This is useful for the image dimensions */ static void exif_process_SOFn(unsigned char* Data, int /*marker*/, jpeg_sof_info* result) { result->bits_per_sample = Data[2]; result->height = php_jpg_get16(Data+3); result->width = php_jpg_get16(Data+5); result->num_components = Data[7]; } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_JPEG_header(image_info_type *ImageInfo) { int section, sn; int marker = 0, last_marker = M_PSEUDO, comment_correction=1; int ll, lh; unsigned char *Data; size_t fpos, size, got, itemlen; jpeg_sof_info sof_info; for(section=0;;section++) { // get marker byte, swallowing possible padding // some software does not count the length bytes of COM section // one company doing so is very much envolved in JPEG... // so we accept too if (last_marker==M_COM && comment_correction) { comment_correction = 2; } do { if ((marker = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if (last_marker==M_COM && comment_correction>0) { if (marker!=0xFF) { marker = 0xff; comment_correction--; } else { last_marker = M_PSEUDO; /* stop skipping 0 for M_COM */ } } } while (marker == 0xff); if (last_marker==M_COM && !comment_correction) { raise_notice("Image has corrupt COM section: some software set " "wrong length information"); } if (last_marker==M_COM && comment_correction) return M_EOI; /* ah illegal: char after COM section not 0xFF */ fpos = ImageInfo->infile->tell(); if (marker == 0xff) { // 0xff is legal padding, but if we get that many, something's wrong. raise_warning("To many padding bytes"); return 0; } /* Read the length of the section. */ if ((lh = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } if ((ll = ImageInfo->infile->getc()) == EOF) { raise_warning("File structure corrupted"); return 0; } itemlen = (lh << 8) | ll; if (itemlen < 2) { raise_warning("File structure corrupted"); return 0; } sn = exif_file_sections_add(ImageInfo, marker, itemlen+1, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; /* Store first two pre-read bytes. */ Data[0] = (unsigned char)lh; Data[1] = (unsigned char)ll; String str = ImageInfo->infile->read(itemlen-2); got = str.length(); if (got != itemlen-2) { raise_warning("Error reading from file: " "got=x%04lX(=%lu) != itemlen-2=x%04lX(=%lu)", got, got, itemlen-2, itemlen-2); return 0; } memcpy(Data+2, str.c_str(), got); switch(marker) { case M_SOS: /* stop before hitting compressed data */ // If reading entire image is requested, read the rest of the data. if (ImageInfo->read_all) { /* Determine how much file is left. */ fpos = ImageInfo->infile->tell(); size = ImageInfo->FileSize - fpos; sn = exif_file_sections_add(ImageInfo, M_PSEUDO, size, nullptr); if (sn == -1) return 0; Data = ImageInfo->file.list[sn].data; str = ImageInfo->infile->read(size); got = str.length(); if (got != size) { raise_warning("Unexpected end of file reached"); return 0; } memcpy(Data, str.c_str(), got); } return 1; case M_EOI: /* in case it's a tables-only JPEG stream */ raise_warning("No image in jpeg!"); return (ImageInfo->sections_found&(~FOUND_COMPUTED)) ? 1 : 0; case M_COM: /* Comment section */ exif_process_COM(ImageInfo, (char *)Data, itemlen); break; case M_EXIF: if (!(ImageInfo->sections_found&FOUND_IFD0)) { /*ImageInfo->sections_found |= FOUND_EXIF;*/ /* Seen files from some 'U-lead' software with Vivitar scanner that uses marker 31 later in the file (no clue what for!) */ exif_process_APP1(ImageInfo, (char *)Data, itemlen, fpos); } break; case M_APP12: exif_process_APP12(ImageInfo, (char *)Data, itemlen); break; case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: if ((itemlen - 2) < 6) { return 0; } exif_process_SOFn(Data, marker, &sof_info); ImageInfo->Width = sof_info.width; ImageInfo->Height = sof_info.height; if (sof_info.num_components == 3) { ImageInfo->IsColor = 1; } else { ImageInfo->IsColor = 0; } break; default: /* skip any other marker silently. */ break; } /* keep track of last marker */ last_marker = marker; } return 1; } /* Reallocate a file section returns 0 on success and -1 on failure */ static int exif_file_sections_realloc(image_info_type *ImageInfo, int section_index, size_t size) { void *tmp; /* This is not a malloc/realloc check. It is a plausibility check for the * function parameters (requirements engineering). */ if (section_index >= ImageInfo->file.count) { raise_warning("Illegal reallocating of undefined file section"); return -1; } tmp = IM_REALLOC(ImageInfo->file.list[section_index].data, size); CHECK_ALLOC_R(tmp, size, -1); ImageInfo->file.list[section_index].data = (unsigned char *)tmp; ImageInfo->file.list[section_index].size = size; return 0; } /* Parse the TIFF header; */ static int exif_process_IFD_in_TIFF(image_info_type *ImageInfo, size_t dir_offset, int section_index) { int i, sn, num_entries, sub_section_index = 0; unsigned char *dir_entry; char tagname[64]; size_t ifd_size, dir_size, entry_offset, next_offset, entry_length, entry_value=0, fgot; int entry_tag , entry_type; tag_table_type tag_table = exif_get_tag_table(section_index); if (ImageInfo->ifd_nesting_level > MAX_IFD_NESTING_LEVEL) { return 0; } if (ImageInfo->FileSize >= dir_offset+2) { sn = exif_file_sections_add(ImageInfo, M_PSEUDO, 2, nullptr); if (sn == -1) return 0; /* we do not know the order of sections */ ImageInfo->infile->seek(dir_offset, SEEK_SET); String snData = ImageInfo->infile->read(2); memcpy(ImageInfo->file.list[sn].data, snData.c_str(), 2); num_entries = php_ifd_get16u(ImageInfo->file.list[sn].data, ImageInfo->motorola_intel); dir_size = 2/*num dir entries*/ + 12/*length of entry*/*num_entries + 4/* offset to next ifd (points to thumbnail or NULL)*/; if (ImageInfo->FileSize >= dir_offset+dir_size) { if (exif_file_sections_realloc(ImageInfo, sn, dir_size)) { return 0; } snData = ImageInfo->infile->read(dir_size-2); memcpy(ImageInfo->file.list[sn].data+2, snData.c_str(), dir_size-2); next_offset = php_ifd_get32u(ImageInfo->file.list[sn].data + dir_size - 4, ImageInfo->motorola_intel); /* now we have the directory we can look how long it should be */ ifd_size = dir_size; char *end = (char*)ImageInfo->file.list[sn].data + dir_size; for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+4, end, 4, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_type > NUM_FORMATS) { raise_notice("Read from TIFF: tag(0x%04X,%12s): " "Illegal format code 0x%04X, switching to BYTE", entry_tag, exif_get_tagname(entry_tag, tagname, -12, tag_table), entry_type); /* Since this is repeated in exif_process_IFD_TAG make it a notice here and make it a warning in the exif_process_IFD_TAG which is called elsewhere. */ entry_type = TAG_FMT_BYTE; } entry_length = php_ifd_get32u(dir_entry+4, ImageInfo->motorola_intel) * get_php_tiff_bytes_per_format(entry_type); if (entry_length <= 4) { switch(entry_type) { case TAG_FMT_USHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SSHORT: CHECK_BUFFER_R(dir_entry+8, end, 2, 0); entry_value = php_ifd_get16s(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_ULONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); break; case TAG_FMT_SLONG: CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_value = php_ifd_get32s(dir_entry+8, ImageInfo->motorola_intel); break; } switch(entry_tag) { case TAG_IMAGEWIDTH: case TAG_COMP_IMAGE_WIDTH: ImageInfo->Width = entry_value; break; case TAG_IMAGEHEIGHT: case TAG_COMP_IMAGE_HEIGHT: ImageInfo->Height = entry_value; break; case TAG_PHOTOMETRIC_INTERPRETATION: switch (entry_value) { case PMI_BLACK_IS_ZERO: case PMI_WHITE_IS_ZERO: case PMI_TRANSPARENCY_MASK: ImageInfo->IsColor = 0; break; case PMI_RGB: case PMI_PALETTE_COLOR: case PMI_SEPARATED: case PMI_YCBCR: case PMI_CIELAB: ImageInfo->IsColor = 1; break; } break; } } else { CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); /* if entry needs expading ifd cache and entry is at end of current ifd cache. */ /* otherwise there may be huge holes between two entries */ if (entry_offset + entry_length > dir_offset + ifd_size && entry_offset == dir_offset + ifd_size) { ifd_size = entry_offset + entry_length - dir_offset; } } } if (ImageInfo->FileSize >= dir_offset + ImageInfo->file.list[sn].size) { if (ifd_size > dir_size) { if (dir_offset + ifd_size > ImageInfo->FileSize) { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX + x%04lX)", ImageInfo->FileSize, dir_offset, ifd_size); return 0; } if (exif_file_sections_realloc(ImageInfo, sn, ifd_size)) { return 0; } else { end = (char*)ImageInfo->file.list[sn].data + dir_size; } /* read values not stored in directory itself */ snData = ImageInfo->infile->read(ifd_size-dir_size); memcpy(ImageInfo->file.list[sn].data+dir_size, snData.c_str(), ifd_size-dir_size); } /* now process the tags */ for(i=0;i<num_entries;i++) { dir_entry = ImageInfo->file.list[sn].data+2+i*12; CHECK_BUFFER_R(dir_entry+2, end, 2, 0); entry_tag = php_ifd_get16u(dir_entry+0, ImageInfo->motorola_intel); entry_type = php_ifd_get16u(dir_entry+2, ImageInfo->motorola_intel); if (entry_tag == TAG_EXIF_IFD_POINTER || entry_tag == TAG_INTEROP_IFD_POINTER || entry_tag == TAG_GPS_IFD_POINTER || entry_tag == TAG_SUB_IFD) { switch(entry_tag) { case TAG_EXIF_IFD_POINTER: ImageInfo->sections_found |= FOUND_EXIF; sub_section_index = SECTION_EXIF; break; case TAG_GPS_IFD_POINTER: ImageInfo->sections_found |= FOUND_GPS; sub_section_index = SECTION_GPS; break; case TAG_INTEROP_IFD_POINTER: ImageInfo->sections_found |= FOUND_INTEROP; sub_section_index = SECTION_INTEROP; break; case TAG_SUB_IFD: ImageInfo->sections_found |= FOUND_THUMBNAIL; sub_section_index = SECTION_THUMBNAIL; break; } CHECK_BUFFER_R(dir_entry+8, end, 4, 0); entry_offset = php_ifd_get32u(dir_entry+8, ImageInfo->motorola_intel); ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, entry_offset, sub_section_index); if (section_index!=SECTION_THUMBNAIL && entry_tag==TAG_SUB_IFD) { if (ImageInfo->Thumbnail.filetype != IMAGE_FILETYPE_UNKNOWN && ImageInfo->Thumbnail.size && ImageInfo->Thumbnail.offset && ImageInfo->read_thumbnail) { if (!ImageInfo->Thumbnail.data) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } } } else { if (!exif_process_IFD_TAG(ImageInfo, (char*)dir_entry, (char*)(ImageInfo->file.list[sn].data-dir_offset), (char*)(ImageInfo->file.list[sn].data + ifd_size), ifd_size, 0, section_index, 0, tag_table)) { return 0; } } } /* If we had a thumbnail in a SUB_IFD we have ANOTHER image in NEXT IFD */ if (next_offset && section_index != SECTION_THUMBNAIL) { /* this should be a thumbnail IFD */ /* the thumbnail itself is stored at Tag=StripOffsets */ ImageInfo->ifd_nesting_level++; exif_process_IFD_in_TIFF(ImageInfo, next_offset, SECTION_THUMBNAIL); if (!ImageInfo->Thumbnail.data && ImageInfo->Thumbnail.offset && ImageInfo->Thumbnail.size && ImageInfo->read_thumbnail) { ImageInfo->Thumbnail.data = (char *)IM_MALLOC(ImageInfo->Thumbnail.size); CHECK_ALLOC_R(ImageInfo->Thumbnail.data, ImageInfo->Thumbnail.size, 0); ImageInfo->infile->seek(ImageInfo->Thumbnail.offset, SEEK_SET); String str = ImageInfo->infile->read(ImageInfo->Thumbnail.size); fgot = str.length(); if (fgot < ImageInfo->Thumbnail.size) { raise_warning("Thumbnail goes IFD boundary or " "end of file reached"); IM_FREE(ImageInfo->Thumbnail.data); ImageInfo->Thumbnail.data = nullptr; } else { memcpy(ImageInfo->Thumbnail.data, str.c_str(), fgot); exif_thumbnail_build(ImageInfo); } } } return 1; } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "size of IFD(x%04lX)", ImageInfo->FileSize, dir_offset+ImageInfo->file.list[sn].size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than size " "of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+dir_size); return 0; } } else { raise_warning("Error in TIFF: filesize(x%04lX) less than " "start of IFD dir(x%04lX)", ImageInfo->FileSize, dir_offset+2); return 0; } } /* Parse the marker stream until SOS or EOI is seen; */ static int exif_scan_FILE_header(image_info_type *ImageInfo) { unsigned char *file_header; int ret = 0; ImageInfo->FileType = IMAGE_FILETYPE_UNKNOWN; if (ImageInfo->FileSize >= 2) { ImageInfo->infile->seek(0, SEEK_SET); String fileHeader = ImageInfo->infile->read(2); if (fileHeader.length() != 2) { return 0; } file_header = (unsigned char *)fileHeader.c_str(); if ((file_header[0]==0xff) && (file_header[1]==M_SOI)) { ImageInfo->FileType = IMAGE_FILETYPE_JPEG; if (exif_scan_JPEG_header(ImageInfo)) { ret = 1; } else { raise_warning("Invalid JPEG file"); } } else if (ImageInfo->FileSize >= 8) { String str = ImageInfo->infile->read(6); if (str.length() != 6) { return 0; } fileHeader += str; file_header = (unsigned char *)fileHeader.c_str(); if (!memcmp(file_header, "II\x2A\x00", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_II; ImageInfo->motorola_intel = 0; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else if (!memcmp(file_header, "MM\x00\x2a", 4)) { ImageInfo->FileType = IMAGE_FILETYPE_TIFF_MM; ImageInfo->motorola_intel = 1; ImageInfo->sections_found |= FOUND_IFD0; if (exif_process_IFD_in_TIFF(ImageInfo, php_ifd_get32u(file_header + 4, ImageInfo->motorola_intel), SECTION_IFD0)) { ret = 1; } else { raise_warning("Invalid TIFF file"); } } else { raise_warning("File not supported"); return 0; } } } else { raise_warning("File too small (%lu)", ImageInfo->FileSize); } return ret; } static int exif_read_file(image_info_type *ImageInfo, String FileName, bool read_thumbnail, bool read_all) { struct stat st; /* Start with an empty image information structure. */ memset(ImageInfo, 0, sizeof(*ImageInfo)); ImageInfo->motorola_intel = -1; /* flag as unknown */ ImageInfo->infile = File::Open(FileName, "rb"); if (!ImageInfo->infile) { raise_warning("Unable to open file %s", FileName.c_str()); return 0; } auto plain_file = dyn_cast<PlainFile>(ImageInfo->infile); if (plain_file) { if (stat(FileName.c_str(), &st) >= 0) { if ((st.st_mode & S_IFMT) != S_IFREG) { raise_warning("Not a file"); return 0; } } /* Store file date/time. */ ImageInfo->FileDateTime = st.st_mtime; ImageInfo->FileSize = st.st_size; } else { if (!ImageInfo->FileSize) { ImageInfo->infile->seek(0, SEEK_END); ImageInfo->FileSize = ImageInfo->infile->tell(); ImageInfo->infile->seek(0, SEEK_SET); } } ImageInfo->FileName = HHVM_FN(basename)(FileName); ImageInfo->read_thumbnail = read_thumbnail; ImageInfo->read_all = read_all; ImageInfo->Thumbnail.filetype = IMAGE_FILETYPE_UNKNOWN; PHP_STRDUP(ImageInfo->encode_unicode, "ISO-8859-15"); PHP_STRDUP(ImageInfo->decode_unicode_be, "UCS-2BE"); PHP_STRDUP(ImageInfo->decode_unicode_le, "UCS-2LE"); PHP_STRDUP(ImageInfo->encode_jis, ""); PHP_STRDUP(ImageInfo->decode_jis_be, "JIS"); PHP_STRDUP(ImageInfo->decode_jis_le, "JIS"); ImageInfo->ifd_nesting_level = 0; /* Scan the JPEG headers. */ auto ret = exif_scan_FILE_header(ImageInfo); ImageInfo->infile->close(); return ret; } /* Free memory allocated for image_info */ static void exif_iif_free(image_info_type *image_info, int section_index) { int i; void *f; /* faster */ if (image_info->info_list[section_index].count) { for (i=0; i < image_info->info_list[section_index].count; i++) { if ((f=image_info->info_list[section_index].list[i].name) != nullptr) { IM_FREE(f); } switch(image_info->info_list[section_index].list[i].format) { case TAG_FMT_SBYTE: case TAG_FMT_BYTE: /* in contrast to strings bytes do not need to allocate buffer for nullptr if length==0 */ if (image_info->info_list[section_index].list[i].length<1) break; default: case TAG_FMT_UNDEFINED: case TAG_FMT_STRING: if ((f=image_info->info_list[section_index].list[i].value.s) != nullptr) { IM_FREE(f); } break; case TAG_FMT_USHORT: case TAG_FMT_ULONG: case TAG_FMT_URATIONAL: case TAG_FMT_SSHORT: case TAG_FMT_SLONG: case TAG_FMT_SRATIONAL: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: /* nothing to do here */ if (image_info->info_list[section_index].list[i].length > 1) { if ((f=image_info->info_list[section_index].list[i].value.list) != nullptr) { IM_FREE(f); } } break; } } } if (image_info->info_list[section_index].list) { IM_FREE(image_info->info_list[section_index].list); } } /* Discard all file_sections in ImageInfo */ static int exif_file_sections_free(image_info_type *ImageInfo) { int i; if (ImageInfo->file.count) { for (i=0; i<ImageInfo->file.count; i++) { if (ImageInfo->file.list[i].data) { IM_FREE(ImageInfo->file.list[i].data); } } } if (ImageInfo->file.list) IM_FREE(ImageInfo->file.list); ImageInfo->file.count = 0; return 1; } /* Discard data scanned by exif_read_file. */ static int exif_discard_imageinfo(image_info_type *ImageInfo) { int i; if (ImageInfo->UserComment) IM_FREE(ImageInfo->UserComment); if (ImageInfo->UserCommentEncoding) { IM_FREE(ImageInfo->UserCommentEncoding); } if (ImageInfo->Copyright) IM_FREE(ImageInfo->Copyright); if (ImageInfo->CopyrightPhotographer) { IM_FREE(ImageInfo->CopyrightPhotographer); } if (ImageInfo->CopyrightEditor) IM_FREE(ImageInfo->CopyrightEditor); if (ImageInfo->Thumbnail.data) IM_FREE(ImageInfo->Thumbnail.data); if (ImageInfo->encode_unicode) IM_FREE(ImageInfo->encode_unicode); if (ImageInfo->decode_unicode_be) { IM_FREE(ImageInfo->decode_unicode_be); } if (ImageInfo->decode_unicode_le) { IM_FREE(ImageInfo->decode_unicode_le); } if (ImageInfo->encode_jis) IM_FREE(ImageInfo->encode_jis); if (ImageInfo->decode_jis_be) IM_FREE(ImageInfo->decode_jis_be); if (ImageInfo->decode_jis_le) IM_FREE(ImageInfo->decode_jis_le); if (ImageInfo->make) IM_FREE(ImageInfo->make); if (ImageInfo->model) IM_FREE(ImageInfo->model); for (i=0; i<ImageInfo->xp_fields.count; i++) { if (ImageInfo->xp_fields.list[i].value) { IM_FREE(ImageInfo->xp_fields.list[i].value); } } if (ImageInfo->xp_fields.list) IM_FREE(ImageInfo->xp_fields.list); for (i=0; i<SECTION_COUNT; i++) { exif_iif_free(ImageInfo, i); } exif_file_sections_free(ImageInfo); memset(ImageInfo, 0, sizeof(*ImageInfo)); return 1; } /* Add an int value to image_info */ static void exif_iif_add_int(image_info_type *image_info, int section_index, char *name, int value) { image_info_data *info_data; image_info_data *list; size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_SLONG; info_data->length = 1; PHP_STRDUP(info_data->name, name); info_data->value.i = value; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_str(image_info_type *image_info, int section_index, char *name, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_STRING; info_data->length = 1; PHP_STRDUP(info_data->name, name); // TODO // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, strlen(value), nullptr, 0); // } else { PHP_STRDUP(info_data->value.s, value); image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* Add a format string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_fmt(image_info_type *image_info, int section_index, char *name, char *value, ...) { va_list arglist; va_start(arglist, value); if (value) { char *tmp = 0; php_vspprintf_ap(&tmp, 0, value, arglist); exif_iif_add_str(image_info, section_index, name, tmp); if (tmp) IM_FREE(tmp); } va_end(arglist); } /* Add a string value to image_info MUST BE NUL TERMINATED */ static void exif_iif_add_buffer(image_info_type *image_info, int section_index, char *name, int length, char *value) { image_info_data *info_data; image_info_data *list; if (value) { size_t realloc_size = (image_info->info_list[section_index].count+1) * sizeof(image_info_data); list = (image_info_data *) IM_REALLOC(image_info->info_list[section_index].list, realloc_size); CHECK_ALLOC(list, realloc_size); image_info->info_list[section_index].list = list; info_data = &image_info->info_list[section_index]. list[image_info->info_list[section_index].count]; memset(info_data, 0, sizeof(image_info_data)); info_data->tag = (unsigned short)TAG_NONE; info_data->format = TAG_FMT_UNDEFINED; info_data->length = length; PHP_STRDUP(info_data->name, name); // if (PG(magic_quotes_runtime)) { // info_data->value.s = php_addslashes(value, length, &length, 0); // info_data->length = length; // } else { info_data->value.s = (char *)IM_MALLOC(length + 1); if (!info_data->value.s) info_data->length = 0; CHECK_ALLOC(info_data->value.s, length + 1); memcpy(info_data->value.s, value, length); info_data->value.s[length] = 0; image_info->sections_found |= 1<<section_index; image_info->info_list[section_index].count++; } } /* scan JPEG in thumbnail (memory) */ static int exif_scan_thumbnail(image_info_type *ImageInfo) { unsigned char c, *data = (unsigned char*)ImageInfo->Thumbnail.data; int n, marker; size_t length=2, pos=0; jpeg_sof_info sof_info; if (!data) { return 0; /* nothing to do here */ } if (memcmp(data, "\xFF\xD8\xFF", 3)) { if (!ImageInfo->Thumbnail.width && !ImageInfo->Thumbnail.height) { raise_warning("Thumbnail is not a JPEG image"); } return 0; } for (;;) { pos += length; if (pos>=ImageInfo->Thumbnail.size) return 0; c = data[pos++]; if (pos>=ImageInfo->Thumbnail.size) return 0; if (c != 0xFF) { return 0; } n = 8; while ((c = data[pos++]) == 0xFF && n--) { if (pos+3>=ImageInfo->Thumbnail.size) return 0; /* +3 = pos++ of next check when reaching marker + 2 bytes for length */ } if (c == 0xFF) return 0; marker = c; length = php_jpg_get16(data+pos); if (pos+length>=ImageInfo->Thumbnail.size) { return 0; } switch (marker) { case M_SOF0: case M_SOF1: case M_SOF2: case M_SOF3: case M_SOF5: case M_SOF6: case M_SOF7: case M_SOF9: case M_SOF10: case M_SOF11: case M_SOF13: case M_SOF14: case M_SOF15: /* handle SOFn block */ exif_process_SOFn(data+pos, marker, &sof_info); ImageInfo->Thumbnail.height = sof_info.height; ImageInfo->Thumbnail.width = sof_info.width; return 1; case M_SOS: case M_EOI: raise_warning("Could not compute size of thumbnail"); return 0; break; default: /* just skip */ break; } } raise_warning("Could not compute size of thumbnail"); return 0; } /* Add image_info to associative array value. */ static void add_assoc_image_info(Array &value, bool sub_array, image_info_type *image_info, int section_index) { char buffer[64], *val, *name, uname[64]; int i, ap, l, b, idx=0, unknown=0; image_info_value *info_value; image_info_data *info_data; Array tmp; Array *tmpi = &tmp; Array array; if (image_info->info_list[section_index].count) { if (!sub_array) { tmpi = &value; } for(i=0; i<image_info->info_list[section_index].count; i++) { info_data = &image_info->info_list[section_index].list[i]; info_value = &info_data->value; if (!(name = info_data->name)) { snprintf(uname, sizeof(uname), "%d", unknown++); name = uname; } if (info_data->length==0) { tmpi->set(String(name, CopyString), uninit_null()); } else { switch (info_data->format) { default: /* Standard says more types possible but skip them... * but allow users to handle data if they know how to * So not return but use type UNDEFINED * return; */ case TAG_FMT_BYTE: case TAG_FMT_SBYTE: case TAG_FMT_UNDEFINED: if (!info_value->s) { tmpi->set(String(name, CopyString), ""); } else { tmpi->set(String(name, CopyString), String(info_value->s, info_data->length, CopyString)); } break; case TAG_FMT_STRING: if (!(val = info_value->s)) { val = ""; } if (section_index==SECTION_COMMENT) { tmpi->set(idx++, String(val, CopyString)); } else { tmpi->set(String(name, CopyString), String(val, CopyString)); } break; case TAG_FMT_URATIONAL: case TAG_FMT_SRATIONAL: /*case TAG_FMT_BYTE: case TAG_FMT_SBYTE:*/ case TAG_FMT_USHORT: case TAG_FMT_SSHORT: case TAG_FMT_SINGLE: case TAG_FMT_DOUBLE: case TAG_FMT_ULONG: case TAG_FMT_SLONG: /* now the rest, first see if it becomes an array */ if ((l = info_data->length) > 1) { array.clear(); } for(ap=0; ap<l; ap++) { if (l>1) { info_value = &info_data->value.list[ap]; } switch (info_data->format) { case TAG_FMT_BYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(b, (int)(info_value->s[b])); } break; } case TAG_FMT_USHORT: case TAG_FMT_ULONG: if (l==1) { tmpi->set(String(name, CopyString), (int)info_value->u); } else { array.set(ap, (int)info_value->u); } break; case TAG_FMT_URATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->ur.num, info_value->ur.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SBYTE: if (l>1) { info_value = &info_data->value; for (b=0;b<l;b++) { array.set(ap, (int)info_value->s[b]); } break; } case TAG_FMT_SSHORT: case TAG_FMT_SLONG: if (l==1) { tmpi->set(String(name, CopyString), info_value->i); } else { array.set(ap, info_value->i); } break; case TAG_FMT_SRATIONAL: snprintf(buffer, sizeof(buffer), "%i/%i", info_value->sr.num, info_value->sr.den); if (l==1) { tmpi->set(String(name, CopyString), String(buffer, CopyString)); } else { array.set(ap, String(buffer, CopyString)); } break; case TAG_FMT_SINGLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->f); } else { array.set(ap, info_value->f); } break; case TAG_FMT_DOUBLE: if (l==1) { tmpi->set(String(name, CopyString), info_value->d); } else { array.set(ap, info_value->d); } break; } info_value = &info_data->value.list[ap]; } if (l>1) { tmpi->set(String(name, CopyString), array); } break; } } } if (sub_array) { value.set(exif_get_sectionname(section_index), tmp); } } } Variant HHVM_FUNCTION(exif_tagname, int64_t index) { char *szTemp; szTemp = exif_get_tagname(index, nullptr, 0, tag_table_IFD); if (index <0 || !szTemp || !szTemp[0]) { return false; } else { return String(szTemp, CopyString); } } Variant HHVM_FUNCTION(exif_read_data, const String& filename, const String& sections /*="" */, bool arrays /*=false */, bool thumbnail /*=false */) { int i, ret, sections_needed=0; image_info_type ImageInfo; char tmp[64], *sections_str, *s; memset(&ImageInfo, 0, sizeof(ImageInfo)); if (!sections.empty()) { php_vspprintf(&sections_str, 0, ",%s,", sections.c_str()); /* sections_str DOES start with , and SPACES are NOT allowed in names */ s = sections_str; while(*++s) { if (*s==' ') { *s = ','; } } for (i=0; i<SECTION_COUNT; i++) { snprintf(tmp, sizeof(tmp), ",%s,", exif_get_sectionname(i).c_str()); if (strstr(sections_str, tmp)) { sections_needed |= 1<<i; } } if (sections_str) IM_FREE(sections_str); } ret = exif_read_file(&ImageInfo, filename, thumbnail, 0); sections_str = exif_get_sectionlist(ImageInfo.sections_found); /* do not inform about in debug*/ ImageInfo.sections_found |= FOUND_COMPUTED|FOUND_FILE; if (ret==0|| (sections_needed && !(sections_needed&ImageInfo.sections_found))) { exif_discard_imageinfo(&ImageInfo); if (sections_str) IM_FREE(sections_str); return false; } /* now we can add our information */ exif_iif_add_str(&ImageInfo, SECTION_FILE, "FileName", (char *)ImageInfo.FileName.c_str()); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileDateTime", ImageInfo.FileDateTime); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileSize", ImageInfo.FileSize); exif_iif_add_int(&ImageInfo, SECTION_FILE, "FileType", ImageInfo.FileType); exif_iif_add_str(&ImageInfo, SECTION_FILE, "MimeType", (char*)php_image_type_to_mime_type(ImageInfo.FileType)); exif_iif_add_str(&ImageInfo, SECTION_FILE, "SectionsFound", sections_str ? sections_str : (char *)"NONE"); if (ImageInfo.Width>0 && ImageInfo.Height>0) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "html", "width=\"%d\" height=\"%d\"", ImageInfo.Width, ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Height", ImageInfo.Height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Width", ImageInfo.Width); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "IsColor", ImageInfo.IsColor); if (ImageInfo.motorola_intel != -1) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "ByteOrderMotorola", ImageInfo.motorola_intel); } if (ImageInfo.FocalLength) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocalLength", "%4.1Fmm", ImageInfo.FocalLength); if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "35mmFocalLength", "%dmm", (int)(ImageInfo.FocalLength/ImageInfo.CCDWidth*35+0.5)); } } if (ImageInfo.CCDWidth) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "CCDWidth", "%dmm", (int)ImageInfo.CCDWidth); } if (ImageInfo.ExposureTime>0) { if (ImageInfo.ExposureTime <= 0.5) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s (1/%d)", ImageInfo.ExposureTime, (int)(0.5 + 1/ImageInfo.ExposureTime)); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ExposureTime", "%0.3F s", ImageInfo.ExposureTime); } } if (ImageInfo.ApertureFNumber) { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "ApertureFNumber", "f/%.1F", ImageInfo.ApertureFNumber); } if (ImageInfo.Distance) { if (ImageInfo.Distance<0) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "Infinite"); } else { exif_iif_add_fmt(&ImageInfo, SECTION_COMPUTED, "FocusDistance", "%0.2Fm", ImageInfo.Distance); } } if (ImageInfo.UserComment) { exif_iif_add_buffer(&ImageInfo, SECTION_COMPUTED, "UserComment", ImageInfo.UserCommentLength, ImageInfo.UserComment); if (ImageInfo.UserCommentEncoding && strlen(ImageInfo.UserCommentEncoding)) { exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "UserCommentEncoding", ImageInfo.UserCommentEncoding); } } exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright", ImageInfo.Copyright); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Photographer", ImageInfo.CopyrightPhotographer); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Copyright.Editor", ImageInfo.CopyrightEditor); for (i=0; i<ImageInfo.xp_fields.count; i++) { exif_iif_add_str(&ImageInfo, SECTION_WINXP, exif_get_tagname(ImageInfo.xp_fields.list[i].tag, nullptr, 0, exif_get_tag_table(SECTION_WINXP)), ImageInfo.xp_fields.list[i].value); } if (ImageInfo.Thumbnail.size) { if (thumbnail) { /* not exif_iif_add_str : this is a buffer */ exif_iif_add_tag(&ImageInfo, SECTION_THUMBNAIL, "THUMBNAIL", TAG_NONE, TAG_FMT_UNDEFINED, ImageInfo.Thumbnail.size, ImageInfo.Thumbnail.data); } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { /* try to evaluate if thumbnail data is present */ exif_scan_thumbnail(&ImageInfo); } exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.FileType", ImageInfo.Thumbnail.filetype); exif_iif_add_str(&ImageInfo, SECTION_COMPUTED, "Thumbnail.MimeType", (char*)php_image_type_to_mime_type(ImageInfo.Thumbnail.filetype)); } if (ImageInfo.Thumbnail.width && ImageInfo.Thumbnail.height) { exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Height", ImageInfo.Thumbnail.height); exif_iif_add_int(&ImageInfo, SECTION_COMPUTED, "Thumbnail.Width", ImageInfo.Thumbnail.width); } if (sections_str) IM_FREE(sections_str); Array retarr; add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FILE); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMPUTED); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_ANY_TAG); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_IFD0); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_THUMBNAIL); add_assoc_image_info(retarr, true, &ImageInfo, SECTION_COMMENT); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_EXIF); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_GPS); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_INTEROP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_FPIX); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_APP12); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_WINXP); add_assoc_image_info(retarr, arrays, &ImageInfo, SECTION_MAKERNOTE); exif_discard_imageinfo(&ImageInfo); return retarr; } Variant HHVM_FUNCTION(exif_thumbnail, const String& filename, VRefParam width /* = null */, VRefParam height /* = null */, VRefParam imagetype /* = null */) { image_info_type ImageInfo; memset(&ImageInfo, 0, sizeof(ImageInfo)); int ret = exif_read_file(&ImageInfo, filename.c_str(), 1, 0); if (ret==0) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.data || !ImageInfo.Thumbnail.size) { exif_discard_imageinfo(&ImageInfo); return false; } if (!ImageInfo.Thumbnail.width || !ImageInfo.Thumbnail.height) { exif_scan_thumbnail(&ImageInfo); } width.assignIfRef((int64_t)ImageInfo.Thumbnail.width); height.assignIfRef((int64_t)ImageInfo.Thumbnail.height); imagetype.assignIfRef(ImageInfo.Thumbnail.filetype); String str(ImageInfo.Thumbnail.data, ImageInfo.Thumbnail.size, CopyString); exif_discard_imageinfo(&ImageInfo); return str; } Variant HHVM_FUNCTION(exif_imagetype, const String& filename) { auto stream = File::Open(filename, "rb"); if (!stream) { return false; } int itype = php_getimagetype(stream); stream->close(); if (itype == IMAGE_FILETYPE_UNKNOWN) return false; return itype; } /////////////////////////////////////////////////////////////////////////////// struct ExifExtension final : Extension { ExifExtension() : Extension("exif", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(exif_imagetype); HHVM_FE(exif_read_data); HHVM_FE(exif_tagname); HHVM_FE(exif_thumbnail); HHVM_RC_INT(EXIF_USE_MBSTRING, 0); loadSystemlib(); } } s_exif_extension; struct GdExtension final : Extension { GdExtension() : Extension("gd", NO_EXTENSION_VERSION_YET) {} void moduleInit() override { HHVM_FE(gd_info); HHVM_FE(getimagesize); HHVM_FE(getimagesizefromstring); HHVM_FE(image_type_to_extension); HHVM_FE(image_type_to_mime_type); HHVM_FE(image2wbmp); HHVM_FE(imageaffine); HHVM_FE(imageaffinematrixconcat); HHVM_FE(imageaffinematrixget); HHVM_FE(imagealphablending); HHVM_FE(imageantialias); HHVM_FE(imagearc); HHVM_FE(imagechar); HHVM_FE(imagecharup); HHVM_FE(imagecolorallocate); HHVM_FE(imagecolorallocatealpha); HHVM_FE(imagecolorat); HHVM_FE(imagecolorclosest); HHVM_FE(imagecolorclosestalpha); HHVM_FE(imagecolorclosesthwb); HHVM_FE(imagecolordeallocate); HHVM_FE(imagecolorexact); HHVM_FE(imagecolorexactalpha); HHVM_FE(imagecolormatch); HHVM_FE(imagecolorresolve); HHVM_FE(imagecolorresolvealpha); HHVM_FE(imagecolorset); HHVM_FE(imagecolorsforindex); HHVM_FE(imagecolorstotal); HHVM_FE(imagecolortransparent); HHVM_FE(imageconvolution); HHVM_FE(imagecopy); HHVM_FE(imagecopymerge); HHVM_FE(imagecopymergegray); HHVM_FE(imagecopyresampled); HHVM_FE(imagecopyresized); HHVM_FE(imagecreate); HHVM_FE(imagecreatefromgd2part); HHVM_FE(imagecreatefromgd); HHVM_FE(imagecreatefromgd2); HHVM_FE(imagecreatefromgif); #ifdef HAVE_GD_JPG HHVM_FE(imagecreatefromjpeg); #endif #ifdef HAVE_GD_PNG HHVM_FE(imagecreatefrompng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagecreatefromwebp); #endif HHVM_FE(imagecreatefromstring); HHVM_FE(imagecreatefromwbmp); HHVM_FE(imagecreatefromxbm); #if defined(HAVE_GD_XPM) && defined(HAVE_GD_BUNDLED) HHVM_FE(imagecreatefromxpm); #endif HHVM_FE(imagecreatetruecolor); HHVM_FE(imagecrop); HHVM_FE(imagecropauto); HHVM_FE(imagedashedline); HHVM_FE(imagedestroy); HHVM_FE(imageellipse); HHVM_FE(imagefill); HHVM_FE(imagefilledarc); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilledellipse); HHVM_FE(imagefilledpolygon); HHVM_FE(imagefilledrectangle); HHVM_FE(imagefilltoborder); HHVM_FE(imagefilter); HHVM_FE(imageflip); HHVM_FE(imagefontheight); HHVM_FE(imagefontwidth); #if defined(ENABLE_GD_TTF) && HAVE_LIBFREETYPE HHVM_FE(imageftbbox); HHVM_FE(imagefttext); #endif HHVM_FE(imagegammacorrect); HHVM_FE(imagegd2); HHVM_FE(imagegd); HHVM_FE(imagegif); HHVM_FE(imageinterlace); HHVM_FE(imageistruecolor); #ifdef HAVE_GD_JPG HHVM_FE(imagejpeg); #endif HHVM_FE(imagelayereffect); HHVM_FE(imageline); HHVM_FE(imageloadfont); #ifdef HAVE_GD_PNG HHVM_FE(imagepng); #endif #ifdef HAVE_LIBVPX HHVM_FE(imagewebp); #endif HHVM_FE(imagepolygon); HHVM_FE(imagerectangle); HHVM_FE(imagerotate); HHVM_FE(imagesavealpha); HHVM_FE(imagescale); HHVM_FE(imagesetbrush); HHVM_FE(imagesetinterpolation); HHVM_FE(imagesetpixel); HHVM_FE(imagesetstyle); HHVM_FE(imagesetthickness); HHVM_FE(imagesettile); HHVM_FE(imagestring); HHVM_FE(imagestringup); HHVM_FE(imagesx); HHVM_FE(imagesy); HHVM_FE(imagetruecolortopalette); #ifdef ENABLE_GD_TTF HHVM_FE(imagettfbbox); HHVM_FE(imagettftext); #endif HHVM_FE(imagetypes); HHVM_FE(imagewbmp); HHVM_FE(iptcembed); HHVM_FE(iptcparse); HHVM_FE(jpeg2wbmp); HHVM_FE(png2wbmp); HHVM_FE(imagepalettecopy); HHVM_RC_INT(IMG_GIF, IMAGE_TYPE_GIF); HHVM_RC_INT(IMG_JPG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_JPEG, IMAGE_TYPE_JPEG); HHVM_RC_INT(IMG_PNG, IMAGE_TYPE_PNG); HHVM_RC_INT(IMG_WBMP, IMAGE_TYPE_WBMP); HHVM_RC_INT(IMG_XPM, IMAGE_TYPE_XPM); /* special colours for gd */ HHVM_RC_INT(IMG_COLOR_TILED, gdTiled); HHVM_RC_INT(IMG_COLOR_STYLED, gdStyled); HHVM_RC_INT(IMG_COLOR_BRUSHED, gdBrushed); HHVM_RC_INT(IMG_COLOR_STYLEDBRUSHED, gdStyledBrushed); HHVM_RC_INT(IMG_COLOR_TRANSPARENT, gdTransparent); /* for imagefilledarc */ HHVM_RC_INT(IMG_ARC_ROUNDED, gdArc); HHVM_RC_INT(IMG_ARC_PIE, gdPie); HHVM_RC_INT(IMG_ARC_CHORD, gdChord); HHVM_RC_INT(IMG_ARC_NOFILL, gdNoFill); HHVM_RC_INT(IMG_ARC_EDGED, gdEdged); /* GD2 image format types */ HHVM_RC_INT(IMG_GD2_RAW, GD2_FMT_RAW); HHVM_RC_INT(IMG_GD2_COMPRESSED, GD2_FMT_COMPRESSED); HHVM_RC_INT(IMG_FLIP_HORIZONTAL, GD_FLIP_HORINZONTAL); HHVM_RC_INT(IMG_FLIP_VERTICAL, GD_FLIP_VERTICAL); HHVM_RC_INT(IMG_FLIP_BOTH, GD_FLIP_BOTH); HHVM_RC_INT(IMG_EFFECT_REPLACE, gdEffectReplace); HHVM_RC_INT(IMG_EFFECT_ALPHABLEND, gdEffectAlphaBlend); HHVM_RC_INT(IMG_EFFECT_NORMAL, gdEffectNormal); HHVM_RC_INT(IMG_EFFECT_OVERLAY, gdEffectOverlay); HHVM_RC_INT(IMG_CROP_DEFAULT, GD_CROP_DEFAULT); HHVM_RC_INT(IMG_CROP_TRANSPARENT, GD_CROP_TRANSPARENT); HHVM_RC_INT(IMG_CROP_BLACK, GD_CROP_BLACK); HHVM_RC_INT(IMG_CROP_WHITE, GD_CROP_WHITE); HHVM_RC_INT(IMG_CROP_SIDES, GD_CROP_SIDES); HHVM_RC_INT(IMG_CROP_THRESHOLD, GD_CROP_THRESHOLD); HHVM_RC_INT(IMG_BELL, GD_BELL); HHVM_RC_INT(IMG_BESSEL, GD_BESSEL); HHVM_RC_INT(IMG_BILINEAR_FIXED, GD_BILINEAR_FIXED); HHVM_RC_INT(IMG_BICUBIC, GD_BICUBIC); HHVM_RC_INT(IMG_BICUBIC_FIXED, GD_BICUBIC_FIXED); HHVM_RC_INT(IMG_BLACKMAN, GD_BLACKMAN); HHVM_RC_INT(IMG_BOX, GD_BOX); HHVM_RC_INT(IMG_BSPLINE, GD_BSPLINE); HHVM_RC_INT(IMG_CATMULLROM, GD_CATMULLROM); HHVM_RC_INT(IMG_GAUSSIAN, GD_GAUSSIAN); HHVM_RC_INT(IMG_GENERALIZED_CUBIC, GD_GENERALIZED_CUBIC); HHVM_RC_INT(IMG_HERMITE, GD_HERMITE); HHVM_RC_INT(IMG_HAMMING, GD_HAMMING); HHVM_RC_INT(IMG_HANNING, GD_HANNING); HHVM_RC_INT(IMG_MITCHELL, GD_MITCHELL); HHVM_RC_INT(IMG_POWER, GD_POWER); HHVM_RC_INT(IMG_QUADRATIC, GD_QUADRATIC); HHVM_RC_INT(IMG_SINC, GD_SINC); HHVM_RC_INT(IMG_NEAREST_NEIGHBOUR, GD_NEAREST_NEIGHBOUR); HHVM_RC_INT(IMG_WEIGHTED4, GD_WEIGHTED4); HHVM_RC_INT(IMG_TRIANGLE, GD_TRIANGLE); HHVM_RC_INT(IMG_AFFINE_TRANSLATE, GD_AFFINE_TRANSLATE); HHVM_RC_INT(IMG_AFFINE_SCALE, GD_AFFINE_SCALE); HHVM_RC_INT(IMG_AFFINE_ROTATE, GD_AFFINE_ROTATE); HHVM_RC_INT(IMG_AFFINE_SHEAR_HORIZONTAL, GD_AFFINE_SHEAR_HORIZONTAL); HHVM_RC_INT(IMG_AFFINE_SHEAR_VERTICAL, GD_AFFINE_SHEAR_VERTICAL); HHVM_RC_INT(IMG_FILTER_BRIGHTNESS, IMAGE_FILTER_BRIGHTNESS); HHVM_RC_INT(IMG_FILTER_COLORIZE, IMAGE_FILTER_COLORIZE); HHVM_RC_INT(IMG_FILTER_CONTRAST, IMAGE_FILTER_CONTRAST); HHVM_RC_INT(IMG_FILTER_EDGEDETECT, IMAGE_FILTER_EDGEDETECT); HHVM_RC_INT(IMG_FILTER_EMBOSS, IMAGE_FILTER_EMBOSS); HHVM_RC_INT(IMG_FILTER_GAUSSIAN_BLUR, IMAGE_FILTER_GAUSSIAN_BLUR); HHVM_RC_INT(IMG_FILTER_GRAYSCALE, IMAGE_FILTER_GRAYSCALE); HHVM_RC_INT(IMG_FILTER_MEAN_REMOVAL, IMAGE_FILTER_MEAN_REMOVAL); HHVM_RC_INT(IMG_FILTER_NEGATE, IMAGE_FILTER_NEGATE); HHVM_RC_INT(IMG_FILTER_SELECTIVE_BLUR, IMAGE_FILTER_SELECTIVE_BLUR); HHVM_RC_INT(IMG_FILTER_SMOOTH, IMAGE_FILTER_SMOOTH); HHVM_RC_INT(IMG_FILTER_PIXELATE, IMAGE_FILTER_PIXELATE); HHVM_RC_INT(IMAGETYPE_GIF, IMAGE_FILETYPE_GIF); HHVM_RC_INT(IMAGETYPE_JPEG, IMAGE_FILETYPE_JPEG); HHVM_RC_INT(IMAGETYPE_PNG, IMAGE_FILETYPE_PNG); HHVM_RC_INT(IMAGETYPE_SWF, IMAGE_FILETYPE_SWF); HHVM_RC_INT(IMAGETYPE_PSD, IMAGE_FILETYPE_PSD); HHVM_RC_INT(IMAGETYPE_BMP, IMAGE_FILETYPE_BMP); HHVM_RC_INT(IMAGETYPE_TIFF_II, IMAGE_FILETYPE_TIFF_II); HHVM_RC_INT(IMAGETYPE_TIFF_MM, IMAGE_FILETYPE_TIFF_MM); HHVM_RC_INT(IMAGETYPE_JPC, IMAGE_FILETYPE_JPC); HHVM_RC_INT(IMAGETYPE_JP2, IMAGE_FILETYPE_JP2); HHVM_RC_INT(IMAGETYPE_JPX, IMAGE_FILETYPE_JPX); HHVM_RC_INT(IMAGETYPE_JB2, IMAGE_FILETYPE_JB2); HHVM_RC_INT(IMAGETYPE_IFF, IMAGE_FILETYPE_IFF); HHVM_RC_INT(IMAGETYPE_WBMP, IMAGE_FILETYPE_WBMP); HHVM_RC_INT(IMAGETYPE_XBM, IMAGE_FILETYPE_XBM); HHVM_RC_INT(IMAGETYPE_ICO, IMAGE_FILETYPE_ICO); HHVM_RC_INT(IMAGETYPE_UNKNOWN, IMAGE_FILETYPE_UNKNOWN); HHVM_RC_INT(IMAGETYPE_COUNT, IMAGE_FILETYPE_COUNT); HHVM_RC_INT(IMAGETYPE_SWC, IMAGE_FILETYPE_SWC); HHVM_RC_INT(IMAGETYPE_JPEG2000, IMAGE_FILETYPE_JPC); #ifdef GD_VERSION_STRING HHVM_RC_STR(GD_VERSION, GD_VERSION_STRING); #endif #if defined(GD_MAJOR_VERSION) && defined(GD_MINOR_VERSION) && \ defined(GD_RELEASE_VERSION) && defined(GD_EXTRA_VERSION) HHVM_RC_INT_SAME(GD_MAJOR_VERSION); HHVM_RC_INT_SAME(GD_MINOR_VERSION); HHVM_RC_INT_SAME(GD_RELEASE_VERSION); HHVM_RC_STR_SAME(GD_EXTRA_VERSION); #endif #ifdef HAVE_GD_PNG HHVM_RC_INT(PNG_NO_FILTER, 0x00); HHVM_RC_INT(PNG_FILTER_NONE, 0x08); HHVM_RC_INT(PNG_FILTER_SUB, 0x10); HHVM_RC_INT(PNG_FILTER_UP, 0x20); HHVM_RC_INT(PNG_FILTER_AVG, 0x40); HHVM_RC_INT(PNG_FILTER_PAETH, 0x80); HHVM_RC_INT(PNG_ALL_FILTERS, 0x08 | 0x10 | 0x20 | 0x40 | 0x80); #endif HHVM_RC_BOOL(GD_BUNDLED, true); loadSystemlib(); } } s_gd_extension; /////////////////////////////////////////////////////////////////////////////// }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_845_0
crossvul-cpp_data_good_849_1
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/io/async/test/AsyncSSLSocketTest.h> #include <folly/SocketAddress.h> #include <folly/String.h> #include <folly/io/Cursor.h> #include <folly/io/async/AsyncPipe.h> #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/EventBase.h> #include <folly/io/async/ScopedEventBaseThread.h> #include <folly/net/NetOps.h> #include <folly/net/NetworkSocket.h> #include <folly/portability/GMock.h> #include <folly/portability/GTest.h> #include <folly/portability/OpenSSL.h> #include <folly/portability/Unistd.h> #include <folly/ssl/Init.h> #include <folly/io/async/test/BlockingSocket.h> #include <fcntl.h> #include <signal.h> #include <sys/types.h> #include <fstream> #include <iostream> #include <list> #include <set> #include <thread> #ifdef __linux__ #include <dlfcn.h> #endif #if FOLLY_OPENSSL_IS_110 #include <openssl/async.h> #endif #ifdef FOLLY_HAVE_MSG_ERRQUEUE #include <sys/utsname.h> #endif using std::cerr; using std::endl; using std::list; using std::min; using std::string; using std::vector; using namespace testing; #if defined __linux__ namespace { // to store libc's original setsockopt() typedef int (*setsockopt_ptr)(int, int, int, const void*, socklen_t); setsockopt_ptr real_setsockopt_ = nullptr; // global struct to initialize before main runs. we can init within a test, // or in main, but this method seems to be least intrsive and universal struct GlobalStatic { GlobalStatic() { real_setsockopt_ = (setsockopt_ptr)dlsym(RTLD_NEXT, "setsockopt"); } void reset() noexcept { ttlsDisabledSet.clear(); } // for each fd, tracks whether TTLS is disabled or not std::unordered_set<folly::NetworkSocket /* fd */> ttlsDisabledSet; }; // the constructor will be called before main() which is all we care about GlobalStatic globalStatic; } // namespace // we intercept setsoctopt to test setting NO_TRANSPARENT_TLS opt // this name has to be global int setsockopt( int sockfd, int level, int optname, const void* optval, socklen_t optlen) { if (optname == SO_NO_TRANSPARENT_TLS) { globalStatic.ttlsDisabledSet.insert(folly::NetworkSocket::fromFd(sockfd)); return 0; } return real_setsockopt_(sockfd, level, optname, optval, optlen); } #endif namespace folly { constexpr size_t SSLClient::kMaxReadBufferSz; constexpr size_t SSLClient::kMaxReadsPerEvent; void getfds(NetworkSocket fds[2]) { if (netops::socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) { FAIL() << "failed to create socketpair: " << errnoStr(errno); } for (int idx = 0; idx < 2; ++idx) { if (netops::set_socket_non_blocking(fds[idx]) != 0) { FAIL() << "failed to put socket " << idx << " in non-blocking mode: " << errnoStr(errno); } } } void getctx( std::shared_ptr<folly::SSLContext> clientCtx, std::shared_ptr<folly::SSLContext> serverCtx) { clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadPrivateKey(kTestKey); } void sslsocketpair( EventBase* eventBase, AsyncSSLSocket::UniquePtr* clientSock, AsyncSSLSocket::UniquePtr* serverSock) { auto clientCtx = std::make_shared<folly::SSLContext>(); auto serverCtx = std::make_shared<folly::SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, serverCtx); clientSock->reset(new AsyncSSLSocket(clientCtx, eventBase, fds[0], false)); serverSock->reset(new AsyncSSLSocket(serverCtx, eventBase, fds[1], true)); // (*clientSock)->setSendTimeout(100); // (*serverSock)->setSendTimeout(100); } // client protocol filters bool clientProtoFilterPickPony( unsigned char** client, unsigned int* client_len, const unsigned char*, unsigned int) { // the protocol string in length prefixed byte string. the // length byte is not included in the length static unsigned char p[7] = {6, 'p', 'o', 'n', 'i', 'e', 's'}; *client = p; *client_len = 7; return true; } bool clientProtoFilterPickNone( unsigned char**, unsigned int*, const unsigned char*, unsigned int) { return false; } std::string getFileAsBuf(const char* fileName) { std::string buffer; folly::readFile(fileName, buffer); return buffer; } /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server. */ TEST(AsyncSSLSocketTest, ConnectWriteReadClose) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem"); // sslContext->authenticate(true, false); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(std::chrono::milliseconds(10000)); // write() uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); // read() uint8_t readbuf[128]; uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf)); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0); // close() socket->close(); cerr << "ConnectWriteReadClose test completed" << endl; EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000); } /** * Same as above simple test, but with a large read len to test * clamping behavior. */ TEST(AsyncSSLSocketTest, ConnectWriteReadLargeClose) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem"); // sslContext->authenticate(true, false); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(std::chrono::milliseconds(10000)); // write() uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); // read() uint8_t readbuf[128]; // we will fake the read len but that should be fine size_t readLen = 1L << 33; uint32_t bytesRead = socket->read(readbuf, readLen); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0); // close() socket->close(); cerr << "ConnectWriteReadClose test completed" << endl; EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000); } /** * Test reading after server close. */ TEST(AsyncSSLSocketTest, ReadAfterClose) { // Start listening on a local port WriteCallbackBase writeCallback; ReadEOFCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); auto server = std::make_unique<TestSSLServer>(&acceptCallback); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); auto socket = std::make_shared<BlockingSocket>(server->getAddress(), sslContext); socket->open(); // This should trigger an EOF on the client. auto evb = handshakeCallback.getSocket()->getEventBase(); evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); }); std::array<uint8_t, 128> readbuf; auto bytesRead = socket->read(readbuf.data(), readbuf.size()); EXPECT_EQ(0, bytesRead); } /** * Test bad renegotiation */ #if !defined(OPENSSL_IS_BORINGSSL) TEST(AsyncSSLSocketTest, Renegotiate) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); std::array<NetworkSocket, 2> fds; getfds(fds.data()); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); RenegotiatingServer server(std::move(serverSock)); while (!client.handshakeSuccess_ && !client.handshakeError_) { eventBase.loopOnce(); } ASSERT_TRUE(client.handshakeSuccess_); auto sslSock = std::move(client).moveSocket(); sslSock->detachEventBase(); // This is nasty, however we don't want to add support for // renegotiation in AsyncSSLSocket. SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL())); auto socket = std::make_shared<BlockingSocket>(std::move(sslSock)); std::thread t([&]() { eventBase.loopForever(); }); // Trigger the renegotiation. std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); try { socket->write(buf.data(), buf.size()); } catch (AsyncSocketException& e) { LOG(INFO) << "client got error " << e.what(); } eventBase.terminateLoopSoon(); t.join(); eventBase.loop(); ASSERT_TRUE(server.renegotiationError_); } #endif /** * Negative test for handshakeError(). */ TEST(AsyncSSLSocketTest, HandshakeError) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); HandshakeErrorCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); // read() bool ex = false; try { socket->open(); uint8_t readbuf[128]; uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf)); LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing"; } catch (AsyncSocketException&) { ex = true; } EXPECT_TRUE(ex); // close() socket->close(); cerr << "HandshakeError test completed" << endl; } /** * Negative test for readError(). */ TEST(AsyncSSLSocketTest, ReadError) { // Start listening on a local port WriteCallbackBase writeCallback; ReadErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // write something to trigger ssl handshake uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); socket->close(); cerr << "ReadError test completed" << endl; } /** * Negative test for writeError(). */ TEST(AsyncSSLSocketTest, WriteError) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // write something to trigger ssl handshake uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); socket->close(); cerr << "WriteError test completed" << endl; } /** * Test a socket with TCP_NODELAY unset. */ TEST(AsyncSSLSocketTest, SocketWithDelay) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. std::shared_ptr<SSLContext> sslContext(new SSLContext()); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // write() uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); socket->write(buf, sizeof(buf)); // read() uint8_t readbuf[128]; uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf)); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0); // close() socket->close(); cerr << "SocketWithDelay test completed" << endl; } #if FOLLY_OPENSSL_HAS_ALPN class NextProtocolTest : public Test { // For matching protos public: void SetUp() override { getctx(clientCtx, serverCtx); } void connect(bool unset = false) { getfds(fds); if (unset) { // unsetting NPN for any of [client, server] is enough to make NPN not // work clientCtx->unsetNextProtocols(); } AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); client = std::make_unique<AlpnClient>(std::move(clientSock)); server = std::make_unique<AlpnServer>(std::move(serverSock)); eventBase.loop(); } void expectProtocol(const std::string& proto) { expectHandshakeSuccess(); EXPECT_NE(client->nextProtoLength, 0); EXPECT_EQ(client->nextProtoLength, server->nextProtoLength); EXPECT_EQ( memcmp(client->nextProto, server->nextProto, server->nextProtoLength), 0); string selected((const char*)client->nextProto, client->nextProtoLength); EXPECT_EQ(proto, selected); } void expectNoProtocol() { expectHandshakeSuccess(); EXPECT_EQ(client->nextProtoLength, 0); EXPECT_EQ(server->nextProtoLength, 0); EXPECT_EQ(client->nextProto, nullptr); EXPECT_EQ(server->nextProto, nullptr); } void expectHandshakeSuccess() { EXPECT_FALSE(client->except.hasValue()) << "client handshake error: " << client->except->what(); EXPECT_FALSE(server->except.hasValue()) << "server handshake error: " << server->except->what(); } void expectHandshakeError() { EXPECT_TRUE(client->except.hasValue()) << "Expected client handshake error!"; EXPECT_TRUE(server->except.hasValue()) << "Expected server handshake error!"; } EventBase eventBase; std::shared_ptr<SSLContext> clientCtx{std::make_shared<SSLContext>()}; std::shared_ptr<SSLContext> serverCtx{std::make_shared<SSLContext>()}; NetworkSocket fds[2]; std::unique_ptr<AlpnClient> client; std::unique_ptr<AlpnServer> server; }; TEST_F(NextProtocolTest, AlpnTestOverlap) { clientCtx->setAdvertisedNextProtocols({"blub", "baz"}); serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); connect(); expectProtocol("baz"); } TEST_F(NextProtocolTest, AlpnTestUnset) { // Identical to above test, except that we want unset NPN before // looping. clientCtx->setAdvertisedNextProtocols({"blub", "baz"}); serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); connect(true /* unset */); expectNoProtocol(); } TEST_F(NextProtocolTest, AlpnTestNoOverlap) { clientCtx->setAdvertisedNextProtocols({"blub"}); serverCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); connect(); expectNoProtocol(); } TEST_F(NextProtocolTest, RandomizedAlpnTest) { // Probability that this test will fail is 2^-64, which could be considered // as negligible. const int kTries = 64; clientCtx->setAdvertisedNextProtocols({"foo", "bar", "baz"}); serverCtx->setRandomizedAdvertisedNextProtocols({{1, {"foo"}}, {1, {"bar"}}}); std::set<string> selectedProtocols; for (int i = 0; i < kTries; ++i) { connect(); EXPECT_NE(client->nextProtoLength, 0); EXPECT_EQ(client->nextProtoLength, server->nextProtoLength); EXPECT_EQ( memcmp(client->nextProto, server->nextProto, server->nextProtoLength), 0); string selected((const char*)client->nextProto, client->nextProtoLength); selectedProtocols.insert(selected); expectHandshakeSuccess(); } EXPECT_EQ(selectedProtocols.size(), 2); } #endif #ifndef OPENSSL_NO_TLSEXT /** * 1. Client sends TLSEXT_HOSTNAME in client hello. * 2. Server found a match SSL_CTX and use this SSL_CTX to * continue the SSL handshake. * 3. Server sends back TLSEXT_HOSTNAME in server hello. */ TEST(AsyncSSLSocketTest, SNITestMatch) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string serverName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverName); eventBase.loop(); EXPECT_TRUE(client.serverNameMatch); EXPECT_TRUE(server.serverNameMatch); } /** * 1. Client sends TLSEXT_HOSTNAME in client hello. * 2. Server cannot find a matching SSL_CTX and continue to use * the current SSL_CTX to do the handshake. * 3. Server does not send back TLSEXT_HOSTNAME in server hello. */ TEST(AsyncSSLSocketTest, SNITestNotMatch) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string clientRequestingServerName("foo.com"); const std::string serverExpectedServerName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock(new AsyncSSLSocket( clientCtx, &eventBase, fds[0], clientRequestingServerName)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverExpectedServerName); eventBase.loop(); EXPECT_TRUE(!client.serverNameMatch); EXPECT_TRUE(!server.serverNameMatch); } /** * 1. Client sends TLSEXT_HOSTNAME in client hello. * 2. We then change the serverName. * 3. We expect that we get 'false' as the result for serNameMatch. */ TEST(AsyncSSLSocketTest, SNITestChangeServerName) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string serverName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName)); // Change the server name std::string newName("new.com"); clientSock->setServerName(newName); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverName); eventBase.loop(); EXPECT_TRUE(!client.serverNameMatch); } /** * 1. Client does not send TLSEXT_HOSTNAME in client hello. * 2. Server does not send back TLSEXT_HOSTNAME in server hello. */ TEST(AsyncSSLSocketTest, SNITestClientHelloNoHostname) { EventBase eventBase; std::shared_ptr<SSLContext> clientCtx(new SSLContext); std::shared_ptr<SSLContext> dfServerCtx(new SSLContext); // Use the same SSLContext to continue the handshake after // tlsext_hostname match. std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx); const std::string serverExpectedServerName("xyz.newdev.facebook.com"); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SNIClient client(std::move(clientSock)); SNIServer server( std::move(serverSock), dfServerCtx, hskServerCtx, serverExpectedServerName); eventBase.loop(); EXPECT_TRUE(!client.serverNameMatch); EXPECT_TRUE(!server.serverNameMatch); } #endif /** * Test SSL client socket */ TEST(AsyncSSLSocketTest, SSLClientTest) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL client EventBase eventBase; auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1); client->connect(); EventBaseAborter eba(&eventBase, 3000); eventBase.loop(); EXPECT_EQ(client->getMiss(), 1); EXPECT_EQ(client->getHit(), 0); cerr << "SSLClientTest test completed" << endl; } /** * Test SSL client socket session re-use */ TEST(AsyncSSLSocketTest, SSLClientTestReuse) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL client EventBase eventBase; auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10); client->connect(); EventBaseAborter eba(&eventBase, 3000); eventBase.loop(); EXPECT_EQ(client->getMiss(), 1); EXPECT_EQ(client->getHit(), 9); cerr << "SSLClientTestReuse test completed" << endl; } /** * Test SSL client socket timeout */ TEST(AsyncSSLSocketTest, SSLClientTimeoutTest) { // Start listening on a local port EmptyReadCallback readCallback; HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); HandshakeTimeoutCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL client EventBase eventBase; auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10); client->connect(true /* write before connect completes */); EventBaseAborter eba(&eventBase, 3000); eventBase.loop(); usleep(100000); // This is checking that the connectError callback precedes any queued // writeError callbacks. This matches AsyncSocket's behavior EXPECT_EQ(client->getWriteAfterConnectErrors(), 1); EXPECT_EQ(client->getErrors(), 1); EXPECT_EQ(client->getMiss(), 0); EXPECT_EQ(client->getHit(), 0); cerr << "SSLClientTimeoutTest test completed" << endl; } class PerLoopReadCallback : public AsyncTransportWrapper::ReadCallback { public: void getReadBuffer(void** bufReturn, size_t* lenReturn) override { *bufReturn = buf_.data(); *lenReturn = buf_.size(); } void readDataAvailable(size_t len) noexcept override { VLOG(3) << "Read of size: " << len; s_->setReadCB(nullptr); s_->getEventBase()->runInLoop([this]() { s_->setReadCB(this); }); } void readErr(const AsyncSocketException&) noexcept override {} void readEOF() noexcept override {} void setSocket(AsyncSocket* s) { s_ = s; } private: AsyncSocket* s_; std::array<uint8_t, 1000> buf_; }; class CloseNotifyConnector : public AsyncSocket::ConnectCallback { public: CloseNotifyConnector(EventBase* evb, const SocketAddress& addr) { evb_ = evb; ssl_ = AsyncSSLSocket::newSocket(std::make_shared<SSLContext>(), evb_); ssl_->connect(this, addr); } void connectSuccess() noexcept override { ssl_->writeChain(nullptr, IOBuf::copyBuffer("hi")); auto ssl = const_cast<SSL*>(ssl_->getSSL()); SSL_shutdown(ssl); auto fd = ssl_->detachNetworkSocket(); tcp_.reset(new AsyncSocket(evb_, fd), AsyncSocket::Destructor()); evb_->runAfterDelay( [this]() { perLoopReads_.setSocket(tcp_.get()); tcp_->setReadCB(&perLoopReads_); evb_->runAfterDelay([this]() { tcp_->closeNow(); }, 10); }, 100); } void connectErr(const AsyncSocketException& ex) noexcept override { FAIL() << ex.what(); } private: EventBase* evb_; std::shared_ptr<AsyncSSLSocket> ssl_; std::shared_ptr<AsyncSocket> tcp_; PerLoopReadCallback perLoopReads_; }; class ErrorCheckingWriteCallback : public AsyncSocket::WriteCallback { public: void writeSuccess() noexcept override {} void writeErr(size_t, const AsyncSocketException& ex) noexcept override { LOG(ERROR) << "write error: " << ex.what(); EXPECT_NE( ex.getType(), AsyncSocketException::AsyncSocketExceptionType::SSL_ERROR); } }; class WriteOnEofReadCallback : public ReadCallback { public: using ReadCallback::ReadCallback; void readEOF() noexcept override { LOG(INFO) << "Got EOF"; auto chain = IOBuf::create(0); for (size_t i = 0; i < 1000 * 1000; i++) { auto buf = IOBuf::create(10); buf->append(10); memset(buf->writableData(), 'x', 10); chain->prependChain(std::move(buf)); } socket_->writeChain(&writeCallback_, std::move(chain)); } void readErr(const AsyncSocketException& ex) noexcept override { LOG(ERROR) << ex.what(); } private: ErrorCheckingWriteCallback writeCallback_; }; TEST(AsyncSSLSocketTest, EarlyCloseNotify) { WriteOnEofReadCallback readCallback(nullptr); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); EventBase eventBase; CloseNotifyConnector cnc(&eventBase, server.getAddress()); eventBase.loop(); } /** * Verify Client Ciphers obtained using SSL MSG Callback. */ TEST(AsyncSSLSocketTest, SSLParseClientHelloSuccess) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("AES256-SHA:AES128-SHA"); clientCtx->loadPrivateKey(kTestKey); clientCtx->loadCertificate(kTestCert); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true); eventBase.loop(); #if defined(OPENSSL_IS_BORINGSSL) EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA"); #else EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff"); #endif EXPECT_EQ(server.chosenCipher_, "AES256-SHA"); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_TRUE(server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); } /** * Verify that server is able to get client cert by getPeerCert() API. */ TEST(AsyncSSLSocketTest, GetClientCertificate) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kClientTestCA); serverCtx->loadClientCAList(kClientTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("AES256-SHA:AES128-SHA"); clientCtx->loadPrivateKey(kClientTestKey); clientCtx->loadCertificate(kClientTestCert); clientCtx->loadTrustedCertificates(kTestCA); std::array<NetworkSocket, 2> fds; getfds(fds.data()); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true); eventBase.loop(); // Handshake should succeed. EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(server.handshakeSuccess_); // Reclaim the sockets from SSLHandshakeBase. auto cliSocket = std::move(client).moveSocket(); auto srvSocket = std::move(server).moveSocket(); // Client cert retrieved from server side. auto serverPeerCert = srvSocket->getPeerCertificate(); CHECK(serverPeerCert); // Client cert retrieved from client side. auto clientSelfCert = cliSocket->getSelfCertificate(); CHECK(clientSelfCert); auto serverX509 = serverPeerCert->getX509(); auto clientX509 = clientSelfCert->getX509(); CHECK(serverX509); CHECK(clientX509); // The two certs should be the same. EXPECT_EQ(0, X509_cmp(clientX509.get(), serverX509.get())); } TEST(AsyncSSLSocketTest, SSLParseClientHelloOnePacket) { EventBase eventBase; auto ctx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); int bufLen = 42; uint8_t majorVersion = 18; uint8_t minorVersion = 25; // Create callback buf auto buf = IOBuf::create(bufLen); buf->append(bufLen); folly::io::RWPrivateCursor cursor(buf.get()); cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO); cursor.write<uint16_t>(0); cursor.write<uint8_t>(38); cursor.write<uint8_t>(majorVersion); cursor.write<uint8_t>(minorVersion); cursor.skip(32); cursor.write<uint32_t>(0); SSL* ssl = ctx->createSSL(); SCOPE_EXIT { SSL_free(ssl); }; AsyncSSLSocket::UniquePtr sock( new AsyncSSLSocket(ctx, &eventBase, fds[0], true)); sock->enableClientHelloParsing(); // Test client hello parsing in one packet AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get()); buf.reset(); auto parsedClientHello = sock->getClientHelloInfo(); EXPECT_TRUE(parsedClientHello != nullptr); EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion); EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion); } TEST(AsyncSSLSocketTest, SSLParseClientHelloTwoPackets) { EventBase eventBase; auto ctx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); int bufLen = 42; uint8_t majorVersion = 18; uint8_t minorVersion = 25; // Create callback buf auto buf = IOBuf::create(bufLen); buf->append(bufLen); folly::io::RWPrivateCursor cursor(buf.get()); cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO); cursor.write<uint16_t>(0); cursor.write<uint8_t>(38); cursor.write<uint8_t>(majorVersion); cursor.write<uint8_t>(minorVersion); cursor.skip(32); cursor.write<uint32_t>(0); SSL* ssl = ctx->createSSL(); SCOPE_EXIT { SSL_free(ssl); }; AsyncSSLSocket::UniquePtr sock( new AsyncSSLSocket(ctx, &eventBase, fds[0], true)); sock->enableClientHelloParsing(); // Test parsing with two packets with first packet size < 3 auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2); AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(), ssl, sock.get()); bufCopy.reset(); bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2); AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(), ssl, sock.get()); bufCopy.reset(); auto parsedClientHello = sock->getClientHelloInfo(); EXPECT_TRUE(parsedClientHello != nullptr); EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion); EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion); } TEST(AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets) { EventBase eventBase; auto ctx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); int bufLen = 42; uint8_t majorVersion = 18; uint8_t minorVersion = 25; // Create callback buf auto buf = IOBuf::create(bufLen); buf->append(bufLen); folly::io::RWPrivateCursor cursor(buf.get()); cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO); cursor.write<uint16_t>(0); cursor.write<uint8_t>(38); cursor.write<uint8_t>(majorVersion); cursor.write<uint8_t>(minorVersion); cursor.skip(32); cursor.write<uint32_t>(0); SSL* ssl = ctx->createSSL(); SCOPE_EXIT { SSL_free(ssl); }; AsyncSSLSocket::UniquePtr sock( new AsyncSSLSocket(ctx, &eventBase, fds[0], true)); sock->enableClientHelloParsing(); // Test parsing with multiple small packets for (std::size_t i = 0; i < buf->length(); i += 3) { auto bufCopy = folly::IOBuf::copyBuffer( buf->data() + i, std::min((std::size_t)3, buf->length() - i)); AsyncSSLSocket::clientHelloParsingCallback( 0, 0, SSL3_RT_HANDSHAKE, bufCopy->data(), bufCopy->length(), ssl, sock.get()); bufCopy.reset(); } auto parsedClientHello = sock->getClientHelloInfo(); EXPECT_TRUE(parsedClientHello != nullptr); EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion); EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion); } /** * Verify sucessful behavior of SSL certificate validation. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationSuccess) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); clientCtx->loadTrustedCertificates(kTestCA); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the client's verification callback is able to fail SSL * connection establishment. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationFailure) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, false); clientCtx->loadTrustedCertificates(kTestCA); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(!client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(!server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the options in SSLContext can be overridden in * sslConnect/Accept.i.e specifying that no validation should be performed * allows an otherwise-invalid certificate to be accepted and doesn't fire * the validation callback. */ TEST(AsyncSSLSocketTest, OverrideSSLCtxDisableVerify) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClientNoVerify client(std::move(clientSock), false, false); clientCtx->loadTrustedCertificates(kTestCA); SSLHandshakeServerNoVerify server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(!client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the options in SSLContext can be overridden in * sslConnect/Accept. Enable verification even if context says otherwise. * Test requireClientCert with client cert */ TEST(AsyncSSLSocketTest, OverrideSSLCtxEnableVerify) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadPrivateKey(kTestKey); clientCtx->loadCertificate(kTestCert); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClientDoVerify client(std::move(clientSock), true, true); SSLHandshakeServerDoVerify server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that the client's verification callback is able to override * the preverification failure and allow a successful connection. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationOverride) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Verify that specifying that no validation should be performed allows an * otherwise-invalid certificate to be accepted and doesn't fire the validation * callback. */ TEST(AsyncSSLSocketTest, SSLHandshakeValidationSkip) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, dfServerCtx); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(!client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(!client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(!server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(!server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } /** * Test requireClientCert with client cert */ TEST(AsyncSSLSocketTest, ClientCertHandshakeSuccess) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption( SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadPrivateKey(kTestKey); clientCtx->loadCertificate(kTestCert); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeVerify_); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(server.handshakeVerify_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); // check certificates auto clientSsl = std::move(client).moveSocket(); auto serverSsl = std::move(server).moveSocket(); auto clientPeer = clientSsl->getPeerCertificate(); auto clientSelf = clientSsl->getSelfCertificate(); auto serverPeer = serverSsl->getPeerCertificate(); auto serverSelf = serverSsl->getSelfCertificate(); EXPECT_NE(clientPeer, nullptr); EXPECT_NE(clientSelf, nullptr); EXPECT_NE(serverPeer, nullptr); EXPECT_NE(serverSelf, nullptr); EXPECT_EQ(clientPeer->getIdentity(), serverSelf->getIdentity()); EXPECT_EQ(clientSelf->getIdentity(), serverPeer->getIdentity()); } /** * Test requireClientCert with no client cert */ TEST(AsyncSSLSocketTest, NoClientCertHandshakeError) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->setVerificationOption( SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_FALSE(server.handshakeVerify_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_LE(0, server.handshakeTime.count()); } /** * Test OpenSSL 1.1.0's async functionality */ #if FOLLY_OPENSSL_IS_110 static void makeNonBlockingPipe(int pipefds[2]) { if (pipe(pipefds) != 0) { throw std::runtime_error("Cannot create pipe"); } if (::fcntl(pipefds[0], F_SETFL, O_NONBLOCK) != 0) { throw std::runtime_error("Cannot set pipe to nonblocking"); } if (::fcntl(pipefds[1], F_SETFL, O_NONBLOCK) != 0) { throw std::runtime_error("Cannot set pipe to nonblocking"); } } // Custom RSA private key encryption method static int kRSAExIndex = -1; static int kRSAEvbExIndex = -1; static int kRSASocketExIndex = -1; static constexpr StringPiece kEngineId = "AsyncSSLSocketTest"; static int customRsaPrivEnc( int flen, const unsigned char* from, unsigned char* to, RSA* rsa, int padding) { LOG(INFO) << "rsa_priv_enc"; EventBase* asyncJobEvb = reinterpret_cast<EventBase*>(RSA_get_ex_data(rsa, kRSAEvbExIndex)); CHECK(asyncJobEvb); RSA* actualRSA = reinterpret_cast<RSA*>(RSA_get_ex_data(rsa, kRSAExIndex)); CHECK(actualRSA); AsyncSSLSocket* socket = reinterpret_cast<AsyncSSLSocket*>( RSA_get_ex_data(rsa, kRSASocketExIndex)); ASYNC_JOB* job = ASYNC_get_current_job(); if (job == nullptr) { throw std::runtime_error("Expected call in job context"); } ASYNC_WAIT_CTX* waitctx = ASYNC_get_wait_ctx(job); OSSL_ASYNC_FD pipefds[2] = {0, 0}; makeNonBlockingPipe(pipefds); if (!ASYNC_WAIT_CTX_set_wait_fd( waitctx, kEngineId.data(), pipefds[0], nullptr, nullptr)) { throw std::runtime_error("Cannot set wait fd"); } int ret = 0; int* retptr = &ret; auto hand = folly::NetworkSocket::native_handle_type(pipefds[1]); auto asyncPipeWriter = folly::AsyncPipeWriter::newWriter( asyncJobEvb, folly::NetworkSocket(hand)); asyncJobEvb->runInEventBaseThread([retptr = retptr, flen = flen, from = from, to = to, padding = padding, actualRSA = actualRSA, writer = std::move(asyncPipeWriter), socket = socket]() { LOG(INFO) << "Running job"; if (socket) { LOG(INFO) << "Got a socket passed in, closing it..."; socket->closeNow(); } *retptr = RSA_meth_get_priv_enc(RSA_PKCS1_OpenSSL())( flen, from, to, actualRSA, padding); LOG(INFO) << "Finished job, writing to pipe"; uint8_t byte = *retptr > 0 ? 1 : 0; writer->write(nullptr, &byte, 1); }); LOG(INFO) << "About to pause job"; ASYNC_pause_job(); LOG(INFO) << "Resumed job with ret: " << ret; return ret; } void rsaFree(void*, void* ptr, CRYPTO_EX_DATA*, int, long, void*) { LOG(INFO) << "RSA_free is called with ptr " << std::hex << ptr; if (ptr == nullptr) { LOG(INFO) << "Returning early from rsaFree because ptr is null"; return; } RSA* rsa = (RSA*)ptr; auto meth = RSA_get_method(rsa); if (meth != RSA_get_default_method()) { auto nonconst = const_cast<RSA_METHOD*>(meth); RSA_meth_free(nonconst); RSA_set_method(rsa, RSA_get_default_method()); } RSA_free(rsa); } struct RSAPointers { RSA* actualrsa{nullptr}; RSA* dummyrsa{nullptr}; RSA_METHOD* meth{nullptr}; }; inline void RSAPointersFree(RSAPointers* p) { if (p->meth && p->dummyrsa && RSA_get_method(p->dummyrsa) == p->meth) { RSA_set_method(p->dummyrsa, RSA_get_default_method()); } if (p->meth) { LOG(INFO) << "Freeing meth"; RSA_meth_free(p->meth); } if (p->actualrsa) { LOG(INFO) << "Freeing actualrsa"; RSA_free(p->actualrsa); } if (p->dummyrsa) { LOG(INFO) << "Freeing dummyrsa"; RSA_free(p->dummyrsa); } delete p; } using RSAPointersDeleter = folly::static_function_deleter<RSAPointers, RSAPointersFree>; std::unique_ptr<RSAPointers, RSAPointersDeleter> setupCustomRSA(const char* certPath, const char* keyPath, EventBase* jobEvb) { auto certPEM = getFileAsBuf(certPath); auto keyPEM = getFileAsBuf(keyPath); ssl::BioUniquePtr certBio( BIO_new_mem_buf((void*)certPEM.data(), certPEM.size())); ssl::BioUniquePtr keyBio( BIO_new_mem_buf((void*)keyPEM.data(), keyPEM.size())); ssl::X509UniquePtr cert( PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr)); ssl::EvpPkeyUniquePtr evpPkey( PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr)); ssl::EvpPkeyUniquePtr publicEvpPkey(X509_get_pubkey(cert.get())); std::unique_ptr<RSAPointers, RSAPointersDeleter> ret(new RSAPointers()); RSA* actualrsa = EVP_PKEY_get1_RSA(evpPkey.get()); LOG(INFO) << "actualrsa ptr " << std::hex << (void*)actualrsa; RSA* dummyrsa = EVP_PKEY_get1_RSA(publicEvpPkey.get()); if (dummyrsa == nullptr) { throw std::runtime_error("Couldn't get RSA cert public factors"); } RSA_METHOD* meth = RSA_meth_dup(RSA_get_default_method()); if (meth == nullptr || RSA_meth_set1_name(meth, "Async RSA method") == 0 || RSA_meth_set_priv_enc(meth, customRsaPrivEnc) == 0 || RSA_meth_set_flags(meth, RSA_METHOD_FLAG_NO_CHECK) == 0) { throw std::runtime_error("Cannot create async RSA_METHOD"); } RSA_set_method(dummyrsa, meth); RSA_set_flags(dummyrsa, RSA_FLAG_EXT_PKEY); kRSAExIndex = RSA_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); kRSAEvbExIndex = RSA_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); kRSASocketExIndex = RSA_get_ex_new_index(0, nullptr, nullptr, nullptr, nullptr); CHECK_NE(kRSAExIndex, -1); CHECK_NE(kRSAEvbExIndex, -1); CHECK_NE(kRSASocketExIndex, -1); RSA_set_ex_data(dummyrsa, kRSAExIndex, actualrsa); RSA_set_ex_data(dummyrsa, kRSAEvbExIndex, jobEvb); ret->actualrsa = actualrsa; ret->dummyrsa = dummyrsa; ret->meth = meth; return ret; } // TODO: disabled with ASAN doesn't play nice with ASYNC for some reason #ifndef FOLLY_SANITIZE_ADDRESS TEST(AsyncSSLSocketTest, OpenSSL110AsyncTest) { ASYNC_init_thread(1, 1); EventBase eventBase; ScopedEventBaseThread jobEvbThread; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); auto rsaPointers = setupCustomRSA(kTestCert, kTestKey, jobEvbThread.getEventBase()); CHECK(rsaPointers->dummyrsa); // up-refs dummyrsa SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa); SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_TRUE(client.handshakeSuccess_); ASYNC_cleanup_thread(); } TEST(AsyncSSLSocketTest, OpenSSL110AsyncTestFailure) { ASYNC_init_thread(1, 1); EventBase eventBase; ScopedEventBaseThread jobEvbThread; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); // Set the wrong key for the cert auto rsaPointers = setupCustomRSA(kTestCert, kClientTestKey, jobEvbThread.getEventBase()); CHECK(rsaPointers->dummyrsa); SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa); SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(server.handshakeError_); EXPECT_TRUE(client.handshakeError_); ASYNC_cleanup_thread(); } TEST(AsyncSSLSocketTest, OpenSSL110AsyncTestClosedWithCallbackPending) { ASYNC_init_thread(1, 1); EventBase eventBase; ScopedEventBaseThread jobEvbThread; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadCertificate(kTestCert); serverCtx->loadTrustedCertificates(kTestCA); serverCtx->loadClientCAList(kTestCA); auto rsaPointers = setupCustomRSA(kTestCert, kTestKey, jobEvbThread.getEventBase()); CHECK(rsaPointers->dummyrsa); // up-refs dummyrsa SSL_CTX_use_RSAPrivateKey(serverCtx->getSSLCtx(), rsaPointers->dummyrsa); SSL_CTX_set_mode(serverCtx->getSSLCtx(), SSL_MODE_ASYNC); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); RSA_set_ex_data(rsaPointers->dummyrsa, kRSASocketExIndex, serverSock.get()); SSLHandshakeClient client(std::move(clientSock), false, false); SSLHandshakeServer server(std::move(serverSock), false, false); eventBase.loop(); EXPECT_TRUE(server.handshakeError_); EXPECT_TRUE(client.handshakeError_); ASYNC_cleanup_thread(); } #endif // FOLLY_SANITIZE_ADDRESS #endif // FOLLY_OPENSSL_IS_110 TEST(AsyncSSLSocketTest, LoadCertFromMemory) { using folly::ssl::OpenSSLUtils; auto cert = getFileAsBuf(kTestCert); auto key = getFileAsBuf(kTestKey); ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem())); BIO_write(certBio.get(), cert.data(), cert.size()); ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem())); BIO_write(keyBio.get(), key.data(), key.size()); // Create SSL structs from buffers to get properties ssl::X509UniquePtr certStruct( PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr)); ssl::EvpPkeyUniquePtr keyStruct( PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr)); certBio = nullptr; keyBio = nullptr; auto origCommonName = OpenSSLUtils::getCommonName(certStruct.get()); auto origKeySize = EVP_PKEY_bits(keyStruct.get()); certStruct = nullptr; keyStruct = nullptr; auto ctx = std::make_shared<SSLContext>(); ctx->loadPrivateKeyFromBufferPEM(key); ctx->loadCertificateFromBufferPEM(cert); ctx->loadTrustedCertificates(kTestCA); ssl::SSLUniquePtr ssl(ctx->createSSL()); auto newCert = SSL_get_certificate(ssl.get()); auto newKey = SSL_get_privatekey(ssl.get()); // Get properties from SSL struct auto newCommonName = OpenSSLUtils::getCommonName(newCert); auto newKeySize = EVP_PKEY_bits(newKey); // Check that the key and cert have the expected properties EXPECT_EQ(origCommonName, newCommonName); EXPECT_EQ(origKeySize, newKeySize); } TEST(AsyncSSLSocketTest, MinWriteSizeTest) { EventBase eb; // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // create SSL socket AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb)); EXPECT_EQ(1500, socket->getMinWriteSize()); socket->setMinWriteSize(0); EXPECT_EQ(0, socket->getMinWriteSize()); socket->setMinWriteSize(50000); EXPECT_EQ(50000, socket->getMinWriteSize()); } class ReadCallbackTerminator : public ReadCallback { public: ReadCallbackTerminator(EventBase* base, WriteCallbackBase* wcb) : ReadCallback(wcb), base_(base) {} // Do not write data back, terminate the loop. void readDataAvailable(size_t len) noexcept override { std::cerr << "readDataAvailable, len " << len << std::endl; currentBuffer.length = len; buffers.push_back(currentBuffer); currentBuffer.reset(); state = STATE_SUCCEEDED; socket_->setReadCB(nullptr); base_->terminateLoopSoon(); } private: EventBase* base_; }; /** * Test a full unencrypted codepath */ TEST(AsyncSSLSocketTest, UnencryptedTest) { EventBase base; auto clientCtx = std::make_shared<folly::SSLContext>(); auto serverCtx = std::make_shared<folly::SSLContext>(); NetworkSocket fds[2]; getfds(fds); getctx(clientCtx, serverCtx); auto client = AsyncSSLSocket::newSocket(clientCtx, &base, fds[0], false, true); auto server = AsyncSSLSocket::newSocket(serverCtx, &base, fds[1], true, true); ReadCallbackTerminator readCallback(&base, nullptr); server->setReadCB(&readCallback); readCallback.setSocket(server); uint8_t buf[128]; memset(buf, 'a', sizeof(buf)); client->write(nullptr, buf, sizeof(buf)); // Check that bytes are unencrypted char c; EXPECT_EQ(1, netops::recv(fds[1], &c, 1, MSG_PEEK)); EXPECT_EQ('a', c); EventBaseAborter eba(&base, 3000); base.loop(); EXPECT_EQ(1, readCallback.buffers.size()); EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState()); server->setReadCB(&readCallback); // Unencrypted server->sslAccept(nullptr); client->sslConn(nullptr); // Do NOT wait for handshake, writing should be queued and happen after client->write(nullptr, buf, sizeof(buf)); // Check that bytes are *not* unencrypted char c2; EXPECT_EQ(1, netops::recv(fds[1], &c2, 1, MSG_PEEK)); EXPECT_NE('a', c2); base.loop(); EXPECT_EQ(2, readCallback.buffers.size()); EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState()); } TEST(AsyncSSLSocketTest, ConnectUnencryptedTest) { auto clientCtx = std::make_shared<folly::SSLContext>(); auto serverCtx = std::make_shared<folly::SSLContext>(); getctx(clientCtx, serverCtx); WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); EventBase evb; std::shared_ptr<AsyncSSLSocket> socket = AsyncSSLSocket::newSocket(clientCtx, &evb, true); socket->connect(nullptr, server.getAddress(), 0); evb.loop(); EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, socket->getSSLState()); socket->sslConn(nullptr); evb.loop(); EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, socket->getSSLState()); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(nullptr, buf.data(), buf.size()); socket->close(); } /** * Test acceptrunner in various situations */ TEST(AsyncSSLSocketTest, SSLAcceptRunnerBasic) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); serverCtx->sslAcceptRunner(std::make_unique<SSLAcceptEvbRunner>(&eventBase)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_LE(0, client.handshakeTime.count()); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); EXPECT_LE(0, server.handshakeTime.count()); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptError) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptErrorRunner>(&eventBase)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_FALSE(client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptClose) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptCloseRunner>(&eventBase, serverSock.get())); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); EXPECT_FALSE(client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerAcceptDestroy) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptDestroyRunner>(&eventBase, &server)); eventBase.loop(); EXPECT_FALSE(client.handshakeSuccess_); EXPECT_TRUE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, SSLAcceptRunnerFiber) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); clientCtx->loadTrustedCertificates(kTestCA); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptFiberRunner>(&eventBase)); eventBase.loop(); EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_FALSE(server.handshakeError_); } static int newCloseCb(SSL* ssl, SSL_SESSION*) { AsyncSSLSocket::getFromSSL(ssl)->closeNow(); return 1; } #if FOLLY_OPENSSL_IS_110 static SSL_SESSION* getCloseCb(SSL* ssl, const unsigned char*, int, int*) { #else static SSL_SESSION* getCloseCb(SSL* ssl, unsigned char*, int, int*) { #endif AsyncSSLSocket::getFromSSL(ssl)->closeNow(); return nullptr; } // namespace folly TEST(AsyncSSLSocketTest, SSLAcceptRunnerFiberCloseSessionCb) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto serverCtx = std::make_shared<SSLContext>(); serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); SSL_CTX_set_session_cache_mode( serverCtx->getSSLCtx(), SSL_SESS_CACHE_NO_INTERNAL | SSL_SESS_CACHE_SERVER); SSL_CTX_sess_set_new_cb(serverCtx->getSSLCtx(), &newCloseCb); SSL_CTX_sess_set_get_cb(serverCtx->getSSLCtx(), &getCloseCb); serverCtx->sslAcceptRunner( std::make_unique<SSLAcceptFiberRunner>(&eventBase)); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY); clientCtx->ciphers("AES128-SHA256"); clientCtx->loadTrustedCertificates(kTestCA); clientCtx->setOptions(SSL_OP_NO_TICKET); NetworkSocket fds[2]; getfds(fds); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); SSLHandshakeClient client(std::move(clientSock), true, true); SSLHandshakeServer server(std::move(serverSock), true, true); eventBase.loop(); // As close() is called during session callbacks, client sees it as a // successful connection EXPECT_TRUE(client.handshakeSuccess_); EXPECT_FALSE(client.handshakeError_); EXPECT_FALSE(server.handshakeSuccess_); EXPECT_TRUE(server.handshakeError_); } TEST(AsyncSSLSocketTest, ConnResetErrorString) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr); socket->open(); uint8_t buf[3] = {0x16, 0x03, 0x01}; socket->write(buf, sizeof(buf)); socket->closeWithReset(); handshakeCallback.waitForHandshake(); EXPECT_NE( handshakeCallback.errorString_.find("Network error"), std::string::npos); EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos); } TEST(AsyncSSLSocketTest, ConnEOFErrorString) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr); socket->open(); uint8_t buf[3] = {0x16, 0x03, 0x01}; socket->write(buf, sizeof(buf)); socket->close(); handshakeCallback.waitForHandshake(); #if FOLLY_OPENSSL_IS_110 EXPECT_NE( handshakeCallback.errorString_.find("Network error"), std::string::npos); #else EXPECT_NE( handshakeCallback.errorString_.find("Connection EOF"), std::string::npos); #endif } TEST(AsyncSSLSocketTest, ConnOpenSSLErrorString) { // Start listening on a local port WriteCallbackBase writeCallback; WriteErrorCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr); socket->open(); uint8_t buf[256] = {0x16, 0x03}; memset(buf + 2, 'a', sizeof(buf) - 2); socket->write(buf, sizeof(buf)); socket->close(); handshakeCallback.waitForHandshake(); EXPECT_NE( handshakeCallback.errorString_.find("SSL routines"), std::string::npos); #if defined(OPENSSL_IS_BORINGSSL) EXPECT_NE( handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"), std::string::npos); #elif FOLLY_OPENSSL_IS_110 EXPECT_NE( handshakeCallback.errorString_.find("packet length too long"), std::string::npos); #else EXPECT_NE( handshakeCallback.errorString_.find("unknown protocol"), std::string::npos); #endif } TEST(AsyncSSLSocketTest, TestSSLCipherCodeToNameMap) { using folly::ssl::OpenSSLUtils; EXPECT_EQ( OpenSSLUtils::getCipherName(0xc02c), "ECDHE-ECDSA-AES256-GCM-SHA384"); // TLS_DHE_RSA_WITH_DES_CBC_SHA - We shouldn't be building with this EXPECT_EQ(OpenSSLUtils::getCipherName(0x0015), ""); // This indicates TLS_EMPTY_RENEGOTIATION_INFO_SCSV, no name expected EXPECT_EQ(OpenSSLUtils::getCipherName(0x00ff), ""); } #if defined __linux__ /** * Ensure TransparentTLS flag is disabled with AsyncSSLSocket */ TEST(AsyncSSLSocketTest, TTLSDisabled) { // clear all setsockopt tracking history globalStatic.reset(); // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, false); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); EXPECT_EQ(1, globalStatic.ttlsDisabledSet.count(socket->getNetworkSocket())); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // close() socket->close(); } #endif #if FOLLY_ALLOW_TFO class MockAsyncTFOSSLSocket : public AsyncSSLSocket { public: using UniquePtr = std::unique_ptr<MockAsyncTFOSSLSocket, Destructor>; explicit MockAsyncTFOSSLSocket( std::shared_ptr<folly::SSLContext> sslCtx, EventBase* evb) : AsyncSocket(evb), AsyncSSLSocket(sslCtx, evb) {} MOCK_METHOD3( tfoSendMsg, ssize_t(NetworkSocket fd, struct msghdr* msg, int msg_flags)); }; #if defined __linux__ /** * Ensure TransparentTLS flag is disabled with AsyncSSLSocket + TFO */ TEST(AsyncSSLSocketTest, TTLSDisabledWithTFO) { // clear all setsockopt tracking history globalStatic.reset(); // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); socket->open(); EXPECT_EQ(1, globalStatic.ttlsDisabledSet.count(socket->getNetworkSocket())); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // close() socket->close(); } #endif /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server with TFO. */ TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFO) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); socket->open(); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // read() std::array<uint8_t, 128> readbuf; uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0); // close() socket->close(); } /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server with TFO. */ TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOWithTFOServerDisabled) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, false); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); socket->open(); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); socket->write(buf.data(), buf.size()); // read() std::array<uint8_t, 128> readbuf; uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0); // close() socket->close(); } class ConnCallback : public AsyncSocket::ConnectCallback { public: void connectSuccess() noexcept override { state = State::SUCCESS; } void connectErr(const AsyncSocketException& ex) noexcept override { state = State::ERROR; error = ex.what(); } enum class State { WAITING, SUCCESS, ERROR }; State state{State::WAITING}; std::string error; }; template <class Cardinality> MockAsyncTFOSSLSocket::UniquePtr setupSocketWithFallback( EventBase* evb, const SocketAddress& address, Cardinality cardinality) { // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = MockAsyncTFOSSLSocket::UniquePtr( new MockAsyncTFOSSLSocket(sslContext, evb)); socket->enableTFO(); EXPECT_CALL(*socket, tfoSendMsg(_, _, _)) .Times(cardinality) .WillOnce(Invoke([&](NetworkSocket fd, struct msghdr*, int) { sockaddr_storage addr; auto len = address.getAddress(&addr); return netops::connect(fd, (const struct sockaddr*)&addr, len); })); return socket; } TEST(AsyncSSLSocketTest, ConnectWriteReadCloseTFOFallback) { // Start listening on a local port WriteCallbackBase writeCallback; ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); EventBase evb; auto socket = setupSocketWithFallback(&evb, server.getAddress(), 1); ConnCallback ccb; socket->connect(&ccb, server.getAddress(), 30); evb.loop(); EXPECT_EQ(ConnCallback::State::SUCCESS, ccb.state); evb.runInEventBaseThread([&] { socket->detachEventBase(); }); evb.loop(); BlockingSocket sock(std::move(socket)); // write() std::array<uint8_t, 128> buf; memset(buf.data(), 'a', buf.size()); sock.write(buf.data(), buf.size()); // read() std::array<uint8_t, 128> readbuf; uint32_t bytesRead = sock.readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, 128); EXPECT_EQ(memcmp(buf.data(), readbuf.data(), bytesRead), 0); // close() sock.close(); } #if !defined(OPENSSL_IS_BORINGSSL) TEST(AsyncSSLSocketTest, ConnectTFOTimeout) { // Start listening on a local port ConnectTimeoutCallback acceptCallback; TestSSLServer server(&acceptCallback, true); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->enableTFO(); EXPECT_THROW( socket->open(std::chrono::milliseconds(20)), AsyncSocketException); } #endif #if !defined(OPENSSL_IS_BORINGSSL) TEST(AsyncSSLSocketTest, ConnectTFOFallbackTimeout) { // Start listening on a local port ConnectTimeoutCallback acceptCallback; TestSSLServer server(&acceptCallback, true); EventBase evb; auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1)); ConnCallback ccb; // Set a short timeout socket->connect(&ccb, server.getAddress(), 1); evb.loop(); EXPECT_EQ(ConnCallback::State::ERROR, ccb.state); } #endif TEST(AsyncSSLSocketTest, HandshakeTFOFallbackTimeout) { // Start listening on a local port EmptyReadCallback readCallback; HandshakeCallback handshakeCallback( &readCallback, HandshakeCallback::EXPECT_ERROR); HandshakeTimeoutCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback, true); EventBase evb; auto socket = setupSocketWithFallback(&evb, server.getAddress(), AtMost(1)); ConnCallback ccb; socket->connect(&ccb, server.getAddress(), 100); evb.loop(); EXPECT_EQ(ConnCallback::State::ERROR, ccb.state); EXPECT_THAT(ccb.error, testing::HasSubstr("SSL connect timed out")); } TEST(AsyncSSLSocketTest, HandshakeTFORefused) { // Start listening on a local port EventBase evb; // Hopefully nothing is listening on this address SocketAddress addr("127.0.0.1", 65535); auto socket = setupSocketWithFallback(&evb, addr, AtMost(1)); ConnCallback ccb; socket->connect(&ccb, addr, 100); evb.loop(); EXPECT_EQ(ConnCallback::State::ERROR, ccb.state); EXPECT_THAT(ccb.error, testing::HasSubstr("refused")); } TEST(AsyncSSLSocketTest, TestPreReceivedData) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); std::array<NetworkSocket, 2> fds; getfds(fds.data()); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSockPtr( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSockPtr( new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true)); auto clientSock = clientSockPtr.get(); auto serverSock = serverSockPtr.get(); SSLHandshakeClient client(std::move(clientSockPtr), true, true); // Steal some data from the server. std::array<uint8_t, 10> buf; auto bytesReceived = netops::recv(fds[1], buf.data(), buf.size(), 0); checkUnixError(bytesReceived, "recv failed"); serverSock->setPreReceivedData( IOBuf::wrapBuffer(ByteRange(buf.data(), bytesReceived))); SSLHandshakeServer server(std::move(serverSockPtr), true, true); while (!client.handshakeSuccess_ && !client.handshakeError_) { eventBase.loopOnce(); } EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_EQ( serverSock->getRawBytesReceived(), clientSock->getRawBytesWritten()); } TEST(AsyncSSLSocketTest, TestMoveFromAsyncSocket) { EventBase eventBase; auto clientCtx = std::make_shared<SSLContext>(); auto dfServerCtx = std::make_shared<SSLContext>(); std::array<NetworkSocket, 2> fds; getfds(fds.data()); getctx(clientCtx, dfServerCtx); AsyncSSLSocket::UniquePtr clientSockPtr( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSocket::UniquePtr serverSockPtr(new AsyncSocket(&eventBase, fds[1])); auto clientSock = clientSockPtr.get(); auto serverSock = serverSockPtr.get(); SSLHandshakeClient client(std::move(clientSockPtr), true, true); // Steal some data from the server. std::array<uint8_t, 10> buf; auto bytesReceived = netops::recv(fds[1], buf.data(), buf.size(), 0); checkUnixError(bytesReceived, "recv failed"); serverSock->setPreReceivedData( IOBuf::wrapBuffer(ByteRange(buf.data(), bytesReceived))); AsyncSSLSocket::UniquePtr serverSSLSockPtr( new AsyncSSLSocket(dfServerCtx, std::move(serverSockPtr), true)); auto serverSSLSock = serverSSLSockPtr.get(); SSLHandshakeServer server(std::move(serverSSLSockPtr), true, true); while (!client.handshakeSuccess_ && !client.handshakeError_) { eventBase.loopOnce(); } EXPECT_TRUE(client.handshakeSuccess_); EXPECT_TRUE(server.handshakeSuccess_); EXPECT_EQ( serverSSLSock->getRawBytesReceived(), clientSock->getRawBytesWritten()); } /** * Test overriding the flags passed to "sendmsg()" system call, * and verifying that write requests fail properly. */ TEST(AsyncSSLSocketTest, SendMsgParamsCallback) { // Start listening on a local port SendMsgFlagsCallback msgCallback; ExpectWriteErrorCallback writeCallback(&msgCallback); ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // Setting flags to "-1" to trigger "Invalid argument" error // on attempt to use this flags in sendmsg() system call. msgCallback.resetFlags(-1); // write() std::vector<uint8_t> buf(128, 'a'); ASSERT_EQ(socket->write(buf.data(), buf.size()), buf.size()); // close() socket->close(); cerr << "SendMsgParamsCallback test completed" << endl; } #ifdef FOLLY_HAVE_MSG_ERRQUEUE /** * Test connecting to, writing to, reading from, and closing the * connection to the SSL server with ancillary data from the application. */ TEST(AsyncSSLSocketTest, SendMsgDataCallback) { // This test requires Linux kernel v4.6 or later struct utsname s_uname; memset(&s_uname, 0, sizeof(s_uname)); ASSERT_EQ(uname(&s_uname), 0); int major, minor; folly::StringPiece extra; if (folly::split<false>( '.', std::string(s_uname.release) + ".", major, minor, extra)) { if (major < 4 || (major == 4 && minor < 6)) { LOG(INFO) << "Kernel version: 4.6 and newer required for this test (" << "kernel ver. " << s_uname.release << " detected)."; return; } } // Start listening on a local port SendMsgAncillaryDataCallback msgCallback; WriteCheckTimestampCallback writeCallback(&msgCallback); ReadCallback readCallback(&writeCallback); HandshakeCallback handshakeCallback(&readCallback); SSLServerAcceptCallback acceptCallback(&handshakeCallback); TestSSLServer server(&acceptCallback); // Set up SSL context. auto sslContext = std::make_shared<SSLContext>(); sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH"); // connect auto socket = std::make_shared<BlockingSocket>(server.getAddress(), sslContext); socket->open(); // we'll pass the EOR and TIMESTAMP_TX flags with the write back // EOR tracking must be enabled for WriteFlags be passed const auto writeFlags = folly::WriteFlags::EOR | folly::WriteFlags::TIMESTAMP_TX; readCallback.setWriteFlags(writeFlags); msgCallback.setEorTracking(true); // Init ancillary data buffer to trigger timestamp notification // // We generate the same ancillary data regardless of the specific WriteFlags, // we verify that the WriteFlags are observed as expected below. union { uint8_t ctrl_data[CMSG_LEN(sizeof(uint32_t))]; struct cmsghdr cmsg; } u; u.cmsg.cmsg_level = SOL_SOCKET; u.cmsg.cmsg_type = SO_TIMESTAMPING; u.cmsg.cmsg_len = CMSG_LEN(sizeof(uint32_t)); uint32_t flags = SOF_TIMESTAMPING_TX_SCHED | SOF_TIMESTAMPING_TX_SOFTWARE | SOF_TIMESTAMPING_TX_ACK; memcpy(CMSG_DATA(&u.cmsg), &flags, sizeof(uint32_t)); std::vector<char> ctrl(CMSG_LEN(sizeof(uint32_t))); memcpy(ctrl.data(), u.ctrl_data, CMSG_LEN(sizeof(uint32_t))); msgCallback.resetData(std::move(ctrl)); // write(), including flags std::vector<uint8_t> buf(128, 'a'); socket->write(buf.data(), buf.size(), writeFlags); // read() std::vector<uint8_t> readbuf(buf.size()); uint32_t bytesRead = socket->readAll(readbuf.data(), readbuf.size()); EXPECT_EQ(bytesRead, buf.size()); EXPECT_TRUE(std::equal(buf.begin(), buf.end(), readbuf.begin())); // should receive three timestamps (schedule, TX/SND, ACK) // may take some time for all to arrive, so loop to wait // // socket error queue does not have the equivalent of an EOF, so we must // loop on it unless we want to use libevent for this test... const std::vector<int32_t> timestampsExpected = { SCM_TSTAMP_SCHED, SCM_TSTAMP_SND, SCM_TSTAMP_ACK}; std::vector<int32_t> timestampsReceived; while (timestampsExpected.size() != timestampsReceived.size()) { const auto timestamps = writeCallback.getTimestampNotifications(); timestampsReceived.insert( timestampsReceived.end(), timestamps.begin(), timestamps.end()); } EXPECT_THAT(timestampsReceived, ElementsAreArray(timestampsExpected)); // check the observed write flags EXPECT_EQ( static_cast<std::underlying_type<folly::WriteFlags>::type>( msgCallback.getObservedWriteFlags()), static_cast<std::underlying_type<folly::WriteFlags>::type>(writeFlags)); // close() socket->close(); cerr << "SendMsgDataCallback test completed" << endl; } #endif // FOLLY_HAVE_MSG_ERRQUEUE #endif TEST(AsyncSSLSocketTest, TestSNIClientHelloBehavior) { EventBase eventBase; auto serverCtx = std::make_shared<SSLContext>(); auto clientCtx = std::make_shared<SSLContext>(); serverCtx->loadPrivateKey(kTestKey); serverCtx->loadCertificate(kTestCert); clientCtx->setSessionCacheContext("test context"); clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY); SSL_SESSION* resumptionSession = nullptr; { std::array<NetworkSocket, 2> fds; getfds(fds.data()); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); // Client sends SNI that doesn't match anything the server cert advertises clientSock->setServerName("Foobar"); SSLHandshakeServerParseClientHello server( std::move(serverSock), true, true); SSLHandshakeClient client(std::move(clientSock), true, true); eventBase.loop(); serverSock = std::move(server).moveSocket(); auto chi = serverSock->getClientHelloInfo(); ASSERT_NE(chi, nullptr); EXPECT_EQ( std::string("Foobar"), std::string(serverSock->getSSLServerName())); // create another client, resuming with the prior session, but under a // different common name. clientSock = std::move(client).moveSocket(); resumptionSession = clientSock->getSSLSession(); } { std::array<NetworkSocket, 2> fds; getfds(fds.data()); AsyncSSLSocket::UniquePtr clientSock( new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false)); AsyncSSLSocket::UniquePtr serverSock( new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true)); clientSock->setSSLSession(resumptionSession, true); clientSock->setServerName("Baz"); SSLHandshakeServerParseClientHello server( std::move(serverSock), true, true); SSLHandshakeClient client(std::move(clientSock), true, true); eventBase.loop(); serverSock = std::move(server).moveSocket(); clientSock = std::move(client).moveSocket(); EXPECT_TRUE(clientSock->getSSLSessionReused()); // OpenSSL 1.1.1 changes the semantics of SSL_get_servername // in // https://github.com/openssl/openssl/commit/1c4aa31d79821dee9be98e915159d52cc30d8403 // // Previously, the SNI would be taken from the ClientHello. // Now, the SNI will be taken from the established session. // // But the session that was established with the client (prior handshake) // would not have set the server name field because the SNI that the client // requested ("Foobar") did not match any of the SANs that the server was // presenting ("127.0.0.1") // // To preserve this 1.1.0 behavior, getSSLServerName() should return the // parsed ClientHello servername. This test asserts this behavior. auto sni = serverSock->getSSLServerName(); ASSERT_NE(sni, nullptr); std::string sniStr(sni); EXPECT_EQ(sniStr, std::string("Baz")); } } } // namespace folly #ifdef SIGPIPE /////////////////////////////////////////////////////////////////////////// // init_unit_test_suite /////////////////////////////////////////////////////////////////////////// namespace { struct Initializer { Initializer() { signal(SIGPIPE, SIG_IGN); } }; Initializer initializer; } // namespace #endif
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_849_1
crossvul-cpp_data_good_1183_1
// This file is part of The New Aspell // Copyright (C) 2001 by Kevin Atkinson under the GNU LGPL license // version 2.0 or 2.1. You should have received a copy of the LGPL // license along with this library if you did not you can find // it at http://www.gnu.org/. #include "settings.h" //#include "iostream.hpp" #include "config.hpp" #include "file_util.hpp" #include "fstream.hpp" #include "errors.hpp" #include "string_list.hpp" #ifdef USE_FILE_LOCKS # include <fcntl.h> # include <unistd.h> # include <sys/types.h> #endif #include <stdio.h> #include <sys/stat.h> #include <dirent.h> #ifdef WIN32 # include <io.h> # define ACCESS _access # include <windows.h> # include <winbase.h> #else # include <unistd.h> # define ACCESS access #endif namespace acommon { // Return false if file is already an absolute path and does not need // a directory prepended. bool need_dir(ParmString file) { if (file[0] == '/' || (file[0] == '.' && file[1] == '/') #ifdef WIN32 || (asc_isalpha(file[0]) && file[1] == ':') || file[0] == '\\' || (file[0] == '.' && file[1] == '\\') #endif ) return false; else return true; } String add_possible_dir(ParmString dir, ParmString file) { if (need_dir(file)) { String path; path += dir; path += '/'; path += file; return path; } else { return file; } } String figure_out_dir(ParmString dir, ParmString file) { String temp; int s = file.size() - 1; while (s != -1 && file[s] != '/') --s; if (need_dir(file)) { temp += dir; temp += '/'; } if (s != -1) { temp.append(file, s); } return temp; } time_t get_modification_time(FStream & f) { struct stat s; fstat(f.file_no(), &s); return s.st_mtime; } PosibErr<void> open_file_readlock(FStream & in, ParmString file) { RET_ON_ERR(in.open(file, "r")); #ifdef USE_FILE_LOCKS int fd = in.file_no(); struct flock fl; fl.l_type = F_RDLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fcntl(fd, F_SETLKW, &fl); // ignore errors #endif return no_err; } PosibErr<bool> open_file_writelock(FStream & inout, ParmString file) { typedef PosibErr<bool> Ret; #ifndef USE_FILE_LOCKS bool exists = file_exists(file); #endif { Ret pe = inout.open(file, "r+"); if (pe.get_err() != 0) pe = inout.open(file, "w+"); if (pe.has_err()) return pe; } #ifdef USE_FILE_LOCKS int fd = inout.file_no(); struct flock fl; fl.l_type = F_WRLCK; fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; fcntl(fd, F_SETLKW, &fl); // ignore errors struct stat s; fstat(fd, &s); return s.st_size != 0; #else return exists; #endif } void truncate_file(FStream & f, ParmString name) { #ifdef USE_FILE_LOCKS f.restart(); ftruncate(f.file_no(),0); #else f.close(); f.open(name, "w+"); #endif } bool remove_file(ParmString name) { return remove(name) == 0; } bool file_exists(ParmString name) { return ACCESS(name, F_OK) == 0; } bool rename_file(ParmString orig_name, ParmString new_name) { remove(new_name); return rename(orig_name, new_name) == 0; } const char * get_file_name(const char * path) { const char * file_name; if (path != 0) { file_name = strrchr(path,'/'); if (file_name == 0) file_name = path; } else { file_name = 0; } return file_name; } unsigned find_file(const Config * config, const char * option, String & filename) { StringList sl; config->retrieve_list(option, &sl); return find_file(sl, filename); } unsigned find_file(const StringList & sl, String & filename) { StringListEnumeration els = sl.elements_obj(); const char * dir; String path; while ( (dir = els.next()) != 0 ) { path = dir; if (path.empty()) continue; if (path.back() != '/') path += '/'; unsigned dir_len = path.size(); path += filename; if (file_exists(path)) { filename.swap(path); return dir_len; } } return 0; } PathBrowser::PathBrowser(const StringList & sl, const char * suf) : dir_handle(0) { els = sl.elements(); suffix = suf; } PathBrowser::~PathBrowser() { delete els; if (dir_handle) closedir((DIR *)dir_handle); } const char * PathBrowser::next() { if (dir_handle == 0) goto get_next_dir; begin: { struct dirent * entry = readdir((DIR *)dir_handle); if (entry == 0) goto try_again; const char * name = entry->d_name; unsigned name_len = strlen(name); if (suffix.size() != 0 && !(name_len > suffix.size() && memcmp(name + name_len - suffix.size(), suffix.str(), suffix.size()) == 0)) goto begin; path = dir; if (path.back() != '/') path += '/'; path += name; } return path.str(); try_again: if (dir_handle) closedir((DIR *)dir_handle); dir_handle = 0; get_next_dir: dir = els->next(); if (!dir) return 0; dir_handle = opendir(dir); if (dir_handle == 0) goto try_again; goto begin; } }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_1183_1
crossvul-cpp_data_bad_611_1
/* * Load_stp.cpp * ------------ * Purpose: STP (Soundtracker Pro II) module loader * Notes : A few exotic effects aren't supported. * Multiple sample loops are supported, but only the first 10 can be used as cue points * (with 16xx and 18xx). * Fractional speed values and combined auto effects are handled whenever possible, * but some effects may be omitted (and there may be tempo accuracy issues). * Authors: Devin Acker * OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. * * Wisdom from the Soundtracker Pro II manual: * "To create shorter patterns, simply create shorter patterns." */ #include "stdafx.h" #include "Loaders.h" OPENMPT_NAMESPACE_BEGIN // File header (except for "STP3" magic) struct STPFileHeader { char magic[4]; uint16be version; uint8be numOrders; uint8be patternLength; uint8be orderList[128]; uint16be speed; uint16be speedFrac; uint16be timerCount; uint16be flags; uint32be reserved; uint16be midiCount; // always 50 uint8be midi[50]; uint16be numSamples; uint16be sampleStructSize; }; MPT_BINARY_STRUCT(STPFileHeader, 204) // Sample header (common part between all versions) struct STPSampleHeader { uint32be length; uint8be volume; uint8be reserved1; uint32be loopStart; uint32be loopLength; uint16be defaultCommand; // Default command to put next to note when editing patterns; not relevant for playback // The following 4 bytes are reserved in version 0 and 1. uint16be defaultPeriod; uint8be finetune; uint8be reserved2; void ConvertToMPT(ModSample &mptSmp) const { mptSmp.nLength = length; mptSmp.nVolume = 4u * std::min<uint16>(volume, 64); mptSmp.nLoopStart = loopStart; mptSmp.nLoopEnd = loopStart + loopLength; if(mptSmp.nLoopStart >= mptSmp.nLength) { mptSmp.nLoopStart = mptSmp.nLength - 1; } if(mptSmp.nLoopEnd > mptSmp.nLength) { mptSmp.nLoopEnd = mptSmp.nLength; } if(mptSmp.nLoopStart > mptSmp.nLoopEnd) { mptSmp.nLoopStart = 0; mptSmp.nLoopEnd = 0; } else if(mptSmp.nLoopEnd > mptSmp.nLoopStart) { mptSmp.uFlags.set(CHN_LOOP); mptSmp.cues[0] = mptSmp.nLoopStart; } } }; MPT_BINARY_STRUCT(STPSampleHeader, 20) struct STPLoopInfo { SmpLength loopStart; SmpLength loopLength; SAMPLEINDEX looped; SAMPLEINDEX nonLooped; }; typedef std::vector<STPLoopInfo> STPLoopList; static TEMPO ConvertTempo(uint16 ciaSpeed) { // 3546 is the resulting CIA timer value when using 4F7D (tempo 125 bpm) command in STProII return TEMPO((125.0 * 3546.0) / ciaSpeed); } static void ConvertLoopSlice(ModSample &src, ModSample &dest, SmpLength start, SmpLength len, bool loop) { if(!src.HasSampleData()) return; dest.FreeSample(); dest = src; dest.nLength = len; dest.pSample = nullptr; if(!dest.AllocateSample()) { return; } // only preserve cue points if the target sample length is the same if(len != src.nLength) MemsetZero(dest.cues); std::memcpy(dest.pSample8, src.pSample8 + start, len); dest.uFlags.set(CHN_LOOP, loop); if(loop) { dest.nLoopStart = 0; dest.nLoopEnd = len; } else { dest.nLoopStart = 0; dest.nLoopEnd = 0; } } static void ConvertLoopSequence(ModSample &smp, STPLoopList &loopList) { // This should only modify a sample if it has more than one loop // (otherwise, it behaves like a normal sample loop) if(!smp.HasSampleData() || loopList.size() < 2) return; ModSample newSmp = smp; newSmp.nLength = 0; newSmp.pSample = nullptr; size_t numLoops = loopList.size(); // get the total length of the sample after combining all looped sections for(size_t i = 0; i < numLoops; i++) { STPLoopInfo &info = loopList[i]; // if adding this loop would cause the sample length to exceed maximum, // then limit and bail out if((newSmp.nLength + info.loopLength > MAX_SAMPLE_LENGTH) || (info.loopLength > MAX_SAMPLE_LENGTH) || (info.loopStart + info.loopLength > smp.nLength)) { numLoops = i; break; } newSmp.nLength += info.loopLength; } if(!newSmp.AllocateSample()) { return; } // start copying the looped sample data parts SmpLength start = 0; for(size_t i = 0; i < numLoops; i++) { STPLoopInfo &info = loopList[i]; memcpy(newSmp.pSample8 + start, smp.pSample8 + info.loopStart, info.loopLength); // update loop info based on position in edited sample info.loopStart = start; if(i > 0 && i <= mpt::size(newSmp.cues)) { newSmp.cues[i - 1] = start; } start += info.loopLength; } // replace old sample with new one smp.FreeSample(); smp = newSmp; smp.nLoopStart = 0; smp.nLoopEnd = smp.nLength; smp.uFlags.set(CHN_LOOP); } static bool ValidateHeader(const STPFileHeader &fileHeader) { if(std::memcmp(fileHeader.magic, "STP3", 4) || fileHeader.version > 2 || fileHeader.numOrders > 128 || fileHeader.numSamples >= MAX_SAMPLES || fileHeader.timerCount == 0 || fileHeader.midiCount != 50) { return false; } return true; } CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderSTP(MemoryFileReader file, const uint64 *pfilesize) { STPFileHeader fileHeader; if(!file.ReadStruct(fileHeader)) { return ProbeWantMoreData; } if(!ValidateHeader(fileHeader)) { return ProbeFailure; } MPT_UNREFERENCED_PARAMETER(pfilesize); return ProbeSuccess; } bool CSoundFile::ReadSTP(FileReader &file, ModLoadingFlags loadFlags) { file.Rewind(); STPFileHeader fileHeader; if(!file.ReadStruct(fileHeader)) { return false; } if(!ValidateHeader(fileHeader)) { return false; } if(loadFlags == onlyVerifyHeader) { return true; } InitializeGlobals(MOD_TYPE_STP); m_nChannels = 4; m_nSamples = 0; m_nDefaultSpeed = fileHeader.speed; m_nDefaultTempo = ConvertTempo(fileHeader.timerCount); m_nMinPeriod = 14 * 4; m_nMaxPeriod = 3424 * 4; ReadOrderFromArray(Order(), fileHeader.orderList, fileHeader.numOrders); std::vector<STPLoopList> loopInfo; // non-looped versions of samples with loops (when needed) std::vector<SAMPLEINDEX> nonLooped; // Load sample headers SAMPLEINDEX samplesInFile = 0; for(SAMPLEINDEX smp = 0; smp < fileHeader.numSamples; smp++) { SAMPLEINDEX actualSmp = file.ReadUint16BE(); if(actualSmp == 0 || actualSmp >= MAX_SAMPLES) return false; uint32 chunkSize = fileHeader.sampleStructSize; if(fileHeader.version == 2) chunkSize = file.ReadUint32BE() - 2; FileReader chunk = file.ReadChunk(chunkSize); samplesInFile = m_nSamples = std::max(m_nSamples, actualSmp); ModSample &mptSmp = Samples[actualSmp]; mptSmp.Initialize(MOD_TYPE_MOD); if(fileHeader.version < 2) { // Read path chunk.ReadString<mpt::String::maybeNullTerminated>(mptSmp.filename, 31); // Ignore flags, they are all not relevant for us chunk.Skip(1); // Read filename / sample text chunk.ReadString<mpt::String::maybeNullTerminated>(m_szNames[actualSmp], 30); } else { std::string str; // Read path chunk.ReadNullString(str, 257); mpt::String::Copy(mptSmp.filename, str); // Ignore flags, they are all not relevant for us chunk.Skip(1); // Read filename / sample text chunk.ReadNullString(str, 31); mpt::String::Copy(m_szNames[actualSmp], str); // Seek to even boundary if(chunk.GetPosition() % 2u) chunk.Skip(1); } STPSampleHeader sampleHeader; chunk.ReadStruct(sampleHeader); sampleHeader.ConvertToMPT(mptSmp); if(fileHeader.version == 2) { mptSmp.nFineTune = static_cast<int8>(sampleHeader.finetune << 3); } if(fileHeader.version >= 1) { nonLooped.resize(samplesInFile); loopInfo.resize(samplesInFile); STPLoopList &loopList = loopInfo[actualSmp - 1]; loopList.clear(); uint16 numLoops = file.ReadUint16BE(); loopList.reserve(numLoops); STPLoopInfo loop; loop.looped = loop.nonLooped = 0; if(numLoops == 0 && mptSmp.uFlags[CHN_LOOP]) { loop.loopStart = mptSmp.nLoopStart; loop.loopLength = mptSmp.nLoopEnd - mptSmp.nLoopStart; loopList.push_back(loop); } else for(uint16 i = 0; i < numLoops; i++) { loop.loopStart = file.ReadUint32BE(); loop.loopLength = file.ReadUint32BE(); loopList.push_back(loop); } } } // Load patterns uint16 numPatterns = 128; if(fileHeader.version == 0) numPatterns = file.ReadUint16BE(); uint16 patternLength = fileHeader.patternLength; CHANNELINDEX channels = 4; if(fileHeader.version > 0) { // Scan for total number of channels FileReader::off_t patOffset = file.GetPosition(); for(uint16 pat = 0; pat < numPatterns; pat++) { PATTERNINDEX actualPat = file.ReadUint16BE(); if(actualPat == 0xFFFF) break; patternLength = file.ReadUint16BE(); channels = file.ReadUint16BE(); m_nChannels = std::max(m_nChannels, channels); file.Skip(channels * patternLength * 4u); } file.Seek(patOffset); if(m_nChannels > MAX_BASECHANNELS) return false; } struct ChannelMemory { uint8 autoFinePorta, autoPortaUp, autoPortaDown, autoVolSlide, autoVibrato; uint8 vibratoMem, autoTremolo, autoTonePorta, tonePortaMem; }; std::vector<ChannelMemory> channelMemory(m_nChannels); uint8 globalVolSlide = 0; for(uint16 pat = 0; pat < numPatterns; pat++) { PATTERNINDEX actualPat = pat; if(fileHeader.version > 0) { actualPat = file.ReadUint16BE(); if(actualPat == 0xFFFF) break; patternLength = file.ReadUint16BE(); channels = file.ReadUint16BE(); } if(!(loadFlags & loadPatternData) || !Patterns.Insert(actualPat, patternLength)) { file.Skip(channels * patternLength * 4u); continue; } for(ROWINDEX row = 0; row < patternLength; row++) { auto rowBase = Patterns[actualPat].GetRow(row); bool didGlobalVolSlide = false; // if a fractional speed value is in use then determine if we should stick a fine pattern delay somewhere bool shouldDelay; switch(fileHeader.speedFrac & 3) { default: shouldDelay = false; break; // 1/4 case 1: shouldDelay = (row & 3) == 0; break; // 1/2 case 2: shouldDelay = (row & 1) == 0; break; // 3/4 case 3: shouldDelay = (row & 3) != 3; break; } for(CHANNELINDEX chn = 0; chn < channels; chn++) { ChannelMemory &chnMem = channelMemory[chn]; ModCommand &m = rowBase[chn]; uint8 data[4]; file.ReadArray(data); m.instr = data[0]; m.note = data[1]; m.command = data[2]; m.param = data[3]; if(m.note) { m.note += 24 + NOTE_MIN; chnMem = ChannelMemory(); } // this is a nibble-swapped param value used for auto fine volside // and auto global fine volside uint8 swapped = (m.param >> 4) | (m.param << 4); if((m.command & 0xF0) == 0xF0) { // 12-bit CIA tempo uint16 ciaTempo = (static_cast<uint16>(m.command & 0x0F) << 8) | m.param; if(ciaTempo) { m.param = mpt::saturate_cast<ModCommand::PARAM>(Util::Round(ConvertTempo(ciaTempo).ToDouble())); m.command = CMD_TEMPO; } else { m.command = CMD_NONE; } } else switch(m.command) { case 0x00: // arpeggio if(m.param) m.command = CMD_ARPEGGIO; break; case 0x01: // portamento up m.command = CMD_PORTAMENTOUP; break; case 0x02: // portamento down m.command = CMD_PORTAMENTODOWN; break; case 0x03: // auto fine portamento up chnMem.autoFinePorta = 0x10 | std::min(m.param, ModCommand::PARAM(15)); chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x04: // auto fine portamento down chnMem.autoFinePorta = 0x20 | std::min(m.param, ModCommand::PARAM(15)); chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x05: // auto portamento up chnMem.autoFinePorta = 0; chnMem.autoPortaUp = m.param; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x06: // auto portamento down chnMem.autoFinePorta = 0; chnMem.autoPortaUp = 0; chnMem.autoPortaDown = m.param; chnMem.autoTonePorta = 0; m.command = m.param = 0; break; case 0x07: // set global volume m.command = CMD_GLOBALVOLUME; globalVolSlide = 0; break; case 0x08: // auto global fine volume slide globalVolSlide = swapped; m.command = m.param = 0; break; case 0x09: // fine portamento up m.command = CMD_MODCMDEX; m.param = 0x10 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x0A: // fine portamento down m.command = CMD_MODCMDEX; m.param = 0x20 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x0B: // auto fine volume slide chnMem.autoVolSlide = swapped; m.command = m.param = 0; break; case 0x0C: // set volume m.volcmd = VOLCMD_VOLUME; m.vol = m.param; chnMem.autoVolSlide = 0; m.command = m.param = 0; break; case 0x0D: // volume slide (param is swapped compared to .mod) if(m.param & 0xF0) { m.volcmd = VOLCMD_VOLSLIDEDOWN; m.vol = m.param >> 4; } else if(m.param & 0x0F) { m.volcmd = VOLCMD_VOLSLIDEUP; m.vol = m.param & 0xF; } chnMem.autoVolSlide = 0; m.command = m.param = 0; break; case 0x0E: // set filter (also uses opposite value compared to .mod) m.command = CMD_MODCMDEX; m.param = 1 ^ (m.param ? 1 : 0); break; case 0x0F: // set speed m.command = CMD_SPEED; fileHeader.speedFrac = m.param & 0xF; m.param >>= 4; break; case 0x10: // auto vibrato chnMem.autoVibrato = m.param; chnMem.vibratoMem = 0; m.command = m.param = 0; break; case 0x11: // auto tremolo if(m.param & 0xF) chnMem.autoTremolo = m.param; else chnMem.autoTremolo = 0; m.command = m.param = 0; break; case 0x12: // pattern break m.command = CMD_PATTERNBREAK; break; case 0x13: // auto tone portamento chnMem.autoFinePorta = 0; chnMem.autoPortaUp = 0; chnMem.autoPortaDown = 0; chnMem.autoTonePorta = m.param; chnMem.tonePortaMem = 0; m.command = m.param = 0; break; case 0x14: // position jump m.command = CMD_POSITIONJUMP; break; case 0x16: // start loop sequence if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < std::min(mpt::size(ModSample().cues), loopList.size())) { m.volcmd = VOLCMD_OFFSET; m.vol = m.param; } } m.command = m.param = 0; break; case 0x17: // play only loop nn if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < loopList.size()) { if(!loopList[m.param].looped && m_nSamples < MAX_SAMPLES - 1) loopList[m.param].looped = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].looped); } } m.command = m.param = 0; break; case 0x18: // play sequence without loop if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < std::min(mpt::size(ModSample().cues), loopList.size())) { m.volcmd = VOLCMD_OFFSET; m.vol = m.param; } // switch to non-looped version of sample and create it if needed if(!nonLooped[m.instr - 1] && m_nSamples < MAX_SAMPLES - 1) nonLooped[m.instr - 1] = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(nonLooped[m.instr - 1]); } m.command = m.param = 0; break; case 0x19: // play only loop nn without loop if(m.instr && m.instr <= loopInfo.size()) { STPLoopList &loopList = loopInfo[m.instr - 1]; m.param--; if(m.param < loopList.size()) { if(!loopList[m.param].nonLooped && m_nSamples < MAX_SAMPLES-1) loopList[m.param].nonLooped = ++m_nSamples; m.instr = static_cast<ModCommand::INSTR>(loopList[m.param].nonLooped); } } m.command = m.param = 0; break; case 0x1D: // fine volume slide (nibble order also swapped) m.command = CMD_VOLUMESLIDE; m.param = swapped; if(m.param & 0xF0) // slide down m.param |= 0x0F; else if(m.param & 0x0F) m.param |= 0xF0; break; case 0x20: // "delayed fade" // just behave like either a normal fade or a notecut // depending on the speed if(m.param & 0xF0) { chnMem.autoVolSlide = m.param >> 4; m.command = m.param = 0; } else { m.command = CMD_MODCMDEX; m.param = 0xC0 | (m.param & 0xF); } break; case 0x21: // note delay m.command = CMD_MODCMDEX; m.param = 0xD0 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x22: // retrigger note m.command = CMD_MODCMDEX; m.param = 0x90 | std::min(m.param, ModCommand::PARAM(15)); break; case 0x49: // set sample offset m.command = CMD_OFFSET; break; case 0x4E: // other protracker commands (pattern loop / delay) if((m.param & 0xF0) == 0x60 || (m.param & 0xF0) == 0xE0) m.command = CMD_MODCMDEX; else m.command = m.param = 0; break; case 0x4F: // set speed/tempo if(m.param < 0x20) { m.command = CMD_SPEED; fileHeader.speedFrac = 0; } else { m.command = CMD_TEMPO; } break; default: m.command = CMD_NONE; break; } bool didVolSlide = false; // try to put volume slide in volume command if(chnMem.autoVolSlide && !m.volcmd) { if(chnMem.autoVolSlide & 0xF0) { m.volcmd = VOLCMD_FINEVOLUP; m.vol = chnMem.autoVolSlide >> 4; } else { m.volcmd = VOLCMD_FINEVOLDOWN; m.vol = chnMem.autoVolSlide & 0xF; } didVolSlide = true; } // try to place/combine all remaining running effects. if(m.command == CMD_NONE) { if(chnMem.autoPortaUp) { m.command = CMD_PORTAMENTOUP; m.param = chnMem.autoPortaUp; } else if(chnMem.autoPortaDown) { m.command = CMD_PORTAMENTODOWN; m.param = chnMem.autoPortaDown; } else if(chnMem.autoFinePorta) { m.command = CMD_MODCMDEX; m.param = chnMem.autoFinePorta; } else if(chnMem.autoTonePorta) { m.command = CMD_TONEPORTAMENTO; m.param = chnMem.tonePortaMem = chnMem.autoTonePorta; } else if(chnMem.autoVibrato) { m.command = CMD_VIBRATO; m.param = chnMem.vibratoMem = chnMem.autoVibrato; } else if(!didVolSlide && chnMem.autoVolSlide) { m.command = CMD_VOLUMESLIDE; m.param = chnMem.autoVolSlide; // convert to a "fine" value by setting the other nibble to 0xF if(m.param & 0x0F) m.param |= 0xF0; else if(m.param & 0xF0) m.param |= 0x0F; didVolSlide = true; } else if(chnMem.autoTremolo) { m.command = CMD_TREMOLO; m.param = chnMem.autoTremolo; } else if(shouldDelay) { // insert a fine pattern delay here m.command = CMD_S3MCMDEX; m.param = 0x61; shouldDelay = false; } else if(!didGlobalVolSlide && globalVolSlide) { m.command = CMD_GLOBALVOLSLIDE; m.param = globalVolSlide; // convert to a "fine" value by setting the other nibble to 0xF if(m.param & 0x0F) m.param |= 0xF0; else if(m.param & 0xF0) m.param |= 0x0F; didGlobalVolSlide = true; } } } // TODO: create/use extra channels for global volslide/delay if needed } } // after we know how many channels there really are... m_nSamplePreAmp = 256 / m_nChannels; // Setup channel pan positions and volume SetupMODPanning(true); // Skip over scripts and drumpad info if(fileHeader.version > 0) { while(file.CanRead(2)) { uint16 scriptNum = file.ReadUint16BE(); if(scriptNum == 0xFFFF) break; file.Skip(2); uint32 length = file.ReadUint32BE(); file.Skip(length); } // Skip drumpad stuff file.Skip(17 * 2); } // Reading samples if(loadFlags & loadSampleData) { for(SAMPLEINDEX smp = 1; smp <= samplesInFile; smp++) if(Samples[smp].nLength) { SampleIO( SampleIO::_8bit, SampleIO::mono, SampleIO::littleEndian, SampleIO::signedPCM) .ReadSample(Samples[smp], file); if(smp > loopInfo.size()) continue; ConvertLoopSequence(Samples[smp], loopInfo[smp - 1]); // make a non-looping duplicate of this sample if needed if(nonLooped[smp - 1]) { ConvertLoopSlice(Samples[smp], Samples[nonLooped[smp - 1]], 0, Samples[smp].nLength, false); } for(const auto &info : loopInfo[smp - 1]) { // make duplicate samples for this individual section if needed if(info.looped) { ConvertLoopSlice(Samples[smp], Samples[info.looped], info.loopStart, info.loopLength, true); } if(info.nonLooped) { ConvertLoopSlice(Samples[smp], Samples[info.nonLooped], info.loopStart, info.loopLength, false); } } } } return true; } OPENMPT_NAMESPACE_END
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_611_1
crossvul-cpp_data_good_94_1
/* Library for accessing X3F Files ---------------------------------------------------------------- BSD-style License ---------------------------------------------------------------- * Copyright (c) 2010, Roland Karlsson (roland@proxel.se) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the organization nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY ROLAND KARLSSON ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL ROLAND KARLSSON BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* From X3F_IO.H */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include <stdio.h> #include "../libraw/libraw_datastream.h" #define SIZE_UNIQUE_IDENTIFIER 16 #define SIZE_WHITE_BALANCE 32 #define SIZE_COLOR_MODE 32 #define NUM_EXT_DATA_2_1 32 #define NUM_EXT_DATA_3_0 64 #define NUM_EXT_DATA NUM_EXT_DATA_3_0 #define X3F_VERSION(MAJ,MIN) (uint32_t)(((MAJ)<<16) + MIN) #define X3F_VERSION_2_0 X3F_VERSION(2,0) #define X3F_VERSION_2_1 X3F_VERSION(2,1) #define X3F_VERSION_2_2 X3F_VERSION(2,2) #define X3F_VERSION_2_3 X3F_VERSION(2,3) #define X3F_VERSION_3_0 X3F_VERSION(3,0) #define X3F_VERSION_4_0 X3F_VERSION(4,0) /* Main file identifier */ #define X3F_FOVb (uint32_t)(0x62564f46) /* Directory identifier */ #define X3F_SECd (uint32_t)(0x64434553) /* Property section identifiers */ #define X3F_PROP (uint32_t)(0x504f5250) #define X3F_SECp (uint32_t)(0x70434553) /* Image section identifiers */ #define X3F_IMAG (uint32_t)(0x46414d49) #define X3F_IMA2 (uint32_t)(0x32414d49) #define X3F_SECi (uint32_t)(0x69434553) /* CAMF section identifiers */ #define X3F_CAMF (uint32_t)(0x464d4143) #define X3F_SECc (uint32_t)(0x63434553) /* CAMF entry identifiers */ #define X3F_CMbP (uint32_t)(0x50624d43) #define X3F_CMbT (uint32_t)(0x54624d43) #define X3F_CMbM (uint32_t)(0x4d624d43) #define X3F_CMb (uint32_t)(0x00624d43) /* SDQ section identifiers ? - TODO */ #define X3F_SPPA (uint32_t)(0x41505053) #define X3F_SECs (uint32_t)(0x73434553) #define X3F_IMAGE_THUMB_PLAIN (uint32_t)(0x00020003) #define X3F_IMAGE_THUMB_HUFFMAN (uint32_t)(0x0002000b) #define X3F_IMAGE_THUMB_JPEG (uint32_t)(0x00020012) #define X3F_IMAGE_THUMB_SDQ (uint32_t)(0x00020019) /* SDQ ? - TODO */ #define X3F_IMAGE_RAW_HUFFMAN_X530 (uint32_t)(0x00030005) #define X3F_IMAGE_RAW_HUFFMAN_10BIT (uint32_t)(0x00030006) #define X3F_IMAGE_RAW_TRUE (uint32_t)(0x0003001e) #define X3F_IMAGE_RAW_MERRILL (uint32_t)(0x0001001e) #define X3F_IMAGE_RAW_QUATTRO (uint32_t)(0x00010023) #define X3F_IMAGE_RAW_SDQ (uint32_t)(0x00010025) #define X3F_IMAGE_RAW_SDQH (uint32_t)(0x00010027) #define X3F_IMAGE_RAW_SDQH2 (uint32_t)(0x00010029) #define X3F_IMAGE_HEADER_SIZE 28 #define X3F_CAMF_HEADER_SIZE 28 #define X3F_PROPERTY_LIST_HEADER_SIZE 24 typedef uint16_t utf16_t; typedef int bool_t; typedef enum x3f_extended_types_e { X3F_EXT_TYPE_NONE=0, X3F_EXT_TYPE_EXPOSURE_ADJUST=1, X3F_EXT_TYPE_CONTRAST_ADJUST=2, X3F_EXT_TYPE_SHADOW_ADJUST=3, X3F_EXT_TYPE_HIGHLIGHT_ADJUST=4, X3F_EXT_TYPE_SATURATION_ADJUST=5, X3F_EXT_TYPE_SHARPNESS_ADJUST=6, X3F_EXT_TYPE_RED_ADJUST=7, X3F_EXT_TYPE_GREEN_ADJUST=8, X3F_EXT_TYPE_BLUE_ADJUST=9, X3F_EXT_TYPE_FILL_LIGHT_ADJUST=10 } x3f_extended_types_t; typedef struct x3f_property_s { /* Read from file */ uint32_t name_offset; uint32_t value_offset; /* Computed */ utf16_t *name; /* 0x0000 terminated UTF 16 */ utf16_t *value; /* 0x0000 terminated UTF 16 */ } x3f_property_t; typedef struct x3f_property_table_s { uint32_t size; x3f_property_t *element; } x3f_property_table_t; typedef struct x3f_property_list_s { /* 2.0 Fields */ uint32_t num_properties; uint32_t character_format; uint32_t reserved; uint32_t total_length; x3f_property_table_t property_table; void *data; uint32_t data_size; } x3f_property_list_t; typedef struct x3f_table8_s { uint32_t size; uint8_t *element; } x3f_table8_t; typedef struct x3f_table16_s { uint32_t size; uint16_t *element; } x3f_table16_t; typedef struct x3f_table32_s { uint32_t size; uint32_t *element; } x3f_table32_t; typedef struct { uint8_t *data; /* Pointer to actual image data */ void *buf; /* Pointer to allocated buffer for free() */ uint32_t rows; uint32_t columns; uint32_t channels; uint32_t row_stride; } x3f_area8_t; typedef struct { uint16_t *data; /* Pointer to actual image data */ void *buf; /* Pointer to allocated buffer for free() */ uint32_t rows; uint32_t columns; uint32_t channels; uint32_t row_stride; } x3f_area16_t; #define UNDEFINED_LEAF 0xffffffff typedef struct x3f_huffnode_s { struct x3f_huffnode_s *branch[2]; uint32_t leaf; } x3f_huffnode_t; typedef struct x3f_hufftree_s { uint32_t free_node_index; /* Free node index in huffman tree array */ x3f_huffnode_t *nodes; /* Coding tree */ } x3f_hufftree_t; typedef struct x3f_true_huffman_element_s { uint8_t code_size; uint8_t code; } x3f_true_huffman_element_t; typedef struct x3f_true_huffman_s { uint32_t size; x3f_true_huffman_element_t *element; } x3f_true_huffman_t; /* 0=bottom, 1=middle, 2=top */ #define TRUE_PLANES 3 typedef struct x3f_true_s { uint16_t seed[TRUE_PLANES]; /* Always 512,512,512 */ uint16_t unknown; /* Always 0 */ x3f_true_huffman_t table; /* Huffman table - zero terminated. size is the number of leaves plus 1.*/ x3f_table32_t plane_size; /* Size of the 3 planes */ uint8_t *plane_address[TRUE_PLANES]; /* computed offset to the planes */ x3f_hufftree_t tree; /* Coding tree */ x3f_area16_t x3rgb16; /* 3x16 bit X3-RGB data */ } x3f_true_t; typedef struct x3f_quattro_s { struct { uint16_t columns; uint16_t rows; } plane[TRUE_PLANES]; uint32_t unknown; bool_t quattro_layout; x3f_area16_t top16; /* Container for the bigger top layer */ } x3f_quattro_t; typedef struct x3f_huffman_s { x3f_table16_t mapping; /* Value Mapping = X3F lossy compression */ x3f_table32_t table; /* Coding Table */ x3f_hufftree_t tree; /* Coding tree */ x3f_table32_t row_offsets; /* Row offsets */ x3f_area8_t rgb8; /* 3x8 bit RGB data */ x3f_area16_t x3rgb16; /* 3x16 bit X3-RGB data */ } x3f_huffman_t; typedef struct x3f_image_data_s { /* 2.0 Fields */ /* ------------------------------------------------------------------ */ /* Known combinations of type and format are: 1-6, 2-3, 2-11, 2-18, 3-6 */ uint32_t type; /* 1 = RAW X3 (SD1) 2 = thumbnail or maybe just RGB 3 = RAW X3 */ uint32_t format; /* 3 = 3x8 bit pixmap 6 = 3x10 bit huffman with map table 11 = 3x8 bit huffman 18 = JPEG */ uint32_t type_format; /* type<<16 + format */ /* ------------------------------------------------------------------ */ uint32_t columns; /* width / row size in pixels */ uint32_t rows; /* height */ uint32_t row_stride; /* row size in bytes */ /* NULL if not used */ x3f_huffman_t *huffman; /* Huffman help data */ x3f_true_t *tru; /* TRUE help data */ x3f_quattro_t *quattro; /* Quattro help data */ void *data; /* Take from file if NULL. Otherwise, this is the actual data bytes in the file. */ uint32_t data_size; } x3f_image_data_t; typedef struct camf_dim_entry_s { uint32_t size; uint32_t name_offset; uint32_t n; /* 0,1,2,3... */ char *name; } camf_dim_entry_t; typedef enum {M_FLOAT, M_INT, M_UINT} matrix_type_t; typedef struct camf_entry_s { /* pointer into decoded data */ void *entry; /* entry header */ uint32_t id; uint32_t version; uint32_t entry_size; uint32_t name_offset; uint32_t value_offset; /* computed values */ char *name_address; void *value_address; uint32_t name_size; uint32_t value_size; /* extracted values for explicit CAMF entry types*/ uint32_t text_size; char *text; uint32_t property_num; char **property_name; uint8_t **property_value; uint32_t matrix_dim; camf_dim_entry_t *matrix_dim_entry; /* Offset, pointer and size and type of raw data */ uint32_t matrix_type; uint32_t matrix_data_off; void *matrix_data; uint32_t matrix_element_size; /* Pointer and type of copied data */ matrix_type_t matrix_decoded_type; void *matrix_decoded; /* Help data to try to estimate element size */ uint32_t matrix_elements; uint32_t matrix_used_space; double matrix_estimated_element_size; } camf_entry_t; typedef struct camf_entry_table_s { uint32_t size; camf_entry_t *element; } camf_entry_table_t; typedef struct x3f_camf_typeN_s { uint32_t val0; uint32_t val1; uint32_t val2; uint32_t val3; } x3f_camf_typeN_t; typedef struct x3f_camf_type2_s { uint32_t reserved; uint32_t infotype; uint32_t infotype_version; uint32_t crypt_key; } x3f_camf_type2_t; typedef struct x3f_camf_type4_s { uint32_t decoded_data_size; uint32_t decode_bias; uint32_t block_size; uint32_t block_count; } x3f_camf_type4_t; typedef struct x3f_camf_type5_s { uint32_t decoded_data_size; uint32_t decode_bias; uint32_t unknown2; uint32_t unknown3; } x3f_camf_type5_t; typedef struct x3f_camf_s { /* Header info */ uint32_t type; union { x3f_camf_typeN_t tN; x3f_camf_type2_t t2; x3f_camf_type4_t t4; x3f_camf_type5_t t5; }; /* The encrypted raw data */ void *data; uint32_t data_size; /* Help data for type 4 Huffman compression */ x3f_true_huffman_t table; x3f_hufftree_t tree; uint8_t *decoding_start; uint32_t decoding_size; /* The decrypted data */ void *decoded_data; uint32_t decoded_data_size; /* Pointers into the decrypted data */ camf_entry_table_t entry_table; } x3f_camf_t; typedef struct x3f_directory_entry_header_s { uint32_t identifier; /* Should be ´SECp´, "SECi", ... */ uint32_t version; /* 0x00020001 is version 2.1 */ union { x3f_property_list_t property_list; x3f_image_data_t image_data; x3f_camf_t camf; } data_subsection; } x3f_directory_entry_header_t; typedef struct x3f_directory_entry_s { struct { uint32_t offset; uint32_t size; } input, output; uint32_t type; x3f_directory_entry_header_t header; } x3f_directory_entry_t; typedef struct x3f_directory_section_s { uint32_t identifier; /* Should be ´SECd´ */ uint32_t version; /* 0x00020001 is version 2.1 */ /* 2.0 Fields */ uint32_t num_directory_entries; x3f_directory_entry_t *directory_entry; } x3f_directory_section_t; typedef struct x3f_header_s { /* 2.0 Fields */ uint32_t identifier; /* Should be ´FOVb´ */ uint32_t version; /* 0x00020001 means 2.1 */ uint8_t unique_identifier[SIZE_UNIQUE_IDENTIFIER]; uint32_t mark_bits; uint32_t columns; /* Columns and rows ... */ uint32_t rows; /* ... before rotation */ uint32_t rotation; /* 0, 90, 180, 270 */ char white_balance[SIZE_WHITE_BALANCE]; /* Introduced in 2.1 */ char color_mode[SIZE_COLOR_MODE]; /* Introduced in 2.3 */ /* Introduced in 2.1 and extended from 32 to 64 in 3.0 */ uint8_t extended_types[NUM_EXT_DATA]; /* x3f_extended_types_t */ float extended_data[NUM_EXT_DATA]; /* 32 bits, but do type differ? */ } x3f_header_t; typedef struct x3f_info_s { char *error; struct { LibRaw_abstract_datastream *file; /* Use if more data is needed */ } input, output; } x3f_info_t; typedef struct x3f_s { x3f_info_t info; x3f_header_t header; x3f_directory_section_t directory_section; } x3f_t; typedef enum x3f_return_e { X3F_OK=0, X3F_ARGUMENT_ERROR=1, X3F_INFILE_ERROR=2, X3F_OUTFILE_ERROR=3, X3F_INTERNAL_ERROR=4 } x3f_return_t; x3f_return_t x3f_delete(x3f_t *x3f); /* Hacky external flags */ /* --------------------------------------------------------------------- */ /* extern */ int legacy_offset = 0; /* extern */ bool_t auto_legacy_offset = 1; /* --------------------------------------------------------------------- */ /* Huffman Decode Macros */ /* --------------------------------------------------------------------- */ #define HUF_TREE_MAX_LENGTH 27 #define HUF_TREE_MAX_NODES(_leaves) ((HUF_TREE_MAX_LENGTH+1)*(_leaves)) #define HUF_TREE_GET_LENGTH(_v) (((_v)>>27)&0x1f) #define HUF_TREE_GET_CODE(_v) ((_v)&0x07ffffff) /* --------------------------------------------------------------------- */ /* Reading and writing - assuming little endian in the file */ /* --------------------------------------------------------------------- */ static int x3f_get1(LibRaw_abstract_datastream *f) { /* Little endian file */ return f->get_char(); } static int x3f_sget2 (uchar *s) { return s[0] | s[1] << 8; } static int x3f_get2(LibRaw_abstract_datastream *f) { uchar str[2] = { 0xff,0xff }; f->read (str, 1, 2); return x3f_sget2(str); } unsigned x3f_sget4 (uchar *s) { return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; } unsigned x3f_get4(LibRaw_abstract_datastream *f) { uchar str[4] = { 0xff,0xff,0xff,0xff }; f->read (str, 1, 4); return x3f_sget4(str); } #define FREE(P) do { free(P); (P) = NULL; } while (0) #define PUT_GET_N(_buffer,_size,_file,_func) \ do \ { \ int _left = _size; \ while (_left != 0) { \ int _cur = _file->_func(_buffer,1,_left); \ if (_cur == 0) { \ throw LIBRAW_EXCEPTION_IO_CORRUPT; \ } \ _left -= _cur; \ } \ } while(0) #define GET1(_v) do {(_v) = x3f_get1(I->input.file);} while (0) #define GET2(_v) do {(_v) = x3f_get2(I->input.file);} while (0) #define GET4(_v) do {(_v) = x3f_get4(I->input.file);} while (0) #define GET4F(_v) \ do { \ union {int32_t i; float f;} _tmp; \ _tmp.i = x3f_get4(I->input.file); \ (_v) = _tmp.f; \ } while (0) #define GETN(_v,_s) PUT_GET_N(_v,_s,I->input.file,read) #define GET_TABLE(_T, _GETX, _NUM,_TYPE) \ do { \ int _i; \ (_T).size = (_NUM); \ (_T).element = (_TYPE *)realloc((_T).element, \ (_NUM)*sizeof((_T).element[0])); \ for (_i = 0; _i < (_T).size; _i++) \ _GETX((_T).element[_i]); \ } while (0) #define GET_PROPERTY_TABLE(_T, _NUM) \ do { \ int _i; \ (_T).size = (_NUM); \ (_T).element = (x3f_property_t *)realloc((_T).element, \ (_NUM)*sizeof((_T).element[0])); \ for (_i = 0; _i < (_T).size; _i++) { \ GET4((_T).element[_i].name_offset); \ GET4((_T).element[_i].value_offset); \ } \ } while (0) #define GET_TRUE_HUFF_TABLE(_T) \ do { \ int _i; \ (_T).element = NULL; \ for (_i = 0; ; _i++) { \ (_T).size = _i + 1; \ (_T).element = (x3f_true_huffman_element_t *)realloc((_T).element, \ (_i + 1)*sizeof((_T).element[0])); \ GET1((_T).element[_i].code_size); \ GET1((_T).element[_i].code); \ if ((_T).element[_i].code_size == 0) break; \ } \ } while (0) /* --------------------------------------------------------------------- */ /* Allocating Huffman tree help data */ /* --------------------------------------------------------------------- */ static void cleanup_huffman_tree(x3f_hufftree_t *HTP) { free(HTP->nodes); } static void new_huffman_tree(x3f_hufftree_t *HTP, int bits) { int leaves = 1<<bits; HTP->free_node_index = 0; HTP->nodes = (x3f_huffnode_t *) calloc(1, HUF_TREE_MAX_NODES(leaves)*sizeof(x3f_huffnode_t)); } /* --------------------------------------------------------------------- */ /* Allocating TRUE engine RAW help data */ /* --------------------------------------------------------------------- */ static void cleanup_true(x3f_true_t **TRUP) { x3f_true_t *TRU = *TRUP; if (TRU == NULL) return; FREE(TRU->table.element); FREE(TRU->plane_size.element); cleanup_huffman_tree(&TRU->tree); FREE(TRU->x3rgb16.buf); FREE(TRU); *TRUP = NULL; } static x3f_true_t *new_true(x3f_true_t **TRUP) { x3f_true_t *TRU = (x3f_true_t *)calloc(1, sizeof(x3f_true_t)); cleanup_true(TRUP); TRU->table.size = 0; TRU->table.element = NULL; TRU->plane_size.size = 0; TRU->plane_size.element = NULL; TRU->tree.nodes = NULL; TRU->x3rgb16.data = NULL; TRU->x3rgb16.buf = NULL; *TRUP = TRU; return TRU; } static void cleanup_quattro(x3f_quattro_t **QP) { x3f_quattro_t *Q = *QP; if (Q == NULL) return; FREE(Q->top16.buf); FREE(Q); *QP = NULL; } static x3f_quattro_t *new_quattro(x3f_quattro_t **QP) { x3f_quattro_t *Q = (x3f_quattro_t *)calloc(1, sizeof(x3f_quattro_t)); int i; cleanup_quattro(QP); for (i=0; i<TRUE_PLANES; i++) { Q->plane[i].columns = 0; Q->plane[i].rows = 0; } Q->unknown = 0; Q->top16.data = NULL; Q->top16.buf = NULL; *QP = Q; return Q; } /* --------------------------------------------------------------------- */ /* Allocating Huffman engine help data */ /* --------------------------------------------------------------------- */ static void cleanup_huffman(x3f_huffman_t **HUFP) { x3f_huffman_t *HUF = *HUFP; if (HUF == NULL) return; FREE(HUF->mapping.element); FREE(HUF->table.element); cleanup_huffman_tree(&HUF->tree); FREE(HUF->row_offsets.element); FREE(HUF->rgb8.buf); FREE(HUF->x3rgb16.buf); FREE(HUF); *HUFP = NULL; } static x3f_huffman_t *new_huffman(x3f_huffman_t **HUFP) { x3f_huffman_t *HUF = (x3f_huffman_t *)calloc(1, sizeof(x3f_huffman_t)); cleanup_huffman(HUFP); /* Set all not read data block pointers to NULL */ HUF->mapping.size = 0; HUF->mapping.element = NULL; HUF->table.size = 0; HUF->table.element = NULL; HUF->tree.nodes = NULL; HUF->row_offsets.size = 0; HUF->row_offsets.element = NULL; HUF->rgb8.data = NULL; HUF->rgb8.buf = NULL; HUF->x3rgb16.data = NULL; HUF->x3rgb16.buf = NULL; *HUFP = HUF; return HUF; } /* --------------------------------------------------------------------- */ /* Creating a new x3f structure from file */ /* --------------------------------------------------------------------- */ /* extern */ x3f_t *x3f_new_from_file(LibRaw_abstract_datastream *infile) { if (!infile) return NULL; INT64 fsize = infile->size(); x3f_t *x3f = (x3f_t *)calloc(1, sizeof(x3f_t)); x3f_info_t *I = NULL; x3f_header_t *H = NULL; x3f_directory_section_t *DS = NULL; int i, d; I = &x3f->info; I->error = NULL; I->input.file = infile; I->output.file = NULL; /* Read file header */ H = &x3f->header; infile->seek(0, SEEK_SET); GET4(H->identifier); if (H->identifier != X3F_FOVb) { free(x3f); return NULL; } GET4(H->version); GETN(H->unique_identifier, SIZE_UNIQUE_IDENTIFIER); /* TODO: the meaning of the rest of the header for version >= 4.0 (Quattro) is unknown */ if (H->version < X3F_VERSION_4_0) { GET4(H->mark_bits); GET4(H->columns); GET4(H->rows); GET4(H->rotation); if (H->version >= X3F_VERSION_2_1) { int num_ext_data = H->version >= X3F_VERSION_3_0 ? NUM_EXT_DATA_3_0 : NUM_EXT_DATA_2_1; GETN(H->white_balance, SIZE_WHITE_BALANCE); if (H->version >= X3F_VERSION_2_3) GETN(H->color_mode, SIZE_COLOR_MODE); GETN(H->extended_types, num_ext_data); for (i = 0; i < num_ext_data; i++) GET4F(H->extended_data[i]); } } /* Go to the beginning of the directory */ infile->seek(-4, SEEK_END); infile->seek(x3f_get4(infile), SEEK_SET); /* Read the directory header */ DS = &x3f->directory_section; GET4(DS->identifier); GET4(DS->version); GET4(DS->num_directory_entries); if (DS->num_directory_entries > 50) goto _err; // too much direntries, most likely broken file if (DS->num_directory_entries > 0) { size_t size = DS->num_directory_entries * sizeof(x3f_directory_entry_t); DS->directory_entry = (x3f_directory_entry_t *)calloc(1, size); } /* Traverse the directory */ for (d=0; d<DS->num_directory_entries; d++) { x3f_directory_entry_t *DE = &DS->directory_entry[d]; x3f_directory_entry_header_t *DEH = &DE->header; uint32_t save_dir_pos; /* Read the directory entry info */ GET4(DE->input.offset); GET4(DE->input.size); if (DE->input.offset + DE->input.size > fsize * 2) goto _err; DE->output.offset = 0; DE->output.size = 0; GET4(DE->type); /* Save current pos and go to the entry */ save_dir_pos = infile->tell(); infile->seek(DE->input.offset, SEEK_SET); /* Read the type independent part of the entry header */ DEH = &DE->header; GET4(DEH->identifier); GET4(DEH->version); /* NOTE - the tests below could be made on DE->type instead */ if (DEH->identifier == X3F_SECp) { x3f_property_list_t *PL = &DEH->data_subsection.property_list; if (!PL) goto _err; /* Read the property part of the header */ GET4(PL->num_properties); GET4(PL->character_format); GET4(PL->reserved); GET4(PL->total_length); /* Set all not read data block pointers to NULL */ PL->data = NULL; PL->data_size = 0; } if (DEH->identifier == X3F_SECi) { x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID) goto _err; /* Read the image part of the header */ GET4(ID->type); GET4(ID->format); ID->type_format = (ID->type << 16) + (ID->format); GET4(ID->columns); GET4(ID->rows); GET4(ID->row_stride); /* Set all not read data block pointers to NULL */ ID->huffman = NULL; ID->data = NULL; ID->data_size = 0; } if (DEH->identifier == X3F_SECc) { x3f_camf_t *CAMF = &DEH->data_subsection.camf; if (!CAMF) goto _err; /* Read the CAMF part of the header */ GET4(CAMF->type); GET4(CAMF->tN.val0); GET4(CAMF->tN.val1); GET4(CAMF->tN.val2); GET4(CAMF->tN.val3); /* Set all not read data block pointers to NULL */ CAMF->data = NULL; CAMF->data_size = 0; /* Set all not allocated help pointers to NULL */ CAMF->table.element = NULL; CAMF->table.size = 0; CAMF->tree.nodes = NULL; CAMF->decoded_data = NULL; CAMF->decoded_data_size = 0; CAMF->entry_table.element = NULL; CAMF->entry_table.size = 0; } /* Reset the file pointer back to the directory */ infile->seek(save_dir_pos, SEEK_SET); } return x3f; _err: if (x3f) { DS = &x3f->directory_section; if (DS && DS->directory_entry) free(DS->directory_entry); free(x3f); } return NULL; } /* --------------------------------------------------------------------- */ /* Clean up an x3f structure */ /* --------------------------------------------------------------------- */ static void free_camf_entry(camf_entry_t *entry) { FREE(entry->property_name); FREE(entry->property_value); FREE(entry->matrix_decoded); FREE(entry->matrix_dim_entry); } /* extern */ x3f_return_t x3f_delete(x3f_t *x3f) { x3f_directory_section_t *DS; int d; if (x3f == NULL) return X3F_ARGUMENT_ERROR; DS = &x3f->directory_section; if (DS->num_directory_entries > 50) return X3F_ARGUMENT_ERROR; for (d=0; d<DS->num_directory_entries; d++) { x3f_directory_entry_t *DE = &DS->directory_entry[d]; x3f_directory_entry_header_t *DEH = &DE->header; if (DEH->identifier == X3F_SECp) { x3f_property_list_t *PL = &DEH->data_subsection.property_list; if (PL) { int i; } FREE(PL->property_table.element); FREE(PL->data); } if (DEH->identifier == X3F_SECi) { x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (ID) { cleanup_huffman(&ID->huffman); cleanup_true(&ID->tru); cleanup_quattro(&ID->quattro); FREE(ID->data); } } if (DEH->identifier == X3F_SECc) { x3f_camf_t *CAMF = &DEH->data_subsection.camf; int i; if (CAMF) { FREE(CAMF->data); FREE(CAMF->table.element); cleanup_huffman_tree(&CAMF->tree); FREE(CAMF->decoded_data); for (i = 0; i < CAMF->entry_table.size; i++) { free_camf_entry(&CAMF->entry_table.element[i]); } } FREE(CAMF->entry_table.element); } } FREE(DS->directory_entry); FREE(x3f); return X3F_OK; } /* --------------------------------------------------------------------- */ /* Getting a reference to a directory entry */ /* --------------------------------------------------------------------- */ /* TODO: all those only get the first instance */ static x3f_directory_entry_t *x3f_get(x3f_t *x3f, uint32_t type, uint32_t image_type) { x3f_directory_section_t *DS; int d; if (x3f == NULL) return NULL; DS = &x3f->directory_section; for (d=0; d<DS->num_directory_entries; d++) { x3f_directory_entry_t *DE = &DS->directory_entry[d]; x3f_directory_entry_header_t *DEH = &DE->header; if (DEH->identifier == type) { switch (DEH->identifier) { case X3F_SECi: { x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (ID->type_format == image_type) return DE; } break; default: return DE; } } } return NULL; } /* extern */ x3f_directory_entry_t *x3f_get_raw(x3f_t *x3f) { x3f_directory_entry_t *DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_HUFFMAN_X530)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_HUFFMAN_10BIT)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_TRUE)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_MERRILL)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_QUATTRO)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_SDQ)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_SDQH)) != NULL) return DE; if ((DE = x3f_get(x3f, X3F_SECi, X3F_IMAGE_RAW_SDQH2)) != NULL) return DE; return NULL; } /* extern */ x3f_directory_entry_t *x3f_get_thumb_plain(x3f_t *x3f) { return x3f_get(x3f, X3F_SECi, X3F_IMAGE_THUMB_PLAIN); } /* extern */ x3f_directory_entry_t *x3f_get_thumb_huffman(x3f_t *x3f) { return x3f_get(x3f, X3F_SECi, X3F_IMAGE_THUMB_HUFFMAN); } /* extern */ x3f_directory_entry_t *x3f_get_thumb_jpeg(x3f_t *x3f) { return x3f_get(x3f, X3F_SECi, X3F_IMAGE_THUMB_JPEG); } /* extern */ x3f_directory_entry_t *x3f_get_camf(x3f_t *x3f) { return x3f_get(x3f, X3F_SECc, 0); } /* extern */ x3f_directory_entry_t *x3f_get_prop(x3f_t *x3f) { return x3f_get(x3f, X3F_SECp, 0); } /* For some obscure reason, the bit numbering is weird. It is generally some kind of "big endian" style - e.g. the bit 7 is the first in a byte and bit 31 first in a 4 byte int. For patterns in the huffman pattern table, bit 27 is the first bit and bit 26 the next one. */ #define PATTERN_BIT_POS(_len, _bit) ((_len) - (_bit) - 1) #define MEMORY_BIT_POS(_bit) PATTERN_BIT_POS(8, _bit) /* --------------------------------------------------------------------- */ /* Huffman Decode */ /* --------------------------------------------------------------------- */ /* Make the huffman tree */ #ifdef DBG_PRNT static char *display_code(int length, uint32_t code, char *buffer) { int i; for (i=0; i<length; i++) { int pos = PATTERN_BIT_POS(length, i); buffer[i] = ((code>>pos)&1) == 0 ? '0' : '1'; } buffer[i] = 0; return buffer; } #endif static x3f_huffnode_t *new_node(x3f_hufftree_t *tree) { x3f_huffnode_t *t = &tree->nodes[tree->free_node_index]; t->branch[0] = NULL; t->branch[1] = NULL; t->leaf = UNDEFINED_LEAF; tree->free_node_index++; return t; } static void add_code_to_tree(x3f_hufftree_t *tree, int length, uint32_t code, uint32_t value) { int i; x3f_huffnode_t *t = tree->nodes; for (i=0; i<length; i++) { int pos = PATTERN_BIT_POS(length, i); int bit = (code>>pos)&1; x3f_huffnode_t *t_next = t->branch[bit]; if (t_next == NULL) t_next = t->branch[bit] = new_node(tree); t = t_next; } t->leaf = value; } static void populate_true_huffman_tree(x3f_hufftree_t *tree, x3f_true_huffman_t *table) { int i; new_node(tree); for (i=0; i<table->size; i++) { x3f_true_huffman_element_t *element = &table->element[i]; uint32_t length = element->code_size; if (length != 0) { /* add_code_to_tree wants the code right adjusted */ uint32_t code = ((element->code) >> (8 - length)) & 0xff; uint32_t value = i; add_code_to_tree(tree, length, code, value); #ifdef DBG_PRNT { char buffer[100]; x3f_printf(DEBUG, "H %5d : %5x : %5d : %02x %08x (%08x) (%s)\n", i, i, value, length, code, value, display_code(length, code, buffer)); } #endif } } } static void populate_huffman_tree(x3f_hufftree_t *tree, x3f_table32_t *table, x3f_table16_t *mapping) { int i; new_node(tree); for (i=0; i<table->size; i++) { uint32_t element = table->element[i]; if (element != 0) { uint32_t length = HUF_TREE_GET_LENGTH(element); uint32_t code = HUF_TREE_GET_CODE(element); uint32_t value; /* If we have a valid mapping table - then the value from the mapping table shall be used. Otherwise we use the current index in the table as value. */ if (table->size == mapping->size) value = mapping->element[i]; else value = i; add_code_to_tree(tree, length, code, value); #ifdef DBG_PRNT { char buffer[100]; x3f_printf(DEBUG, "H %5d : %5x : %5d : %02x %08x (%08x) (%s)\n", i, i, value, length, code, element, display_code(length, code, buffer)); } #endif } } } #ifdef DBG_PRNT static void print_huffman_tree(x3f_huffnode_t *t, int length, uint32_t code) { char buf1[100]; char buf2[100]; x3f_printf(DEBUG, "%*s (%s,%s) %s (%s)\n", length, length < 1 ? "-" : (code&1) ? "1" : "0", t->branch[0]==NULL ? "-" : "0", t->branch[1]==NULL ? "-" : "1", t->leaf==UNDEFINED_LEAF ? "-" : (sprintf(buf1, "%x", t->leaf),buf1), display_code(length, code, buf2)); code = code << 1; if (t->branch[0]) print_huffman_tree(t->branch[0], length+1, code+0); if (t->branch[1]) print_huffman_tree(t->branch[1], length+1, code+1); } #endif /* Help machinery for reading bits in a memory */ typedef struct bit_state_s { uint8_t *next_address; uint8_t bit_offset; uint8_t bits[8]; } bit_state_t; static void set_bit_state(bit_state_t *BS, uint8_t *address) { BS->next_address = address; BS->bit_offset = 8; } static uint8_t get_bit(bit_state_t *BS) { if (BS->bit_offset == 8) { uint8_t byte = *BS->next_address; int i; for (i=7; i>= 0; i--) { BS->bits[i] = byte&1; byte = byte >> 1; } BS->next_address++; BS->bit_offset = 0; } return BS->bits[BS->bit_offset++]; } /* Decode use the TRUE algorithm */ static int32_t get_true_diff(bit_state_t *BS, x3f_hufftree_t *HTP) { int32_t diff; x3f_huffnode_t *node = &HTP->nodes[0]; uint8_t bits; while (node->branch[0] != NULL || node->branch[1] != NULL) { uint8_t bit = get_bit(BS); x3f_huffnode_t *new_node = node->branch[bit]; node = new_node; if (node == NULL) { /* TODO: Shouldn't this be treated as a fatal error? */ return 0; } } bits = node->leaf; if (bits == 0) diff = 0; else { uint8_t first_bit = get_bit(BS); int i; diff = first_bit; for (i=1; i<bits; i++) diff = (diff << 1) + get_bit(BS); if (first_bit == 0) diff -= (1<<bits) - 1; } return diff; } /* This code (that decodes one of the X3F color planes, really is a decoding of a compression algorithm suited for Bayer CFA data. In Bayer CFA the data is divided into 2x2 squares that represents (R,G1,G2,B) data. Those four positions are (in this compression) treated as one data stream each, where you store the differences to previous data in the stream. The reason for this is, of course, that the date is more often than not near to the next data in a stream that represents the same color. */ /* TODO: write more about the compression */ static void true_decode_one_color(x3f_image_data_t *ID, int color) { x3f_true_t *TRU = ID->tru; x3f_quattro_t *Q = ID->quattro; uint32_t seed = TRU->seed[color]; /* TODO : Is this correct ? */ int row; x3f_hufftree_t *tree = &TRU->tree; bit_state_t BS; int32_t row_start_acc[2][2]; uint32_t rows = ID->rows; uint32_t cols = ID->columns; x3f_area16_t *area = &TRU->x3rgb16; uint16_t *dst = area->data + color; set_bit_state(&BS, TRU->plane_address[color]); row_start_acc[0][0] = seed; row_start_acc[0][1] = seed; row_start_acc[1][0] = seed; row_start_acc[1][1] = seed; if (ID->type_format == X3F_IMAGE_RAW_QUATTRO || ID->type_format == X3F_IMAGE_RAW_SDQ || ID->type_format == X3F_IMAGE_RAW_SDQH || ID->type_format == X3F_IMAGE_RAW_SDQH2 ) { rows = Q->plane[color].rows; cols = Q->plane[color].columns; if (Q->quattro_layout && color == 2) { area = &Q->top16; dst = area->data; } } else { } if(rows != area->rows || cols < area->columns) throw LIBRAW_EXCEPTION_IO_CORRUPT; for (row = 0; row < rows; row++) { int col; bool_t odd_row = row&1; int32_t acc[2]; for (col = 0; col < cols; col++) { bool_t odd_col = col&1; int32_t diff = get_true_diff(&BS, tree); int32_t prev = col < 2 ? row_start_acc[odd_row][odd_col] : acc[odd_col]; int32_t value = prev + diff; acc[odd_col] = value; if (col < 2) row_start_acc[odd_row][odd_col] = value; /* Discard additional data at the right for binned Quattro plane 2 */ if (col >= area->columns) continue; *dst = value; dst += area->channels; } } } static void true_decode(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; int color; for (color = 0; color < 3; color++) { true_decode_one_color(ID, color); } } /* Decode use the huffman tree */ static int32_t get_huffman_diff(bit_state_t *BS, x3f_hufftree_t *HTP) { int32_t diff; x3f_huffnode_t *node = &HTP->nodes[0]; while (node->branch[0] != NULL || node->branch[1] != NULL) { uint8_t bit = get_bit(BS); x3f_huffnode_t *new_node = node->branch[bit]; node = new_node; if (node == NULL) { /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; return 0; } } diff = node->leaf; return diff; } static void huffman_decode_row(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int row, int offset, int *minimum) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = ID->huffman; int16_t c[3] = {(int16_t)offset,(int16_t)offset,(int16_t)offset}; int col; bit_state_t BS; set_bit_state(&BS, (uint8_t*)ID->data + HUF->row_offsets.element[row]); for (col = 0; col < ID->columns; col++) { int color; for (color = 0; color < 3; color++) { uint16_t c_fix; c[color] += get_huffman_diff(&BS, &HUF->tree); if (c[color] < 0) { c_fix = 0; if (c[color] < *minimum) *minimum = c[color]; } else { c_fix = c[color]; } switch (ID->type_format) { case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: HUF->x3rgb16.data[3*(row*ID->columns + col) + color] = (uint16_t)c_fix; break; case X3F_IMAGE_THUMB_HUFFMAN: HUF->rgb8.data[3*(row*ID->columns + col) + color] = (uint8_t)c_fix; break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } } } } static void huffman_decode(x3f_info_t *I, x3f_directory_entry_t *DE, int bits) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; int row; int minimum = 0; int offset = legacy_offset; for (row = 0; row < ID->rows; row++) huffman_decode_row(I, DE, bits, row, offset, &minimum); if (auto_legacy_offset && minimum < 0) { offset = -minimum; for (row = 0; row < ID->rows; row++) huffman_decode_row(I, DE, bits, row, offset, &minimum); } } static int32_t get_simple_diff(x3f_huffman_t *HUF, uint16_t index) { if (HUF->mapping.size == 0) return index; else return HUF->mapping.element[index]; } static void simple_decode_row(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int row, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = ID->huffman; uint32_t *data = (uint32_t *)((unsigned char*)ID->data + row*row_stride); uint16_t c[3] = {0,0,0}; int col; uint32_t mask = 0; switch (bits) { case 8: mask = 0x0ff; break; case 9: mask = 0x1ff; break; case 10: mask = 0x3ff; break; case 11: mask = 0x7ff; break; case 12: mask = 0xfff; break; default: mask = 0; /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; break; } for (col = 0; col < ID->columns; col++) { int color; uint32_t val = data[col]; for (color = 0; color < 3; color++) { uint16_t c_fix; c[color] += get_simple_diff(HUF, (val>>(color*bits))&mask); switch (ID->type_format) { case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: c_fix = (int16_t)c[color] > 0 ? c[color] : 0; HUF->x3rgb16.data[3*(row*ID->columns + col) + color] = c_fix; break; case X3F_IMAGE_THUMB_HUFFMAN: c_fix = (int8_t)c[color] > 0 ? c[color] : 0; HUF->rgb8.data[3*(row*ID->columns + col) + color] = c_fix; break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } } } } static void simple_decode(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; int row; for (row = 0; row < ID->rows; row++) simple_decode_row(I, DE, bits, row, row_stride); } /* --------------------------------------------------------------------- */ /* Loading the data in a directory entry */ /* --------------------------------------------------------------------- */ /* First you set the offset to where to start reading the data ... */ static void read_data_set_offset(x3f_info_t *I, x3f_directory_entry_t *DE, uint32_t header_size) { uint32_t i_off = DE->input.offset + header_size; I->input.file->seek(i_off, SEEK_SET); } /* ... then you read the data, block for block */ static uint32_t read_data_block(void **data, x3f_info_t *I, x3f_directory_entry_t *DE, uint32_t footer) { INT64 fpos = I->input.file->tell(); uint32_t size = DE->input.size + DE->input.offset - fpos - footer; if (fpos + size > I->input.file->size()) throw LIBRAW_EXCEPTION_IO_CORRUPT; *data = (void *)malloc(size); GETN(*data, size); return size; } static uint32_t data_block_size(void **data, x3f_info_t *I, x3f_directory_entry_t *DE, uint32_t footer) { uint32_t size = DE->input.size + DE->input.offset - I->input.file->tell() - footer; return size; } static void x3f_load_image_verbatim(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, 0); } static int32_t x3f_load_image_verbatim_size(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; return data_block_size(&ID->data, I, DE, 0); } static void x3f_load_property_list(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_property_list_t *PL = &DEH->data_subsection.property_list; int i; read_data_set_offset(I, DE, X3F_PROPERTY_LIST_HEADER_SIZE); GET_PROPERTY_TABLE(PL->property_table, PL->num_properties); if (!PL->data_size) PL->data_size = read_data_block(&PL->data, I, DE, 0); uint32_t maxoffset = PL->data_size/sizeof(utf16_t)-2; // at least 2 chars, value + terminating 0x0000 for (i=0; i<PL->num_properties; i++) { x3f_property_t *P = &PL->property_table.element[i]; if(P->name_offset > maxoffset || P->value_offset > maxoffset) throw LIBRAW_EXCEPTION_IO_CORRUPT; P->name = ((utf16_t *)PL->data + P->name_offset); P->value = ((utf16_t *)PL->data + P->value_offset); } } static void x3f_load_true(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_true_t *TRU = new_true(&ID->tru); x3f_quattro_t *Q = NULL; int i; if (ID->type_format == X3F_IMAGE_RAW_QUATTRO || ID->type_format == X3F_IMAGE_RAW_SDQ || ID->type_format == X3F_IMAGE_RAW_SDQH || ID->type_format == X3F_IMAGE_RAW_SDQH2 ) { Q = new_quattro(&ID->quattro); for (i=0; i<TRUE_PLANES; i++) { GET2(Q->plane[i].columns); GET2(Q->plane[i].rows); } if (Q->plane[0].rows == ID->rows/2) { Q->quattro_layout = 1; } else if (Q->plane[0].rows == ID->rows) { Q->quattro_layout = 0; } else { throw LIBRAW_EXCEPTION_IO_CORRUPT; } } /* Read TRUE header data */ GET2(TRU->seed[0]); GET2(TRU->seed[1]); GET2(TRU->seed[2]); GET2(TRU->unknown); GET_TRUE_HUFF_TABLE(TRU->table); if (ID->type_format == X3F_IMAGE_RAW_QUATTRO ||ID->type_format == X3F_IMAGE_RAW_SDQ ||ID->type_format == X3F_IMAGE_RAW_SDQH ||ID->type_format == X3F_IMAGE_RAW_SDQH2 ) { GET4(Q->unknown); } GET_TABLE(TRU->plane_size, GET4, TRUE_PLANES,uint32_t); /* Read image data */ if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, 0); /* TODO: can it be fewer than 8 bits? Maybe taken from TRU->table? */ new_huffman_tree(&TRU->tree, 8); populate_true_huffman_tree(&TRU->tree, &TRU->table); #ifdef DBG_PRNT print_huffman_tree(TRU->tree.nodes, 0, 0); #endif TRU->plane_address[0] = (uint8_t*)ID->data; for (i=1; i<TRUE_PLANES; i++) TRU->plane_address[i] = TRU->plane_address[i-1] + (((TRU->plane_size.element[i-1] + 15) / 16) * 16); if ( (ID->type_format == X3F_IMAGE_RAW_QUATTRO || ID->type_format == X3F_IMAGE_RAW_SDQ || ID->type_format == X3F_IMAGE_RAW_SDQH || ID->type_format == X3F_IMAGE_RAW_SDQH2 ) && Q->quattro_layout) { uint32_t columns = Q->plane[0].columns; uint32_t rows = Q->plane[0].rows; uint32_t channels = 3; uint32_t size = columns * rows * channels; TRU->x3rgb16.columns = columns; TRU->x3rgb16.rows = rows; TRU->x3rgb16.channels = channels; TRU->x3rgb16.row_stride = columns * channels; TRU->x3rgb16.buf = malloc(sizeof(uint16_t)*size); TRU->x3rgb16.data = (uint16_t *) TRU->x3rgb16.buf; columns = Q->plane[2].columns; rows = Q->plane[2].rows; channels = 1; size = columns * rows * channels; Q->top16.columns = columns; Q->top16.rows = rows; Q->top16.channels = channels; Q->top16.row_stride = columns * channels; Q->top16.buf = malloc(sizeof(uint16_t)*size); Q->top16.data = (uint16_t *)Q->top16.buf; } else { uint32_t size = ID->columns * ID->rows * 3; TRU->x3rgb16.columns = ID->columns; TRU->x3rgb16.rows = ID->rows; TRU->x3rgb16.channels = 3; TRU->x3rgb16.row_stride = ID->columns * 3; TRU->x3rgb16.buf =malloc(sizeof(uint16_t)*size); TRU->x3rgb16.data = (uint16_t *)TRU->x3rgb16.buf; } true_decode(I, DE); } static void x3f_load_huffman_compressed(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int use_map_table) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = ID->huffman; int table_size = 1<<bits; int row_offsets_size = ID->rows * sizeof(HUF->row_offsets.element[0]); GET_TABLE(HUF->table, GET4, table_size,uint32_t); if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, row_offsets_size); GET_TABLE(HUF->row_offsets, GET4, ID->rows,uint32_t); new_huffman_tree(&HUF->tree, bits); populate_huffman_tree(&HUF->tree, &HUF->table, &HUF->mapping); huffman_decode(I, DE, bits); } static void x3f_load_huffman_not_compressed(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int use_map_table, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; if (!ID->data_size) ID->data_size = read_data_block(&ID->data, I, DE, 0); simple_decode(I, DE, bits, row_stride); } static void x3f_load_huffman(x3f_info_t *I, x3f_directory_entry_t *DE, int bits, int use_map_table, int row_stride) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; x3f_huffman_t *HUF = new_huffman(&ID->huffman); uint32_t size; if (use_map_table) { int table_size = 1<<bits; GET_TABLE(HUF->mapping, GET2, table_size,uint16_t); } switch (ID->type_format) { case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: size = ID->columns * ID->rows * 3; HUF->x3rgb16.columns = ID->columns; HUF->x3rgb16.rows = ID->rows; HUF->x3rgb16.channels = 3; HUF->x3rgb16.row_stride = ID->columns * 3; HUF->x3rgb16.buf = malloc(sizeof(uint16_t)*size); HUF->x3rgb16.data = (uint16_t *)HUF->x3rgb16.buf; break; case X3F_IMAGE_THUMB_HUFFMAN: size = ID->columns * ID->rows * 3; HUF->rgb8.columns = ID->columns; HUF->rgb8.rows = ID->rows; HUF->rgb8.channels = 3; HUF->rgb8.row_stride = ID->columns * 3; HUF->rgb8.buf = malloc(sizeof(uint8_t)*size); HUF->rgb8.data = (uint8_t *)HUF->rgb8.buf; break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } if (row_stride == 0) return x3f_load_huffman_compressed(I, DE, bits, use_map_table); else return x3f_load_huffman_not_compressed(I, DE, bits, use_map_table, row_stride); } static void x3f_load_pixmap(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_load_image_verbatim(I, DE); } static uint32_t x3f_load_pixmap_size(x3f_info_t *I, x3f_directory_entry_t *DE) { return x3f_load_image_verbatim_size(I, DE); } static void x3f_load_jpeg(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_load_image_verbatim(I, DE); } static uint32_t x3f_load_jpeg_size(x3f_info_t *I, x3f_directory_entry_t *DE) { return x3f_load_image_verbatim_size(I, DE); } static void x3f_load_image(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; read_data_set_offset(I, DE, X3F_IMAGE_HEADER_SIZE); switch (ID->type_format) { case X3F_IMAGE_RAW_TRUE: case X3F_IMAGE_RAW_MERRILL: case X3F_IMAGE_RAW_QUATTRO: case X3F_IMAGE_RAW_SDQ: case X3F_IMAGE_RAW_SDQH: case X3F_IMAGE_RAW_SDQH2: x3f_load_true(I, DE); break; case X3F_IMAGE_RAW_HUFFMAN_X530: case X3F_IMAGE_RAW_HUFFMAN_10BIT: x3f_load_huffman(I, DE, 10, 1, ID->row_stride); break; case X3F_IMAGE_THUMB_PLAIN: x3f_load_pixmap(I, DE); break; case X3F_IMAGE_THUMB_HUFFMAN: x3f_load_huffman(I, DE, 8, 0, ID->row_stride); break; case X3F_IMAGE_THUMB_JPEG: x3f_load_jpeg(I, DE); break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } } // Used only for thumbnail size estimation static uint32_t x3f_load_image_size(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_image_data_t *ID = &DEH->data_subsection.image_data; read_data_set_offset(I, DE, X3F_IMAGE_HEADER_SIZE); switch (ID->type_format) { case X3F_IMAGE_THUMB_PLAIN: return x3f_load_pixmap_size(I, DE); case X3F_IMAGE_THUMB_JPEG: return x3f_load_jpeg_size(I, DE); break; default: return 0; } } static void x3f_load_camf_decode_type2(x3f_camf_t *CAMF) { uint32_t key = CAMF->t2.crypt_key; int i; CAMF->decoded_data_size = CAMF->data_size; CAMF->decoded_data = malloc(CAMF->decoded_data_size); for (i=0; i<CAMF->data_size; i++) { uint8_t old, _new; uint32_t tmp; old = ((uint8_t *)CAMF->data)[i]; key = (key * 1597 + 51749) % 244944; tmp = (uint32_t)(key * ((int64_t)301593171) >> 24); _new = (uint8_t)(old ^ (uint8_t)(((((key << 8) - tmp) >> 1) + tmp) >> 17)); ((uint8_t *)CAMF->decoded_data)[i] = _new; } } /* NOTE: the unpacking in this code is in big respects identical to true_decode_one_color(). The difference is in the output you build. It might be possible to make some parts shared. NOTE ALSO: This means that the meta data is obfuscated using an image compression algorithm. */ static void camf_decode_type4(x3f_camf_t *CAMF) { uint32_t seed = CAMF->t4.decode_bias; int row; uint8_t *dst; uint32_t dst_size = CAMF->t4.decoded_data_size; uint8_t *dst_end; bool_t odd_dst = 0; x3f_hufftree_t *tree = &CAMF->tree; bit_state_t BS; int32_t row_start_acc[2][2]; uint32_t rows = CAMF->t4.block_count; uint32_t cols = CAMF->t4.block_size; CAMF->decoded_data_size = dst_size; CAMF->decoded_data = malloc(CAMF->decoded_data_size); memset(CAMF->decoded_data, 0, CAMF->decoded_data_size); dst = (uint8_t *)CAMF->decoded_data; dst_end = dst + dst_size; set_bit_state(&BS, CAMF->decoding_start); row_start_acc[0][0] = seed; row_start_acc[0][1] = seed; row_start_acc[1][0] = seed; row_start_acc[1][1] = seed; for (row = 0; row < rows; row++) { int col; bool_t odd_row = row&1; int32_t acc[2]; /* We loop through all the columns and the rows. But the actual data is smaller than that, so we break the loop when reaching the end. */ for (col = 0; col < cols; col++) { bool_t odd_col = col&1; int32_t diff = get_true_diff(&BS, tree); int32_t prev = col < 2 ? row_start_acc[odd_row][odd_col] : acc[odd_col]; int32_t value = prev + diff; acc[odd_col] = value; if (col < 2) row_start_acc[odd_row][odd_col] = value; switch(odd_dst) { case 0: *dst++ = (uint8_t)((value>>4)&0xff); if (dst >= dst_end) { goto ready; } *dst = (uint8_t)((value<<4)&0xf0); break; case 1: *dst++ |= (uint8_t)((value>>8)&0x0f); if (dst >= dst_end) { goto ready; } *dst++ = (uint8_t)((value<<0)&0xff); if (dst >= dst_end) { goto ready; } break; } odd_dst = !odd_dst; } /* end col */ } /* end row */ ready:; } static void x3f_load_camf_decode_type4(x3f_camf_t *CAMF) { int i; uint8_t *p; x3f_true_huffman_element_t *element = NULL; for (i=0, p = (uint8_t*)CAMF->data; *p != 0; i++) { /* TODO: Is this too expensive ??*/ element = (x3f_true_huffman_element_t *)realloc(element, (i+1)*sizeof(*element)); element[i].code_size = *p++; element[i].code = *p++; } CAMF->table.size = i; CAMF->table.element = element; /* TODO: where does the values 28 and 32 come from? */ #define CAMF_T4_DATA_SIZE_OFFSET 28 #define CAMF_T4_DATA_OFFSET 32 CAMF->decoding_size = *(uint32_t *)((unsigned char*)CAMF->data + CAMF_T4_DATA_SIZE_OFFSET); CAMF->decoding_start = (uint8_t *)CAMF->data + CAMF_T4_DATA_OFFSET; /* TODO: can it be fewer than 8 bits? Maybe taken from TRU->table? */ new_huffman_tree(&CAMF->tree, 8); populate_true_huffman_tree(&CAMF->tree, &CAMF->table); #ifdef DBG_PRNT print_huffman_tree(CAMF->tree.nodes, 0, 0); #endif camf_decode_type4(CAMF); } static void camf_decode_type5(x3f_camf_t *CAMF) { int32_t acc = CAMF->t5.decode_bias; uint8_t *dst; x3f_hufftree_t *tree = &CAMF->tree; bit_state_t BS; int32_t i; CAMF->decoded_data_size = CAMF->t5.decoded_data_size; CAMF->decoded_data = malloc(CAMF->decoded_data_size); dst = (uint8_t *)CAMF->decoded_data; set_bit_state(&BS, CAMF->decoding_start); for (i = 0; i < CAMF->decoded_data_size; i++) { int32_t diff = get_true_diff(&BS, tree); acc = acc + diff; *dst++ = (uint8_t)(acc & 0xff); } } static void x3f_load_camf_decode_type5(x3f_camf_t *CAMF) { int i; uint8_t *p; x3f_true_huffman_element_t *element = NULL; for (i=0, p = (uint8_t*)CAMF->data; *p != 0; i++) { /* TODO: Is this too expensive ??*/ element = (x3f_true_huffman_element_t *)realloc(element, (i+1)*sizeof(*element)); element[i].code_size = *p++; element[i].code = *p++; } CAMF->table.size = i; CAMF->table.element = element; /* TODO: where does the values 28 and 32 come from? */ #define CAMF_T5_DATA_SIZE_OFFSET 28 #define CAMF_T5_DATA_OFFSET 32 CAMF->decoding_size = *(uint32_t *)((uint8_t*)CAMF->data + CAMF_T5_DATA_SIZE_OFFSET); CAMF->decoding_start = (uint8_t *)CAMF->data + CAMF_T5_DATA_OFFSET; /* TODO: can it be fewer than 8 bits? Maybe taken from TRU->table? */ new_huffman_tree(&CAMF->tree, 8); populate_true_huffman_tree(&CAMF->tree, &CAMF->table); #ifdef DBG_PRNT print_huffman_tree(CAMF->tree.nodes, 0, 0); #endif camf_decode_type5(CAMF); } static void x3f_setup_camf_text_entry(camf_entry_t *entry) { entry->text_size = *(uint32_t *)entry->value_address; entry->text = (char*)entry->value_address + 4; } static void x3f_setup_camf_property_entry(camf_entry_t *entry) { int i; uint8_t *e = (uint8_t*)entry->entry; uint8_t *v = (uint8_t*)entry->value_address; uint32_t num = entry->property_num = *(uint32_t *)v; uint32_t off = *(uint32_t *)(v + 4); entry->property_name = (char **)malloc(num*sizeof(uint8_t*)); entry->property_value = (uint8_t **)malloc(num*sizeof(uint8_t*)); for (i=0; i<num; i++) { uint32_t name_off = off + *(uint32_t *)(v + 8 + 8*i); uint32_t value_off = off + *(uint32_t *)(v + 8 + 8*i + 4); entry->property_name[i] = (char *)(e + name_off); entry->property_value[i] = e + value_off; } } static void set_matrix_element_info(uint32_t type, uint32_t *size, matrix_type_t *decoded_type) { switch (type) { case 0: *size = 2; *decoded_type = M_INT; /* known to be true */ break; case 1: *size = 4; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; case 2: *size = 4; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; case 3: *size = 4; *decoded_type = M_FLOAT; /* known to be true */ break; case 5: *size = 1; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; case 6: *size = 2; *decoded_type = M_UINT; /* TODO: unknown ???? */ break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } } static void get_matrix_copy(camf_entry_t *entry) { uint32_t element_size = entry->matrix_element_size; uint32_t elements = entry->matrix_elements; int i, size = (entry->matrix_decoded_type==M_FLOAT ? sizeof(double) : sizeof(uint32_t)) * elements; entry->matrix_decoded = malloc(size); switch (element_size) { case 4: switch (entry->matrix_decoded_type) { case M_INT: case M_UINT: memcpy(entry->matrix_decoded, entry->matrix_data, size); break; case M_FLOAT: for (i=0; i<elements; i++) ((double *)entry->matrix_decoded)[i] = (double)((float *)entry->matrix_data)[i]; break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } break; case 2: switch (entry->matrix_decoded_type) { case M_INT: for (i=0; i<elements; i++) ((int32_t *)entry->matrix_decoded)[i] = (int32_t)((int16_t *)entry->matrix_data)[i]; break; case M_UINT: for (i=0; i<elements; i++) ((uint32_t *)entry->matrix_decoded)[i] = (uint32_t)((uint16_t *)entry->matrix_data)[i]; break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } break; case 1: switch (entry->matrix_decoded_type) { case M_INT: for (i=0; i<elements; i++) ((int32_t *)entry->matrix_decoded)[i] = (int32_t)((int8_t *)entry->matrix_data)[i]; break; case M_UINT: for (i=0; i<elements; i++) ((uint32_t *)entry->matrix_decoded)[i] = (uint32_t)((uint8_t *)entry->matrix_data)[i]; break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; } } static void x3f_setup_camf_matrix_entry(camf_entry_t *entry) { int i; int totalsize = 1; uint8_t *e = (uint8_t *)entry->entry; uint8_t *v = (uint8_t *)entry->value_address; uint32_t type = entry->matrix_type = *(uint32_t *)(v + 0); uint32_t dim = entry->matrix_dim = *(uint32_t *)(v + 4); uint32_t off = entry->matrix_data_off = *(uint32_t *)(v + 8); camf_dim_entry_t *dentry = entry->matrix_dim_entry = (camf_dim_entry_t*)malloc(dim*sizeof(camf_dim_entry_t)); for (i=0; i<dim; i++) { uint32_t size = dentry[i].size = *(uint32_t *)(v + 12 + 12*i + 0); dentry[i].name_offset = *(uint32_t *)(v + 12 + 12*i + 4); dentry[i].n = *(uint32_t *)(v + 12 + 12*i + 8); dentry[i].name = (char *)(e + dentry[i].name_offset); if (dentry[i].n != i) { } totalsize *= size; } set_matrix_element_info(type, &entry->matrix_element_size, &entry->matrix_decoded_type); entry->matrix_data = (void *)(e + off); entry->matrix_elements = totalsize; entry->matrix_used_space = entry->entry_size - off; /* This estimate only works for matrices above a certain size */ entry->matrix_estimated_element_size = entry->matrix_used_space / totalsize; get_matrix_copy(entry); } static void x3f_setup_camf_entries(x3f_camf_t *CAMF) { uint8_t *p = (uint8_t *)CAMF->decoded_data; uint8_t *end = p + CAMF->decoded_data_size; camf_entry_t *entry = NULL; int i; for (i=0; p < end; i++) { uint32_t *p4 = (uint32_t *)p; switch (*p4) { case X3F_CMbP: case X3F_CMbT: case X3F_CMbM: break; default: goto stop; } /* TODO: lots of realloc - may be inefficient */ entry = (camf_entry_t *)realloc(entry, (i+1)*sizeof(camf_entry_t)); /* Pointer */ entry[i].entry = p; /* Header */ entry[i].id = *p4++; entry[i].version = *p4++; entry[i].entry_size = *p4++; entry[i].name_offset = *p4++; entry[i].value_offset = *p4++; /* Compute adresses and sizes */ entry[i].name_address = (char *)(p + entry[i].name_offset); entry[i].value_address = p + entry[i].value_offset; entry[i].name_size = entry[i].value_offset - entry[i].name_offset; entry[i].value_size = entry[i].entry_size - entry[i].value_offset; entry[i].text_size = 0; entry[i].text = NULL; entry[i].property_num = 0; entry[i].property_name = NULL; entry[i].property_value = NULL; entry[i].matrix_type = 0; entry[i].matrix_dim = 0; entry[i].matrix_data_off = 0; entry[i].matrix_data = NULL; entry[i].matrix_dim_entry = NULL; entry[i].matrix_decoded = NULL; switch (entry[i].id) { case X3F_CMbP: x3f_setup_camf_property_entry(&entry[i]); break; case X3F_CMbT: x3f_setup_camf_text_entry(&entry[i]); break; case X3F_CMbM: x3f_setup_camf_matrix_entry(&entry[i]); break; } p += entry[i].entry_size; } stop: CAMF->entry_table.size = i; CAMF->entry_table.element = entry; } static void x3f_load_camf(x3f_info_t *I, x3f_directory_entry_t *DE) { x3f_directory_entry_header_t *DEH = &DE->header; x3f_camf_t *CAMF = &DEH->data_subsection.camf; read_data_set_offset(I, DE, X3F_CAMF_HEADER_SIZE); if (!CAMF->data_size) CAMF->data_size = read_data_block(&CAMF->data, I, DE, 0); switch (CAMF->type) { case 2: /* Older SD9-SD14 */ x3f_load_camf_decode_type2(CAMF); break; case 4: /* TRUE ... Merrill */ x3f_load_camf_decode_type4(CAMF); break; case 5: /* Quattro ... */ x3f_load_camf_decode_type5(CAMF); break; default: /* TODO: Shouldn't this be treated as a fatal error? */ throw LIBRAW_EXCEPTION_IO_CORRUPT; } if (CAMF->decoded_data != NULL) x3f_setup_camf_entries(CAMF); else throw LIBRAW_EXCEPTION_IO_CORRUPT; } /* extern */ x3f_return_t x3f_load_data(x3f_t *x3f, x3f_directory_entry_t *DE) { x3f_info_t *I = &x3f->info; if (DE == NULL) return X3F_ARGUMENT_ERROR; switch (DE->header.identifier) { case X3F_SECp: x3f_load_property_list(I, DE); break; case X3F_SECi: x3f_load_image(I, DE); break; case X3F_SECc: x3f_load_camf(I, DE); break; default: return X3F_INTERNAL_ERROR; } return X3F_OK; } /* extern */ int64_t x3f_load_data_size(x3f_t *x3f, x3f_directory_entry_t *DE) { x3f_info_t *I = &x3f->info; if (DE == NULL) return -1; switch (DE->header.identifier) { case X3F_SECi: return x3f_load_image_size(I, DE); default: return 0; } } /* extern */ x3f_return_t x3f_load_image_block(x3f_t *x3f, x3f_directory_entry_t *DE) { x3f_info_t *I = &x3f->info; if (DE == NULL) return X3F_ARGUMENT_ERROR; switch (DE->header.identifier) { case X3F_SECi: read_data_set_offset(I, DE, X3F_IMAGE_HEADER_SIZE); x3f_load_image_verbatim(I, DE); break; default: throw LIBRAW_EXCEPTION_IO_CORRUPT; return X3F_INTERNAL_ERROR; } return X3F_OK; } /* --------------------------------------------------------------------- */ /* The End */ /* --------------------------------------------------------------------- */
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_94_1
crossvul-cpp_data_good_3390_0
// validat1.cpp - originally written and placed in the public domain by Wei Dai // CryptoPP::Test namespace added by JW in February 2017 #include "pch.h" #define CRYPTOPP_ENABLE_NAMESPACE_WEAK 1 #include "cryptlib.h" #include "pubkey.h" #include "gfpcrypt.h" #include "eccrypto.h" #include "filters.h" #include "files.h" #include "hex.h" #include "base32.h" #include "base64.h" #include "modes.h" #include "cbcmac.h" #include "dmac.h" #include "idea.h" #include "des.h" #include "rc2.h" #include "arc4.h" #include "rc5.h" #include "blowfish.h" #include "3way.h" #include "safer.h" #include "gost.h" #include "shark.h" #include "cast.h" #include "square.h" #include "seal.h" #include "rc6.h" #include "mars.h" #include "aes.h" #include "cpu.h" #include "rng.h" #include "rijndael.h" #include "twofish.h" #include "serpent.h" #include "skipjack.h" #include "shacal2.h" #include "camellia.h" #include "aria.h" #include "osrng.h" #include "drbg.h" #include "rdrand.h" #include "mersenne.h" #include "randpool.h" #include "zdeflate.h" #include "smartptr.h" #include "channels.h" #include "misc.h" #include <time.h> #include <memory> #include <iostream> #include <iomanip> #include "validate.h" // Aggressive stack checking with VS2005 SP1 and above. #if (CRYPTOPP_MSC_VERSION >= 1410) # pragma strict_gs_check (on) #endif NAMESPACE_BEGIN(CryptoPP) NAMESPACE_BEGIN(Test) bool ValidateAll(bool thorough) { bool pass=TestSettings(); pass=TestOS_RNG() && pass; pass=TestRandomPool() && pass; #if !defined(NO_OS_DEPENDENCE) pass=TestAutoSeededX917() && pass; #endif // pass=TestSecRandom() && pass; #if defined(CRYPTOPP_EXTENDED_VALIDATION) pass=TestMersenne() && pass; #endif #if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64) pass=TestRDRAND() && pass; pass=TestRDSEED() && pass; #endif #if defined(CRYPTOPP_EXTENDED_VALIDATION) // http://github.com/weidai11/cryptopp/issues/92 pass=TestSecBlock() && pass; // http://github.com/weidai11/cryptopp/issues/336 pass=TestIntegerBitops() && pass; // http://github.com/weidai11/cryptopp/issues/64 pass=TestPolynomialMod2() && pass; // http://github.com/weidai11/cryptopp/issues/360 pass=TestRounding() && pass; // http://github.com/weidai11/cryptopp/issues/242 pass=TestHuffmanCodes() && pass; // http://github.com/weidai11/cryptopp/issues/346 pass=TestASN1Parse() && pass; // Additional tests due to no coverage pass=ValidateBaseCode() && pass; pass=TestCompressors() && pass; pass=TestSharing() && pass; pass=TestEncryptors() && pass; #endif pass=ValidateCRC32() && pass; pass=ValidateCRC32C() && pass; pass=ValidateAdler32() && pass; pass=ValidateMD2() && pass; #if defined(CRYPTOPP_EXTENDED_VALIDATION) pass=ValidateMD4() && pass; #endif pass=ValidateMD5() && pass; pass=ValidateSHA() && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/keccak.txt") && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/sha3.txt") && pass; pass=ValidateHashDRBG() && pass; pass=ValidateHmacDRBG() && pass; pass=ValidateTiger() && pass; pass=ValidateRIPEMD() && pass; pass=ValidatePanama() && pass; pass=ValidateWhirlpool() && pass; pass=ValidateBLAKE2s() && pass; pass=ValidateBLAKE2b() && pass; pass=ValidatePoly1305() && pass; pass=ValidateSipHash() && pass; pass=ValidateHMAC() && pass; pass=ValidateTTMAC() && pass; pass=ValidatePBKDF() && pass; pass=ValidateHKDF() && pass; pass=ValidateDES() && pass; pass=ValidateCipherModes() && pass; pass=ValidateIDEA() && pass; pass=ValidateSAFER() && pass; pass=ValidateRC2() && pass; pass=ValidateARC4() && pass; pass=ValidateRC5() && pass; pass=ValidateBlowfish() && pass; pass=ValidateThreeWay() && pass; pass=ValidateGOST() && pass; pass=ValidateSHARK() && pass; pass=ValidateCAST() && pass; pass=ValidateSquare() && pass; pass=ValidateSKIPJACK() && pass; pass=ValidateSEAL() && pass; pass=ValidateRC6() && pass; pass=ValidateMARS() && pass; pass=ValidateRijndael() && pass; pass=ValidateTwofish() && pass; pass=ValidateSerpent() && pass; pass=ValidateSHACAL2() && pass; pass=ValidateARIA() && pass; pass=ValidateCamellia() && pass; pass=ValidateSalsa() && pass; pass=ValidateSosemanuk() && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/seed.txt") && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/kalyna.txt") && pass; pass=ValidateVMAC() && pass; pass=ValidateCCM() && pass; pass=ValidateGCM() && pass; pass=ValidateCMAC() && pass; pass=RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/eax.txt") && pass; pass=ValidateBBS() && pass; pass=ValidateDH() && pass; pass=ValidateMQV() && pass; pass=ValidateHMQV() && pass; pass=ValidateFHMQV() && pass; pass=ValidateRSA() && pass; pass=ValidateElGamal() && pass; pass=ValidateDLIES() && pass; pass=ValidateNR() && pass; pass=ValidateDSA(thorough) && pass; pass=ValidateLUC() && pass; pass=ValidateLUC_DH() && pass; pass=ValidateLUC_DL() && pass; pass=ValidateXTR_DH() && pass; pass=ValidateRabin() && pass; pass=ValidateRW() && pass; // pass=ValidateBlumGoldwasser() && pass; pass=ValidateECP() && pass; pass=ValidateEC2N() && pass; pass=ValidateECDSA() && pass; pass=ValidateECGDSA() && pass; pass=ValidateESIGN() && pass; if (pass) std::cout << "\nAll tests passed!\n"; else std::cout << "\nOops! Not all tests passed.\n"; return pass; } bool TestSettings() { bool pass = true; std::cout << "\nTesting Settings...\n\n"; word32 w; const byte s[] = "\x01\x02\x03\x04"; #if (CRYPTOPP_MSC_VERSION >= 1410) std::copy(s, s+4, stdext::make_checked_array_iterator(reinterpret_cast<byte*>(&w), sizeof(w))); #else std::copy(s, s+4, reinterpret_cast<byte*>(&w)); #endif if (w == 0x04030201L) { #ifdef IS_LITTLE_ENDIAN std::cout << "passed: "; #else std::cout << "FAILED: "; pass = false; #endif std::cout << "Your machine is little endian.\n"; } else if (w == 0x01020304L) { #ifndef IS_LITTLE_ENDIAN std::cout << "passed: "; #else std::cout << "FAILED: "; pass = false; #endif std::cout << "Your machine is big endian.\n"; } else { std::cout << "FAILED: Your machine is neither big endian nor little endian.\n"; pass = false; } #if defined(CRYPTOPP_EXTENDED_VALIDATION) // App and library versions, http://github.com/weidai11/cryptopp/issues/371 const int v1 = LibraryVersion(); const int v2 = HeaderVersion(); if(v1/10 == v2/10) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "Library version (library): " << v1 << ", header version (app): " << v2 << "\n"; #endif #ifdef CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS // Don't assert the alignment of testvals. That's what this test is for. byte testvals[10] = {1,2,2,3,3,3,3,2,2,1}; if (*(word32 *)(void *)(testvals+3) == 0x03030303 && *(word64 *)(void *)(testvals+1) == W64LIT(0x0202030303030202)) std::cout << "passed: Your machine allows unaligned data access.\n"; else { std::cout << "FAILED: Unaligned data access gave incorrect results.\n"; pass = false; } #else std::cout << "passed: CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS is not defined. Will restrict to aligned data access.\n"; #endif if (sizeof(byte) == 1) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(byte) == " << sizeof(byte) << std::endl; if (sizeof(word16) == 2) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word16) == " << sizeof(word16) << std::endl; if (sizeof(word32) == 4) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word32) == " << sizeof(word32) << std::endl; if (sizeof(word64) == 8) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word64) == " << sizeof(word64) << std::endl; #ifdef CRYPTOPP_WORD128_AVAILABLE if (sizeof(word128) == 16) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(word128) == " << sizeof(word128) << std::endl; #endif if (sizeof(word) == 2*sizeof(hword) #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE && sizeof(dword) == 2*sizeof(word) #endif ) std::cout << "passed: "; else { std::cout << "FAILED: "; pass = false; } std::cout << "sizeof(hword) == " << sizeof(hword) << ", sizeof(word) == " << sizeof(word); #ifdef CRYPTOPP_NATIVE_DWORD_AVAILABLE std::cout << ", sizeof(dword) == " << sizeof(dword); #endif std::cout << std::endl; #ifdef CRYPTOPP_CPUID_AVAILABLE bool hasMMX = HasMMX(); bool hasISSE = HasISSE(); bool hasSSE2 = HasSSE2(); bool hasSSSE3 = HasSSSE3(); bool hasSSE4 = HasSSE4(); bool isP4 = IsP4(); int cacheLineSize = GetCacheLineSize(); if ((isP4 && (!hasMMX || !hasSSE2)) || (hasSSE2 && !hasMMX) || (cacheLineSize < 16 || cacheLineSize > 256 || !IsPowerOf2(cacheLineSize))) { std::cout << "FAILED: "; pass = false; } else std::cout << "passed: "; std::cout << "hasMMX == " << hasMMX << ", hasISSE == " << hasISSE << ", hasSSE2 == " << hasSSE2 << ", hasSSSE3 == " << hasSSSE3 << ", hasSSE4 == " << hasSSE4; std::cout << ", hasAESNI == " << HasAESNI() << ", hasCLMUL == " << HasCLMUL() << ", hasRDRAND == " << HasRDRAND() << ", hasRDSEED == " << HasRDSEED(); std::cout << ", hasSHA == " << HasSHA() << ", isP4 == " << isP4 << ", cacheLineSize == " << cacheLineSize << std::endl; #elif (CRYPTOPP_BOOL_ARM32 || CRYPTOPP_BOOL_ARM64) bool hasNEON = HasNEON(); bool hasPMULL = HasPMULL(); bool hasCRC32 = HasCRC32(); bool hasAES = HasAES(); bool hasSHA1 = HasSHA1(); bool hasSHA2 = HasSHA2(); std::cout << "passed: "; std::cout << "hasNEON == " << hasNEON << ", hasPMULL == " << hasPMULL << ", hasCRC32 == " << hasCRC32 << ", hasAES == " << hasAES << ", hasSHA1 == " << hasSHA1 << ", hasSHA2 == " << hasSHA2 << std::endl; #endif if (!pass) { std::cout << "Some critical setting in config.h is in error. Please fix it and recompile." << std::endl; abort(); } return pass; } bool TestOS_RNG() { bool pass = true; member_ptr<RandomNumberGenerator> rng; #ifdef BLOCKING_RNG_AVAILABLE try {rng.reset(new BlockingRng);} catch (const OS_RNG_Err &) {} #endif if (rng.get()) { std::cout << "\nTesting operating system provided blocking random number generator...\n\n"; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(*rng, UINT_MAX, false, new Deflator(new Redirector(meter))); unsigned long total=0, length=0; time_t t = time(NULLPTR), t1 = 0; CRYPTOPP_UNUSED(length); // check that it doesn't take too long to generate a reasonable amount of randomness while (total < 16 && (t1 < 10 || total*8 > (unsigned long)t1)) { test.Pump(1); total += 1; t1 = time(NULLPTR) - t; } if (total < 16) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " it took " << long(t1) << " seconds to generate " << total << " bytes" << std::endl; #if 0 // disable this part. it's causing an unpredictable pause during the validation testing if (t1 < 2) { // that was fast, are we really blocking? // first exhaust the extropy reserve t = time(NULLPTR); while (time(NULLPTR) - t < 2) { test.Pump(1); total += 1; } // if it generates too many bytes in a certain amount of time, // something's probably wrong t = time(NULLPTR); while (time(NULLPTR) - t < 2) { test.Pump(1); total += 1; length += 1; } if (length > 1024) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " it generated " << length << " bytes in " << long(time(NULLPTR) - t) << " seconds" << std::endl; } #endif test.AttachedTransformation()->MessageEnd(); if (meter.GetTotalBytes() < total) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " " << total << " generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { // Miscellaneous for code coverage RandomNumberGenerator& prng = *rng.get(); (void)prng.AlgorithmName(); word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 0); pass = true; } catch (const Exception&) { pass = false; } if (!pass) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "\nNo operating system provided blocking random number generator, skipping test." << std::endl; rng.reset(NULLPTR); #ifdef NONBLOCKING_RNG_AVAILABLE try {rng.reset(new NonblockingRng);} catch (OS_RNG_Err &) {} #endif if (rng.get()) { std::cout << "\nTesting operating system provided nonblocking random number generator...\n\n"; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(*rng, 100000, true, new Deflator(new Redirector(meter))); if (meter.GetTotalBytes() < 100000) { std::cout << "FAILED:"; pass = false; } else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { // Miscellaneous for code coverage RandomNumberGenerator& prng = *rng.get(); (void)prng.AlgorithmName(); word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 0); pass = true; } catch (const Exception&) { pass = false; } if (!pass) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "\nNo operating system provided nonblocking random number generator, skipping test." << std::endl; return pass; } bool TestRandomPool() { std::cout << "\nTesting RandomPool generator...\n\n"; bool pass=true, fail; { RandomPool prng; static const unsigned int ENTROPY_SIZE = 32; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes" << std::endl; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)prng.AlgorithmName(); // "unknown" word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } #if !defined(NO_OS_DEPENDENCE) std::cout << "\nTesting AutoSeeded RandomPool generator...\n\n"; { AutoSeededRandomPool prng; static const unsigned int ENTROPY_SIZE = 32; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes" << std::endl; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage fail = false; (void)prng.AlgorithmName(); // "unknown" word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } #endif std::cout.flush(); return pass; } #if !defined(NO_OS_DEPENDENCE) bool TestAutoSeededX917() { // This tests Auto-Seeding and GenerateIntoBufferedTransformation. std::cout << "\nTesting AutoSeeded X917 generator...\n\n"; AutoSeededX917RNG<AES> prng; bool pass = true, fail; static const unsigned int ENTROPY_SIZE = 32; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes" << std::endl; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage fail = false; (void)prng.AlgorithmName(); // "unknown" word32 result = prng.GenerateWord32(); result = prng.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result), 1); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; std::cout.flush(); return pass; } #endif #if defined(CRYPTOPP_EXTENDED_VALIDATION) bool TestMersenne() { std::cout << "\nTesting Mersenne Twister...\n\n"; static const unsigned int ENTROPY_SIZE = 32; bool pass = true, fail = false; // First 10; http://create.stephan-brumme.com/mersenne-twister/ word32 result[10], expected[10] = {0xD091BB5C, 0x22AE9EF6, 0xE7E1FAEE, 0xD5C31F79, 0x2082352C, 0xF807B7DF, 0xE9D30005, 0x3895AFE1, 0xA1E24BBA, 0x4EE4092B}; MT19937ar prng; prng.GenerateBlock(reinterpret_cast<byte*>(result), sizeof(result)); fail = (0 != ::memcmp(result, expected, sizeof(expected))); pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " Expected sequence from MT19937ar (2002 version)\n"; MeterFilter meter(new Redirector(TheBitBucket())); RandomNumberSource test(prng, 100000, true, new Deflator(new Redirector(meter))); fail = false; if (meter.GetTotalBytes() < 100000) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " 100000 generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; prng.DiscardBytes(100000); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded 10000 bytes\n"; try { fail = false; if(prng.CanIncorporateEntropy()) { SecByteBlock entropy(ENTROPY_SIZE); GlobalRNG().GenerateBlock(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); prng.IncorporateEntropy(entropy, entropy.SizeInBytes()); } } catch (const Exception& /*ex*/) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " IncorporateEntropy with " << 4*ENTROPY_SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)prng.AlgorithmName(); word32 temp = prng.GenerateWord32(); temp = prng.GenerateWord32((temp & 0xff), 0xffffffff - (temp & 0xff)); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 4); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 3); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 2); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 1); prng.GenerateBlock(reinterpret_cast<byte*>(&result[0]), 0); fail = false; } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; std::cout.flush(); return pass; } #endif #if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64) bool TestRDRAND() { std::cout << "\nTesting RDRAND generator...\n\n"; bool pass = true, fail = false; member_ptr<RandomNumberGenerator> rng; try {rng.reset(new RDRAND);} catch (const RDRAND_Err &) {} if (rng.get()) { RDRAND& rdrand = dynamic_cast<RDRAND&>(*rng.get()); static const unsigned int SIZE = 10000; MeterFilter meter(new Redirector(TheBitBucket())); Deflator deflator(new Redirector(meter)); MaurerRandomnessTest maurer; ChannelSwitch chsw; chsw.AddDefaultRoute(deflator); chsw.AddDefaultRoute(maurer); RandomNumberSource rns(rdrand, SIZE, true, new Redirector(chsw)); deflator.Flush(true); CRYPTOPP_ASSERT(0 == maurer.BytesNeeded()); const double mv = maurer.GetTestValue(); if (mv < 0.98f) fail = true; // Coverity finding, also see http://stackoverflow.com/a/34509163/608639. StreamState ss(std::cout); std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(6); pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " Maurer Randomness Test returned value " << mv << "\n"; fail = false; if (meter.GetTotalBytes() < SIZE) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " " << SIZE << " generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; rdrand.DiscardBytes(SIZE); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded " << SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)rdrand.AlgorithmName(); (void)rdrand.CanIncorporateEntropy(); rdrand.IncorporateEntropy(NULLPTR, 0); word32 result = rdrand.GenerateWord32(); result = rdrand.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 4); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 3); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 2); rdrand.GenerateBlock(reinterpret_cast<byte*>(&result), 1); fail = false; } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "RDRAND generator not available, skipping test.\n"; std::cout.flush(); return pass; } #endif #if (CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || CRYPTOPP_BOOL_X64) bool TestRDSEED() { std::cout << "\nTesting RDSEED generator...\n\n"; bool pass = true, fail = false; member_ptr<RandomNumberGenerator> rng; try {rng.reset(new RDSEED);} catch (const RDSEED_Err &) {} if (rng.get()) { RDSEED& rdseed = dynamic_cast<RDSEED&>(*rng.get()); static const unsigned int SIZE = 10000; MeterFilter meter(new Redirector(TheBitBucket())); Deflator deflator(new Redirector(meter)); MaurerRandomnessTest maurer; ChannelSwitch chsw; chsw.AddDefaultRoute(deflator); chsw.AddDefaultRoute(maurer); RandomNumberSource rns(rdseed, SIZE, true, new Redirector(chsw)); deflator.Flush(true); CRYPTOPP_ASSERT(0 == maurer.BytesNeeded()); const double mv = maurer.GetTestValue(); if (mv < 0.98f) fail = true; // Coverity finding, also see http://stackoverflow.com/a/34509163/608639. StreamState ss(std::cout); std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(6); pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " Maurer Randomness Test returned value " << mv << "\n"; fail = false; if (meter.GetTotalBytes() < SIZE) fail = true; pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " " << SIZE << " generated bytes compressed to " << meter.GetTotalBytes() << " bytes by DEFLATE\n"; try { fail = false; rdseed.DiscardBytes(SIZE); } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " discarded " << SIZE << " bytes\n"; try { // Miscellaneous for code coverage (void)rdseed.AlgorithmName(); (void)rdseed.CanIncorporateEntropy(); rdseed.IncorporateEntropy(NULLPTR, 0); word32 result = rdseed.GenerateWord32(); result = rdseed.GenerateWord32((result & 0xff), 0xffffffff - (result & 0xff)); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 4); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 3); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 2); rdseed.GenerateBlock(reinterpret_cast<byte*>(&result), 1); fail = false; } catch (const Exception&) { fail = true; } pass &= !fail; if (fail) std::cout << "FAILED:"; else std::cout << "passed:"; std::cout << " GenerateWord32 and Crop\n"; } else std::cout << "RDSEED generator not available, skipping test.\n"; std::cout.flush(); return pass; } #endif bool ValidateHashDRBG() { std::cout << "\nTesting NIST Hash DRBGs...\n\n"; bool pass=true, fail; // # CAVS 14.3 // # DRBG800-90A information for "drbg_pr" // # Generated on Tue Apr 02 15:32:09 2013 { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x16\x10\xb8\x28\xcc\xd2\x7d\xe0\x8c\xee\xa0\x32\xa2\x0e\x92\x08"; const byte entropy2[] = "\x72\xd2\x8c\x90\x8e\xda\xf9\xa4\xd1\xe5\x26\xd8\xf2\xde\xd5\x44"; const byte nonce[] = "\x49\x2c\xf1\x70\x92\x42\xf6\xb5"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\x56\xF3\x3D\x4F\xDB\xB9\xA5\xB6\x4D\x26\x23\x44\x97\xE9\xDC\xB8\x77\x98\xC6\x8D" "\x08\xF7\xC4\x11\x99\xD4\xBD\xDF\x97\xEB\xBF\x6C\xB5\x55\x0E\x5D\x14\x9F\xF4\xD5" "\xBD\x0F\x05\xF2\x5A\x69\x88\xC1\x74\x36\x39\x62\x27\x18\x4A\xF8\x4A\x56\x43\x35" "\x65\x8E\x2F\x85\x72\xBE\xA3\x33\xEE\xE2\xAB\xFF\x22\xFF\xA6\xDE\x3E\x22\xAC\xA2"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (COUNT=0, E=16, N=8)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x55\x08\x75\xb7\x4e\xc1\x1f\x90\x67\x78\xa3\x1a\x37\xa3\x29\xfd"; const byte entropy2[] = "\x96\xc6\x39\xec\x14\x9f\x6b\x28\xe2\x79\x3b\xb9\x37\x9e\x60\x67"; const byte nonce[] = "\x08\xdd\x8c\xd3\x5b\xfa\x00\x94"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\xEE\x44\xC6\xCF\x2C\x0C\x73\xA8\xAC\x4C\xA5\x6C\x0E\x71\x2C\xA5\x50\x9A\x19\x5D" "\xE4\x5B\x8D\x2B\xC9\x40\xA7\xDB\x66\xC3\xEB\x2A\xA1\xBD\xB4\xDD\x76\x85\x12\x45" "\x80\x2E\x68\x05\x4A\xAB\xA8\x7C\xD6\x3A\xD3\xE5\xC9\x7C\x06\xE7\xA3\x9F\xF6\xF9" "\x8E\xB3\xD9\x72\xD4\x11\x35\xE5\xE7\x46\x1B\x49\x9C\x56\x45\x6A\xBE\x7F\x77\xD4"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (COUNT=1, E=16, N=8)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 128], [ReturnedBitsLen = 640] const byte entropy1[] = "\xd9\xba\xb5\xce\xdc\xa9\x6f\x61\x78\xd6\x45\x09\xa0\xdf\xdc\x5e"; const byte entropy2[] = "\xc6\xba\xd0\x74\xc5\x90\x67\x86\xf5\xe1\xf3\x20\x99\xf5\xb4\x91"; const byte nonce[] = "\xda\xd8\x98\x94\x14\x45\x0e\x01"; const byte additional1[] = "\x3e\x6b\xf4\x6f\x4d\xaa\x38\x25\xd7\x19\x4e\x69\x4e\x77\x52\xf7"; const byte additional2[] = "\x04\xfa\x28\x95\xaa\x5a\x6f\x8c\x57\x43\x34\x3b\x80\x5e\x5e\xa4"; const byte additional3[] = "\xdf\x5d\xc4\x59\xdf\xf0\x2a\xa2\xf0\x52\xd7\x21\xec\x60\x72\x30"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\xC4\x8B\x89\xF9\xDA\x3F\x74\x82\x45\x55\x5D\x5D\x03\x3B\x69\x3D\xD7\x1A\x4D\xF5" "\x69\x02\x05\xCE\xFC\xD7\x20\x11\x3C\xC2\x4E\x09\x89\x36\xFF\x5E\x77\xB5\x41\x53" "\x58\x70\xB3\x39\x46\x8C\xDD\x8D\x6F\xAF\x8C\x56\x16\x3A\x70\x0A\x75\xB2\x3E\x59" "\x9B\x5A\xEC\xF1\x6F\x3B\xAF\x6D\x5F\x24\x19\x97\x1F\x24\xF4\x46\x72\x0F\xEA\xBE"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=0, E=16, N=8, A=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 128], [ReturnedBitsLen = 640] const byte entropy1[] = "\x28\x00\x0f\xbf\xf0\x57\x22\xc8\x89\x93\x06\xc2\x9b\x50\x78\x0a"; const byte entropy2[] = "\xd9\x95\x8e\x8c\x08\xaf\x5a\x41\x0e\x91\x9b\xdf\x40\x8e\x5a\x0a"; const byte nonce[] = "\x11\x2f\x6e\x20\xc0\x29\xed\x3f"; const byte additional1[] = "\x91\x1d\x96\x5b\x6e\x77\xa9\x6c\xfe\x3f\xf2\xd2\xe3\x0e\x2a\x86"; const byte additional2[] = "\xcd\x44\xd9\x96\xab\x05\xef\xe8\x27\xd3\x65\x83\xf1\x43\x18\x2c"; const byte additional3[] = "\x9f\x6a\x31\x82\x12\x18\x4e\x70\xaf\x5d\x00\x14\x1f\x42\x82\xf6"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\x54\x61\x65\x92\x1E\x71\x4A\xD1\x39\x02\x2F\x97\xD2\x65\x3F\x0D\x47\x69\xB1\x4A" "\x3E\x6E\xEF\xA1\xA0\x16\xD6\x9E\xA9\x7F\x51\xD5\x81\xDC\xAA\xCF\x66\xF9\xB1\xE8" "\x06\x94\x41\xD6\xB5\xC5\x44\x60\x54\x07\xE8\xE7\xDC\x1C\xD8\xE4\x70\xAD\x84\x77" "\x5A\x65\x31\xBE\xE0\xFC\x81\x36\xE2\x8F\x0B\xFE\xEB\xE1\x98\x62\x7E\x98\xE0\xC1"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=1, E=16, N=8, A=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x0e\xd5\x4c\xef\x44\x5c\x61\x7d\x58\x86\xe0\x34\xc0\x97\x36\xd4"; const byte entropy2[] = "\x0b\x90\x27\xb8\x01\xe7\xf7\x2e\xe6\xec\x50\x2b\x8b\x6b\xd7\x11"; const byte nonce[] = "\x2c\x8b\x07\x13\x55\x6c\x91\x6f"; const byte personalization[] = "\xf3\x37\x8e\xa1\x45\x34\x30\x41\x12\xe0\xee\x57\xe9\xb3\x4a\x4b"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\x55\x37\x0E\xD4\xB7\xCA\xA4\xBB\x67\x3A\x0F\x58\x40\xB3\x9F\x76\x4E\xDA\xD2\x85" "\xD5\x6F\x01\x8F\x2D\xA7\x54\x4B\x0E\x66\x39\x62\x35\x96\x1D\xB7\xF6\xDA\xFB\x30" "\xB6\xC5\x68\xD8\x40\x6E\x2B\xD4\x3D\x23\xEB\x0F\x10\xBA\x5F\x24\x9C\xC9\xE9\x4A" "\xD3\xA5\xF1\xDF\xA4\xF2\xB4\x80\x40\x91\xED\x8C\xD6\x6D\xE7\xB7\x53\xB2\x09\xD5"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=0, E=16, N=8, A=0, P=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x8f\x2a\x33\x9f\x5f\x45\x21\x30\xa4\x57\xa9\x6f\xcb\xe2\xe6\x36"; const byte entropy2[] = "\x1f\xff\x9e\x4f\x4d\x66\x3a\x1f\x9e\x85\x4a\x15\x7d\xad\x97\xe0"; const byte nonce[] = "\x0e\xd0\xe9\xa5\xa4\x54\x8a\xd0"; const byte personalization[] = "\x45\xe4\xb3\xe2\x63\x87\x62\x57\x2c\x99\xe4\x03\x45\xd6\x32\x6f"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\x4F\xE8\x96\x41\xF8\xD3\x95\xC4\x43\x6E\xFB\xF8\x05\x75\xA7\x69\x74\x6E\x0C\x5F" "\x54\x14\x35\xB4\xE6\xA6\xB3\x40\x7C\xA2\xC4\x42\xA2\x2F\x66\x28\x28\xCF\x4A\xA8" "\xDC\x16\xBC\x5F\x69\xE5\xBB\x05\xD1\x43\x8F\x80\xAB\xC5\x8F\x9C\x3F\x75\x57\xEB" "\x44\x0D\xF5\x0C\xF4\x95\x23\x94\x67\x11\x55\x98\x14\x43\xFF\x13\x14\x85\x5A\xBC"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=1, E=16, N=8, A=0, P=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x48\xa1\xa9\x7c\xcc\x49\xd7\xcc\xf6\xe3\x78\xa2\xf1\x6b\x0f\xcd"; const byte entropy2[] = "\xba\x5d\xa6\x79\x12\x37\x24\x3f\xea\x60\x50\xf5\xb9\x9e\xcd\xf5"; const byte nonce[] = "\xb0\x91\xd2\xec\x12\xa8\x39\xfe"; const byte personalization[] = "\x3d\xc1\x6c\x1a\xdd\x9c\xac\x4e\xbb\xb0\xb8\x89\xe4\x3b\x9e\x12"; const byte additional1[] = "\xd1\x23\xe3\x8e\x4c\x97\xe8\x29\x94\xa9\x71\x7a\xc6\xf1\x7c\x08"; const byte additional2[] = "\x80\x0b\xed\x97\x29\xcf\xad\xe6\x68\x0d\xfe\x53\xba\x0c\x1e\x28"; const byte additional3[] = "\x25\x1e\x66\xb9\xe3\x85\xac\x1c\x17\xfb\x77\x1b\x5d\xc7\x6c\xf2"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\xA1\xB2\xEE\x86\xA0\xF1\xDA\xB7\x93\x83\x13\x3A\x62\x27\x99\x08\x95\x3A\x1C\x9A" "\x98\x77\x60\x12\x11\x19\xCC\x78\xB8\x51\x2B\xD5\x37\xA1\x9D\xB9\x73\xCA\x39\x7A" "\xDD\x92\x33\x78\x6D\x5D\x41\xFF\xFA\xE9\x80\x59\x04\x85\x21\xE2\x52\x84\xBC\x6F" "\xDB\x97\xF3\x4E\x6A\x12\x7A\xCD\x41\x0F\x50\x68\x28\x46\xBE\x56\x9E\x9A\x6B\xC8"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=0, E=16, N=8, A=16, P=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 128], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x3b\xcb\xa8\x3b\x6d\xfb\x06\x79\x80\xef\xc3\x1e\xd2\x9e\x68\x57"; const byte entropy2[] = "\x2f\xc9\x87\x49\x19\xcb\x52\x4a\x5b\xac\xf0\xcd\x96\x4e\xf8\x6e"; const byte nonce[] = "\x23\xfe\x20\x9f\xac\x70\x45\xde"; const byte personalization[] = "\xf2\x25\xf4\xd9\x6b\x9c\xab\x49\x1e\xab\x18\x14\xb2\x5e\x78\xef"; const byte additional1[] = "\x57\x5b\x9a\x11\x32\x7a\xab\x89\x08\xfe\x46\x11\x9a\xed\x14\x5d"; const byte additional2[] = "\x5d\x19\xcd\xed\xb7\xe3\x44\x66\x8e\x11\x42\x96\xa0\x38\xb1\x7f"; const byte additional3[] = "\x2b\xaf\xa0\x15\xed\xdd\x5c\x76\x32\x75\x34\x35\xd1\x37\x72\xfb"; Hash_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8, personalization, 16); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\x1D\x12\xEB\x6D\x42\x60\xBD\xFB\xA7\x99\xB8\x53\xCC\x6F\x19\xB1\x64\xFE\x2F\x55" "\xBA\xA2\x1C\x89\xD4\xD0\xE9\xB4\xBA\xD4\xE5\xF8\xC5\x30\x06\x41\xBA\xC4\x3D\x2B" "\x73\x91\x27\xE9\x31\xC0\x55\x55\x11\xE8\xB6\x57\x02\x0D\xCE\x90\xAC\x31\xB9\x00" "\x31\xC1\xD4\x4F\xE7\x12\x3B\xCC\x85\x16\x2F\x12\x8F\xB2\xDF\x84\x4E\xF7\x06\xBE"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA1/128/440 (C0UNT=1, E=16, N=8, A=16, P=16)\n"; } { // [SHA-256], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 1024] const byte entropy1[] = "\xf0\x5b\xab\x56\xc7\xac\x6e\xeb\x31\xa0\xcf\x8a\x8a\x06\x2a\x49\x17\x9a\xcf\x3c\x5b\x20\x4d\x60\xdd\x7a\x3e\xb7\x8f\x5d\x8e\x3b"; const byte entropy2[] = "\x72\xd4\x02\xa2\x59\x7b\x98\xa3\xb8\xf5\x0b\x71\x6c\x63\xc6\xdb\xa7\x3a\x07\xe6\x54\x89\x06\x3f\x02\xc5\x32\xf5\xda\xc4\xd4\x18"; const byte nonce[] = "\xa1\x45\x08\x53\x41\x68\xb6\x88\xf0\x5f\x1e\x41\x9c\x88\xcc\x30"; const byte personalization[] = "\xa0\x34\x72\xf4\x04\x59\xe2\x87\xea\xcb\x21\x32\xc0\xb6\x54\x02\x7d\xa3\xe6\x69\x25\xb4\x21\x25\x54\xc4\x48\x18\x8c\x0e\x86\x01"; const byte additional1[] = "\xb3\x0d\x28\xaf\xa4\x11\x6b\xbc\x13\x6e\x65\x09\xb5\x82\xa6\x93\xbc\x91\x71\x40\x46\xaa\x3c\x66\xb6\x77\xb3\xef\xf9\xad\xfd\x49"; const byte additional2[] = "\x77\xfd\x1d\x68\xd6\xa4\xdd\xd5\xf3\x27\x25\x2d\x3f\x6b\xdf\xee\x8c\x35\xce\xd3\x83\xbe\xaf\xc9\x32\x77\xef\xf2\x1b\x6f\xf4\x1b"; const byte additional3[] = "\x59\xa0\x1f\xf8\x6a\x58\x72\x1e\x85\xd2\xf8\x3f\x73\x99\xf1\x96\x4e\x27\xf8\x7f\xcd\x1b\xf5\xc1\xeb\xf3\x37\x10\x9b\x13\xbd\x24"; Hash_DRBG<SHA256, 128/8, 440/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(128); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\xFF\x27\x96\x38\x5C\x32\xBF\x84\x3D\xFA\xBB\xF0\x3E\x70\x5A\x39\xCB\xA3\x4C\xF1" "\x4F\xAE\xC3\x05\x63\xDF\x5A\xDD\xBD\x2D\x35\x83\xF5\x7E\x05\xF9\x40\x30\x56\x18" "\xF2\x00\x88\x14\x03\xC2\xD9\x81\x36\x39\xE6\x67\x55\xDC\xFC\x4E\x88\xEA\x71\xDD" "\xB2\x25\x2E\x09\x91\x49\x40\xEB\xE2\x3D\x63\x44\xA0\xF4\xDB\x5E\xE8\x39\xE6\x70" "\xEC\x47\x24\x3F\xA0\xFC\xF5\x13\x61\xCE\x53\x98\xAA\xBF\xB4\x19\x1B\xFE\xD5\x00" "\xE1\x03\x3A\x76\x54\xFF\xD7\x24\x70\x5E\x8C\xB2\x41\x7D\x92\x0A\x2F\x4F\x27\xB8" "\x45\x13\x7F\xFB\x87\x90\xA9\x49"; fail = !!memcmp(result, expected, 1024/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA256/128/440 (C0UNT=0, E=32, N=16, A=32, P=32)\n"; } { // [SHA-256], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 1024] const byte entropy1[] = "\xfe\x61\x50\x79\xf1\xad\x2a\x71\xea\x7f\x0f\x5a\x14\x34\xee\xc8\x46\x35\x54\x4a\x95\x6a\x4f\xbd\x64\xff\xba\xf6\x1d\x34\x61\x83"; const byte entropy2[] = "\x18\x89\x7b\xd8\x3e\xff\x38\xab\xb5\x6e\x82\xa8\x1b\x8c\x5e\x59\x3c\x3d\x85\x62\x2a\xe2\x88\xe5\xb2\xc6\xc5\xd2\xad\x7d\xc9\x45"; const byte nonce[] = "\x9d\xa7\x87\x56\xb7\x49\x17\x02\x4c\xd2\x00\x65\x11\x9b\xe8\x7e"; const byte personalization[] = "\x77\x5d\xbf\x32\xf3\x5c\xf3\x51\xf4\xb8\x1c\xd3\xfa\x7f\x65\x0b\xcf\x31\x88\xa1\x25\x57\x0c\xdd\xac\xaa\xfe\xa1\x7b\x3b\x29\xbc"; const byte additional1[] = "\xef\x96\xc7\x9c\xb1\x73\x1d\x82\x85\x0a\x6b\xca\x9b\x5c\x34\x39\xba\xd3\x4e\x4d\x82\x6f\x35\x9f\x61\x5c\xf6\xf2\xa3\x3e\x91\x05"; const byte additional2[] = "\xaf\x25\xc4\x6e\x21\xfc\xc3\xaf\x1f\xbb\xf8\x76\xb4\x57\xab\x1a\x94\x0a\x85\x16\x47\x81\xa4\xab\xda\xc8\xab\xca\xd0\x84\xda\xae"; const byte additional3[] = "\x59\x5b\x44\x94\x38\x86\x36\xff\x8e\x45\x1a\x0c\x42\xc8\xcc\x21\x06\x38\x3a\xc5\xa6\x30\x96\xb9\x14\x81\xb3\xa1\x2b\xc8\xcd\xf6"; Hash_DRBG<SHA256, 128/8, 440/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(128); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\x8B\x1C\x9C\x76\xC4\x9B\x3B\xAE\xFD\x6E\xEB\x6C\xFF\xA3\xA1\x03\x3A\x8C\xAF\x09" "\xFE\xBD\x44\x00\xFC\x0F\xD3\xA8\x26\x9C\xEE\x01\xAC\xE3\x73\x0E\xBE\xDA\x9A\xC6" "\x23\x44\x6D\xA1\x56\x94\x29\xEC\x4B\xCD\x01\x84\x32\x25\xEF\x00\x91\x0B\xCC\xF3" "\x06\x3B\x80\xF5\x46\xAC\xD2\xED\x5F\x70\x2B\x56\x2F\x21\x0A\xE9\x80\x87\x38\xAD" "\xB0\x2A\xEB\x27\xF2\xD9\x20\x2A\x66\x0E\xF5\xC9\x20\x4A\xB4\x3C\xCE\xD6\x24\x97" "\xDB\xB1\xED\x94\x12\x6A\x2F\x03\x98\x4A\xD4\xD1\x72\xF3\x7A\x66\x74\x7E\x2A\x5B" "\xDE\xEF\x43\xBC\xB9\x8C\x49\x01"; fail = !!memcmp(result, expected, 1024/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA256/128/440 (C0UNT=1, E=32, N=16, A=32, P=32)\n"; } { // [SHA-512], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 2048] const byte entropy1[] = "\x55\x4e\x8f\xfd\xc4\x9a\xd8\xf9\x9a\xe5\xd5\xf8\x1a\xf5\xda\xfb\x7f\x75\x53\xd7\xcb\x56\x8e\xa7\x3c\xc0\x82\xdd\x80\x76\x25\xc0"; const byte entropy2[] = "\x78\x07\x3e\x86\x79\x4b\x10\x95\x88\xf4\x22\xf9\xbd\x04\x7e\xc0\xce\xab\xd6\x78\x6b\xdf\xe2\x89\xb3\x16\x43\x9c\x32\x2d\xb2\x59"; const byte nonce[] = "\xf0\x89\x78\xde\x2d\xc2\xcd\xd9\xc0\xfd\x3d\x84\xd9\x8b\x8e\x8e"; const byte personalization[] = "\x3e\x52\x7a\xb5\x81\x2b\x0c\x0e\x98\x2a\x95\x78\x93\x98\xd9\xeb\xf1\xb9\xeb\xd6\x1d\x02\x05\xed\x42\x21\x2d\x24\xb8\x37\xf8\x41"; const byte additional1[] = "\xf2\x6b\xb1\xef\x30\xca\x8f\x97\xc0\x19\xd0\x79\xe5\xc6\x5e\xae\xd1\xa3\x9a\x52\xaf\x12\xe8\x28\xde\x03\x70\x79\x9a\x70\x11\x8b"; const byte additional2[] = "\xb0\x9d\xb5\xa8\x45\xec\x79\x7a\x4b\x60\x7e\xe4\xd5\x58\x56\x70\x35\x20\x9b\xd8\xe5\x01\x6c\x78\xff\x1f\x6b\x93\xbf\x7c\x34\xca"; const byte additional3[] = "\x45\x92\x2f\xb3\x5a\xd0\x6a\x84\x5f\xc9\xca\x16\x4a\x42\xbb\x59\x84\xb4\x38\x57\xa9\x16\x23\x48\xf0\x2f\x51\x61\x24\x35\xb8\x62"; Hash_DRBG<SHA512, 256/8, 888/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(256); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\x1F\x20\x83\x9E\x22\x55\x3B\x1E\x6C\xD4\xF6\x3A\x47\xC3\x99\x54\x0F\x69\xA3\xBB" "\x37\x47\xA0\x2A\x12\xAC\xC7\x00\x85\xC5\xCC\xF4\x7B\x12\x5A\x4A\xEA\xED\x2F\xE5" "\x31\x51\x0D\xC1\x8E\x50\x29\xE2\xA6\xCB\x8F\x34\xBA\xDA\x8B\x47\x32\x33\x81\xF1" "\x2D\xF6\x8B\x73\x8C\xFF\x15\xC8\x8E\x8C\x31\x48\xFA\xC3\xC4\x9F\x52\x81\x23\xC2" "\x2A\x83\xBD\xF1\x44\xEF\x15\x49\x93\x44\x83\x6B\x37\x5D\xBB\xFF\x72\xD2\x86\x96" "\x62\xF8\x4D\x12\x3B\x16\xCB\xAC\xA1\x00\x12\x1F\x94\xA8\xD5\xAE\x9A\x9E\xDA\xC8" "\xD7\x6D\x59\x33\xFD\x55\xC9\xCC\x5B\xAD\x39\x73\xB5\x13\x8B\x96\xDF\xDB\xF5\x90" "\x81\xDF\x68\x6A\x30\x72\x42\xF2\x74\xAE\x7F\x1F\x7F\xFE\x8B\x3D\x49\x38\x98\x34" "\x7C\x63\x46\x6E\xAF\xFA\xCB\x06\x06\x08\xE6\xC8\x35\x3C\x68\xB8\xCC\x9D\x5C\xDF" "\xDB\xC0\x41\x44\x48\xE6\x11\xD4\x78\x50\x81\x91\xED\x1D\x75\xF3\xBD\x79\xFF\x1E" "\x37\xAF\xC6\x5D\x49\xD6\x5C\xAC\x5B\xCB\xD6\x91\x37\x51\xFA\x98\x70\xFC\x32\xB3" "\xF2\x86\xE4\xED\x74\xF2\x5D\x8B\x6C\x4D\xB8\xDE\xD8\x4A\xD6\x5E\xD6\x6D\xAE\xB1" "\x1B\xA2\x94\x52\x54\xAD\x3C\x3D\x25\xBD\x12\x46\x3C\xA0\x45\x9D"; fail = !!memcmp(result, expected, 2048/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA512/256/888 (C0UNT=0, E=32, N=16, A=32, P=32)\n"; } { // [SHA-512], [PredictionResistance = False], [EntropyInputLen = 256], [NonceLen = 128] // [PersonalizationStringLen = 256], [AdditionalInputLen = 256], [ReturnedBitsLen = 2048] const byte entropy1[] = "\x0c\x9f\xcd\x06\x21\x3c\xb2\xf6\x3c\xdf\x79\x76\x4b\x46\x74\xfc\xdf\x68\xb0\xff\xae\xc7\x21\x8a\xa2\xaf\x4e\x4c\xb9\xe6\x60\x78"; const byte entropy2[] = "\x75\xb8\x49\x54\xdf\x30\x10\x16\x2c\x06\x8c\x12\xeb\x6c\x1d\x03\x64\x5c\xad\x10\x5c\xc3\x17\x69\xb2\x5a\xc1\x7c\xb8\x33\x5b\x45"; const byte nonce[] = "\x43\x1c\x4d\x65\x93\x96\xad\xdc\xc1\x6d\x17\x9f\x7f\x57\x24\x4d"; const byte personalization[] = "\x7e\x54\xbd\x87\xd2\x0a\x95\xd7\xc4\x0c\x3b\x1b\x32\x15\x26\xd2\x06\x67\xa4\xac\xc1\xaa\xfb\x55\x91\x68\x2c\xb5\xc9\xcd\x66\x05"; const byte additional1[] = "\xd5\x74\x9e\x56\xfb\x5f\xf3\xf8\x2c\x73\x2b\x7a\x83\xe0\xde\x06\x85\x0b\xf0\x57\x50\xc8\x55\x60\x4a\x41\x4f\x86\xb1\x68\x14\x03"; const byte additional2[] = "\x9a\x83\xbb\x06\xdf\x4d\x53\x89\xf5\x3f\x24\xff\xf7\xcd\x0c\xcf\x4f\xbe\x46\x79\x8e\xce\x82\xa8\xc4\x6b\x5f\x8e\x58\x32\x62\x23"; const byte additional3[] = "\x48\x13\xc4\x95\x10\x99\xdd\x7f\xd4\x77\x3c\x9b\x8a\xa4\x1c\x3d\xb0\x93\x92\x50\xba\x23\x98\xef\x4b\x1b\xd2\x53\xc1\x61\xda\xc6"; Hash_DRBG<SHA512, 256/8, 888/8> drbg(entropy1, 32, nonce, 16, personalization, 32); drbg.IncorporateEntropy(entropy2, 32, additional1, 32); SecByteBlock result(256); drbg.GenerateBlock(additional2, 32, result, result.size()); drbg.GenerateBlock(additional3, 32, result, result.size()); const byte expected[] = "\xE1\x7E\x4B\xEE\xD1\x65\x4F\xB2\xFC\xC8\xE8\xD7\xC6\x72\x7D\xD2\xE3\x15\x73\xC0" "\x23\xC8\x55\x5D\x2B\xD8\x28\xD8\x31\xE4\xC9\x87\x42\x51\x87\x66\x43\x1F\x2C\xA4" "\x73\xED\x4E\x50\x12\xC4\x50\x0E\x4C\xDD\x14\x73\xA2\xFB\xB3\x07\x0C\x66\x97\x4D" "\x89\xDE\x35\x1C\x93\xE7\xE6\x8F\x20\x3D\x84\xE6\x73\x46\x0F\x7C\xF4\x3B\x6C\x02" "\x23\x7C\x79\x6C\x86\xD9\x48\x80\x9C\x34\xCB\xA1\x23\xE7\xF7\x8A\x2E\x4B\x9D\x39" "\xA5\x86\x1A\x73\x58\x28\x5A\x1D\x8D\x4A\xBD\x42\xD5\x49\x2B\xDF\x53\x1D\xE7\x4A" "\x5F\x74\x09\x7F\xDC\x29\x7D\x58\x9C\x4B\xC5\x2F\x3B\x8F\xBF\x56\xCA\x48\x0A\x74" "\xAE\xFF\xDD\x12\xE4\xF6\xAB\x83\x26\x4F\x52\x8A\x19\xBB\x91\x32\xA4\x42\xEC\x4F" "\x3C\x76\xED\x9F\x03\xAA\x5E\x53\x79\x4C\xD0\x06\xD2\x1A\x42\x9D\xB1\xA7\xEC\xF7" "\x5B\xD4\x03\x70\x1E\xF2\x47\x26\x48\xAC\x35\xEE\xD0\x58\x40\x94\x8C\x11\xD0\xEB" "\x77\x39\x5A\xA3\xD5\xD0\xD3\xC3\x68\xE1\x75\xAA\xC0\x44\xEA\xD8\xDD\x13\x3F\xF9" "\x7D\x21\x14\x34\xA5\x87\x43\xA4\x0A\x96\x77\x00\xCC\xCA\xB1\xDA\xC4\x39\xE0\x66" "\x37\x05\x6E\xAC\xF2\xE6\xC6\xC5\x4F\x79\xD3\xE5\x6A\x3D\x36\x3F"; fail = !!memcmp(result, expected, 2048/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "Hash_DRBG SHA512/256/888 (C0UNT=1, E=32, N=16, A=32, P=32)\n"; } return pass; } bool ValidateHmacDRBG() { std::cout << "\nTesting NIST HMAC DRBGs...\n\n"; bool pass=true, fail; // # CAVS 14.3 // # DRBG800-90A information for "drbg_pr" // # Generated on Tue Apr 02 15:32:12 2013 { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\x79\x34\x9b\xbf\x7c\xdd\xa5\x79\x95\x57\x86\x66\x21\xc9\x13\x83"; const byte entropy2[] = "\xc7\x21\x5b\x5b\x96\xc4\x8e\x9b\x33\x8c\x74\xe3\xe9\x9d\xfe\xdf"; const byte nonce[] = "\x11\x46\x73\x3a\xbf\x8c\x35\xc8"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\xc6\xa1\x6a\xb8\xd4\x20\x70\x6f\x0f\x34\xab\x7f\xec\x5a\xdc\xa9\xd8\xca\x3a\x13" "\x3e\x15\x9c\xa6\xac\x43\xc6\xf8\xa2\xbe\x22\x83\x4a\x4c\x0a\x0a\xff\xb1\x0d\x71" "\x94\xf1\xc1\xa5\xcf\x73\x22\xec\x1a\xe0\x96\x4e\xd4\xbf\x12\x27\x46\xe0\x87\xfd" "\xb5\xb3\xe9\x1b\x34\x93\xd5\xbb\x98\xfa\xed\x49\xe8\x5f\x13\x0f\xc8\xa4\x59\xb7"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=0, E=16, N=8)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 0], [ReturnedBitsLen = 640] const byte entropy1[] = "\xee\x57\xfc\x23\x60\x0f\xb9\x02\x9a\x9e\xc6\xc8\x2e\x7b\x51\xe4"; const byte entropy2[] = "\x84\x1d\x27\x6c\xa9\x51\x90\x61\xd9\x2d\x7d\xdf\xa6\x62\x8c\xa3"; const byte nonce[] = "\x3e\x97\x21\xe4\x39\x3e\xf9\xad"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16); SecByteBlock result(80); drbg.GenerateBlock(result, result.size()); drbg.GenerateBlock(result, result.size()); const byte expected[] = "\xee\x26\xa5\xc8\xef\x08\xa1\xca\x8f\x14\x15\x4d\x67\xc8\x8f\x5e\x7e\xd8\x21\x9d" "\x93\x1b\x98\x42\xac\x00\x39\xf2\x14\x55\x39\xf2\x14\x2b\x44\x11\x7a\x99\x8c\x22" "\xf5\x90\xf6\xc9\xb3\x8b\x46\x5b\x78\x3e\xcf\xf1\x3a\x77\x50\x20\x1f\x7e\xcf\x1b" "\x8a\xb3\x93\x60\x4c\x73\xb2\x38\x93\x36\x60\x9a\xf3\x44\x0c\xde\x43\x29\x8b\x84"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=1, E=16, N=8)\n"; } // ***************************************************** { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x7d\x70\x52\xa7\x76\xfd\x2f\xb3\xd7\x19\x1f\x73\x33\x04\xee\x8b"; const byte entropy2[] = "\x49\x04\x7e\x87\x9d\x61\x09\x55\xee\xd9\x16\xe4\x06\x0e\x00\xc9"; const byte nonce[] = "\xbe\x4a\x0c\xee\xdc\xa8\x02\x07"; const byte additional1[] = "\xfd\x8b\xb3\x3a\xab\x2f\x6c\xdf\xbc\x54\x18\x11\x86\x1d\x51\x8d"; const byte additional2[] = "\x99\xaf\xe3\x47\x54\x04\x61\xdd\xf6\xab\xeb\x49\x1e\x07\x15\xb4"; const byte additional3[] = "\x02\xf7\x73\x48\x2d\xd7\xae\x66\xf7\x6e\x38\x15\x98\xa6\x4e\xf0"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\xa7\x36\x34\x38\x44\xfc\x92\x51\x13\x91\xdb\x0a\xdd\xd9\x06\x4d\xbe\xe2\x4c\x89" "\x76\xaa\x25\x9a\x9e\x3b\x63\x68\xaa\x6d\xe4\xc9\xbf\x3a\x0e\xff\xcd\xa9\xcb\x0e" "\x9d\xc3\x36\x52\xab\x58\xec\xb7\x65\x0e\xd8\x04\x67\xf7\x6a\x84\x9f\xb1\xcf\xc1" "\xed\x0a\x09\xf7\x15\x50\x86\x06\x4d\xb3\x24\xb1\xe1\x24\xf3\xfc\x9e\x61\x4f\xcb"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=0, E=16, N=8, A=16)\n"; } { // [SHA-1], [PredictionResistance = False], [EntropyInputLen = 128], [NonceLen = 64] // [PersonalizationStringLen = 0], [AdditionalInputLen = 16], [ReturnedBitsLen = 640] const byte entropy1[] = "\x29\xc6\x2a\xfa\x3c\x52\x20\x8a\x3f\xde\xcb\x43\xfa\x61\x3f\x15"; const byte entropy2[] = "\xbd\x87\xbe\x99\xd1\x84\x16\x54\x12\x31\x41\x40\xd4\x02\x71\x41"; const byte nonce[] = "\x6c\x9e\xb5\x9a\xc3\xc2\xd4\x8b"; const byte additional1[] = "\x43\x3d\xda\xf2\x59\xd1\x4b\xcf\x89\x76\x30\xcc\xaa\x27\x33\x8c"; const byte additional2[] = "\x14\x11\x46\xd4\x04\xf2\x84\xc2\xd0\x2b\x6a\x10\x15\x6e\x33\x82"; const byte additional3[] = "\xed\xc3\x43\xdb\xff\xe7\x1a\xb4\x11\x4a\xc3\x63\x9d\x44\x5b\x65"; HMAC_DRBG<SHA1, 128/8, 440/8> drbg(entropy1, 16, nonce, 8); drbg.IncorporateEntropy(entropy2, 16, additional1, 16); SecByteBlock result(80); drbg.GenerateBlock(additional2, 16, result, result.size()); drbg.GenerateBlock(additional3, 16, result, result.size()); const byte expected[] = "\x8c\x73\x0f\x05\x26\x69\x4d\x5a\x9a\x45\xdb\xab\x05\x7a\x19\x75\x35\x7d\x65\xaf" "\xd3\xef\xf3\x03\x32\x0b\xd1\x40\x61\xf9\xad\x38\x75\x91\x02\xb6\xc6\x01\x16\xf6" "\xdb\x7a\x6e\x8e\x7a\xb9\x4c\x05\x50\x0b\x4d\x1e\x35\x7d\xf8\xe9\x57\xac\x89\x37" "\xb0\x5f\xb3\xd0\x80\xa0\xf9\x06\x74\xd4\x4d\xe1\xbd\x6f\x94\xd2\x95\xc4\x51\x9d"; fail = !!memcmp(result, expected, 640/8); pass = !fail && pass; std::cout << (fail ? "FAILED " : "passed ") << "HMAC_DRBG SHA1/128/440 (COUNT=1, E=16, N=8, A=16)\n"; } return pass; } class CipherFactory { public: virtual unsigned int BlockSize() const =0; virtual unsigned int KeyLength() const =0; virtual BlockTransformation* NewEncryption(const byte *keyStr) const =0; virtual BlockTransformation* NewDecryption(const byte *keyStr) const =0; }; template <class E, class D> class FixedRoundsCipherFactory : public CipherFactory { public: FixedRoundsCipherFactory(unsigned int keylen=0) : m_keylen(keylen?keylen:E::DEFAULT_KEYLENGTH) {} unsigned int BlockSize() const {return E::BLOCKSIZE;} unsigned int KeyLength() const {return m_keylen;} BlockTransformation* NewEncryption(const byte *keyStr) const {return new E(keyStr, m_keylen);} BlockTransformation* NewDecryption(const byte *keyStr) const {return new D(keyStr, m_keylen);} unsigned int m_keylen; }; template <class E, class D> class VariableRoundsCipherFactory : public CipherFactory { public: VariableRoundsCipherFactory(unsigned int keylen=0, unsigned int rounds=0) : m_keylen(keylen ? keylen : E::DEFAULT_KEYLENGTH), m_rounds(rounds ? rounds : E::DEFAULT_ROUNDS) {} unsigned int BlockSize() const {return E::BLOCKSIZE;} unsigned int KeyLength() const {return m_keylen;} BlockTransformation* NewEncryption(const byte *keyStr) const {return new E(keyStr, m_keylen, m_rounds);} BlockTransformation* NewDecryption(const byte *keyStr) const {return new D(keyStr, m_keylen, m_rounds);} unsigned int m_keylen, m_rounds; }; bool BlockTransformationTest(const CipherFactory &cg, BufferedTransformation &valdata, unsigned int tuples = 0xffff) { HexEncoder output(new FileSink(std::cout)); SecByteBlock plain(cg.BlockSize()), cipher(cg.BlockSize()), out(cg.BlockSize()), outplain(cg.BlockSize()); SecByteBlock key(cg.KeyLength()); bool pass=true, fail; while (valdata.MaxRetrievable() && tuples--) { valdata.Get(key, cg.KeyLength()); valdata.Get(plain, cg.BlockSize()); valdata.Get(cipher, cg.BlockSize()); member_ptr<BlockTransformation> transE(cg.NewEncryption(key)); transE->ProcessBlock(plain, out); fail = memcmp(out, cipher, cg.BlockSize()) != 0; member_ptr<BlockTransformation> transD(cg.NewDecryption(key)); transD->ProcessBlock(out, outplain); fail=fail || memcmp(outplain, plain, cg.BlockSize()); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed "); output.Put(key, cg.KeyLength()); std::cout << " "; output.Put(outplain, cg.BlockSize()); std::cout << " "; output.Put(out, cg.BlockSize()); std::cout << std::endl; } return pass; } class FilterTester : public Unflushable<Sink> { public: FilterTester(const byte *validOutput, size_t outputLen) : validOutput(validOutput), outputLen(outputLen), counter(0), fail(false) {} void PutByte(byte inByte) { if (counter >= outputLen || validOutput[counter] != inByte) { std::cerr << "incorrect output " << counter << ", " << (word16)validOutput[counter] << ", " << (word16)inByte << "\n"; fail = true; CRYPTOPP_ASSERT(false); } counter++; } size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) { CRYPTOPP_UNUSED(messageEnd), CRYPTOPP_UNUSED(blocking); while (length--) FilterTester::PutByte(*inString++); if (messageEnd) if (counter != outputLen) { fail = true; CRYPTOPP_ASSERT(false); } return 0; } bool GetResult() { return !fail; } const byte *validOutput; size_t outputLen, counter; bool fail; }; bool TestFilter(BufferedTransformation &bt, const byte *in, size_t inLen, const byte *out, size_t outLen) { FilterTester *ft; bt.Attach(ft = new FilterTester(out, outLen)); while (inLen) { size_t randomLen = GlobalRNG().GenerateWord32(0, (word32)inLen); bt.Put(in, randomLen); in += randomLen; inLen -= randomLen; } bt.MessageEnd(); return ft->GetResult(); } bool ValidateDES() { std::cout << "\nDES validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/descert.dat", true, new HexDecoder); bool pass = BlockTransformationTest(FixedRoundsCipherFactory<DESEncryption, DESDecryption>(), valdata); std::cout << "\nTesting EDE2, EDE3, and XEX3 variants...\n\n"; FileSource valdata1(CRYPTOPP_DATA_DIR "TestData/3desval.dat", true, new HexDecoder); pass = BlockTransformationTest(FixedRoundsCipherFactory<DES_EDE2_Encryption, DES_EDE2_Decryption>(), valdata1, 1) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<DES_EDE3_Encryption, DES_EDE3_Decryption>(), valdata1, 1) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<DES_XEX3_Encryption, DES_XEX3_Decryption>(), valdata1, 1) && pass; return pass; } bool TestModeIV(SymmetricCipher &e, SymmetricCipher &d) { SecByteBlock lastIV, iv(e.IVSize()); StreamTransformationFilter filter(e, new StreamTransformationFilter(d)); // Enterprise Analysis finding on the stack based array const int BUF_SIZE=20480U; AlignedSecByteBlock plaintext(BUF_SIZE); for (unsigned int i=1; i<20480; i*=2) { e.GetNextIV(GlobalRNG(), iv); if (iv == lastIV) return false; else lastIV = iv; e.Resynchronize(iv); d.Resynchronize(iv); unsigned int length = STDMAX(GlobalRNG().GenerateWord32(0, i), (word32)e.MinLastBlockSize()); GlobalRNG().GenerateBlock(plaintext, length); if (!TestFilter(filter, plaintext, length, plaintext, length)) return false; } return true; } bool ValidateCipherModes() { std::cout << "\nTesting DES modes...\n\n"; const byte key[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; const byte iv[] = {0x12,0x34,0x56,0x78,0x90,0xab,0xcd,0xef}; const byte plain[] = { // "Now is the time for all " without tailing 0 0x4e,0x6f,0x77,0x20,0x69,0x73,0x20,0x74, 0x68,0x65,0x20,0x74,0x69,0x6d,0x65,0x20, 0x66,0x6f,0x72,0x20,0x61,0x6c,0x6c,0x20}; DESEncryption desE(key); DESDecryption desD(key); bool pass=true, fail; { // from FIPS 81 const byte encrypted[] = { 0x3f, 0xa4, 0x0e, 0x8a, 0x98, 0x4d, 0x48, 0x15, 0x6a, 0x27, 0x17, 0x87, 0xab, 0x88, 0x83, 0xf9, 0x89, 0x3d, 0x51, 0xec, 0x4b, 0x56, 0x3b, 0x53}; ECB_Mode_ExternalCipher::Encryption modeE(desE); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "ECB encryption" << std::endl; ECB_Mode_ExternalCipher::Decryption modeD(desD); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "ECB decryption" << std::endl; } { // from FIPS 81 const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with no padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::NO_PADDING).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with no padding" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC mode IV generation" << std::endl; } { // generated with Crypto++, matches FIPS 81 // but has extra 8 bytes as result of padding const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6, 0x62, 0xC1, 0x6A, 0x27, 0xE4, 0xFC, 0xF2, 0x77}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with PKCS #7 padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with PKCS #7 padding" << std::endl; } { // generated with Crypto++ 5.2, matches FIPS 81 // but has extra 8 bytes as result of padding const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6, 0xcf, 0xb7, 0xc7, 0x64, 0x0e, 0x7c, 0xd9, 0xa7}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::ONE_AND_ZEROS_PADDING).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with one-and-zeros padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::ONE_AND_ZEROS_PADDING).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with one-and-zeros padding" << std::endl; } { const byte plain_1[] = {'a', 0, 0, 0, 0, 0, 0, 0}; // generated with Crypto++ const byte encrypted[] = { 0x9B, 0x47, 0x57, 0x59, 0xD6, 0x9C, 0xF6, 0xD0}; CBC_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE, NULLPTR, StreamTransformationFilter::ZEROS_PADDING).Ref(), plain_1, 1, encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with zeros padding" << std::endl; CBC_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD, NULLPTR, StreamTransformationFilter::ZEROS_PADDING).Ref(), encrypted, sizeof(encrypted), plain_1, sizeof(plain_1)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with zeros padding" << std::endl; } { // generated with Crypto++, matches FIPS 81 // but with last two blocks swapped as result of CTS const byte encrypted[] = { 0xE5, 0xC7, 0xCD, 0xDE, 0x87, 0x2B, 0xF2, 0x7C, 0x68, 0x37, 0x88, 0x49, 0x9A, 0x7C, 0x05, 0xF6, 0x43, 0xE9, 0x34, 0x00, 0x8C, 0x38, 0x9C, 0x0F}; CBC_CTS_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with ciphertext stealing (CTS)" << std::endl; CBC_CTS_Mode_ExternalCipher::Decryption modeD(desD, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with ciphertext stealing (CTS)" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC CTS IV generation" << std::endl; } { // generated with Crypto++ const byte decryptionIV[] = {0x4D, 0xD0, 0xAC, 0x8F, 0x47, 0xCF, 0x79, 0xCE}; const byte encrypted[] = {0x12, 0x34, 0x56}; byte stolenIV[8]; CBC_CTS_Mode_ExternalCipher::Encryption modeE(desE, iv); modeE.SetStolenIV(stolenIV); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, 3, encrypted, sizeof(encrypted)); fail = memcmp(stolenIV, decryptionIV, 8) != 0 || fail; pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC encryption with ciphertext and IV stealing" << std::endl; CBC_CTS_Mode_ExternalCipher::Decryption modeD(desD, stolenIV); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, 3); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC decryption with ciphertext and IV stealing" << std::endl; } { const byte encrypted[] = { // from FIPS 81 0xF3,0x09,0x62,0x49,0xC7,0xF4,0x6E,0x51, 0xA6,0x9E,0x83,0x9B,0x1A,0x92,0xF7,0x84, 0x03,0x46,0x71,0x33,0x89,0x8E,0xA6,0x22}; CFB_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB encryption" << std::endl; CFB_Mode_ExternalCipher::Decryption modeD(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB mode IV generation" << std::endl; } { const byte plain_2[] = { // "Now is the." without tailing 0 0x4e,0x6f,0x77,0x20,0x69,0x73,0x20,0x74,0x68,0x65}; const byte encrypted[] = { // from FIPS 81 0xf3,0x1f,0xda,0x07,0x01,0x14,0x62,0xee,0x18,0x7f}; CFB_Mode_ExternalCipher::Encryption modeE(desE, iv, 1); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain_2, sizeof(plain_2), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB (8-bit feedback) encryption" << std::endl; CFB_Mode_ExternalCipher::Decryption modeD(desE, iv, 1); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain_2, sizeof(plain_2)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB (8-bit feedback) decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CFB (8-bit feedback) IV generation" << std::endl; } { const byte encrypted[] = { // from Eric Young's libdes 0xf3,0x09,0x62,0x49,0xc7,0xf4,0x6e,0x51, 0x35,0xf2,0x4a,0x24,0x2e,0xeb,0x3d,0x3f, 0x3d,0x6d,0x5b,0xe3,0x25,0x5a,0xf8,0xc3}; OFB_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "OFB encryption" << std::endl; OFB_Mode_ExternalCipher::Decryption modeD(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "OFB decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "OFB IV generation" << std::endl; } { const byte encrypted[] = { // generated with Crypto++ 0xF3, 0x09, 0x62, 0x49, 0xC7, 0xF4, 0x6E, 0x51, 0x16, 0x3A, 0x8C, 0xA0, 0xFF, 0xC9, 0x4C, 0x27, 0xFA, 0x2F, 0x80, 0xF4, 0x80, 0xB8, 0x6F, 0x75}; CTR_Mode_ExternalCipher::Encryption modeE(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeE).Ref(), plain, sizeof(plain), encrypted, sizeof(encrypted)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "Counter Mode encryption" << std::endl; CTR_Mode_ExternalCipher::Decryption modeD(desE, iv); fail = !TestFilter(StreamTransformationFilter(modeD).Ref(), encrypted, sizeof(encrypted), plain, sizeof(plain)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "Counter Mode decryption" << std::endl; fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "Counter Mode IV generation" << std::endl; } { const byte plain_3[] = { // "7654321 Now is the time for " 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x20, 0x4e, 0x6f, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74, 0x68, 0x65, 0x20, 0x74, 0x69, 0x6d, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x20}; const byte mac1[] = { // from FIPS 113 0xf1, 0xd3, 0x0f, 0x68, 0x49, 0x31, 0x2c, 0xa4}; const byte mac2[] = { // generated with Crypto++ 0x35, 0x80, 0xC5, 0xC4, 0x6B, 0x81, 0x24, 0xE2}; CBC_MAC<DES> cbcmac(key); HashFilter cbcmacFilter(cbcmac); fail = !TestFilter(cbcmacFilter, plain_3, sizeof(plain_3), mac1, sizeof(mac1)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "CBC MAC" << std::endl; DMAC<DES> dmac(key); HashFilter dmacFilter(dmac); fail = !TestFilter(dmacFilter, plain_3, sizeof(plain_3), mac2, sizeof(mac2)); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "DMAC" << std::endl; } { CTR_Mode<AES>::Encryption modeE(plain, 16, plain); CTR_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES CTR Mode" << std::endl; } { OFB_Mode<AES>::Encryption modeE(plain, 16, plain); OFB_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES OFB Mode" << std::endl; } { CFB_Mode<AES>::Encryption modeE(plain, 16, plain); CFB_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES CFB Mode" << std::endl; } { CBC_Mode<AES>::Encryption modeE(plain, 16, plain); CBC_Mode<AES>::Decryption modeD(plain, 16, plain); fail = !TestModeIV(modeE, modeD); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed ") << "AES CBC Mode" << std::endl; } return pass; } bool ValidateIDEA() { std::cout << "\nIDEA validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/ideaval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<IDEAEncryption, IDEADecryption>(), valdata); } bool ValidateSAFER() { std::cout << "\nSAFER validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/saferval.dat", true, new HexDecoder); bool pass = true; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_K_Encryption, SAFER_K_Decryption>(8,6), valdata, 4) && pass; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_K_Encryption, SAFER_K_Decryption>(16,12), valdata, 4) && pass; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_SK_Encryption, SAFER_SK_Decryption>(8,6), valdata, 4) && pass; pass = BlockTransformationTest(VariableRoundsCipherFactory<SAFER_SK_Encryption, SAFER_SK_Decryption>(16,10), valdata, 4) && pass; return pass; } bool ValidateRC2() { std::cout << "\nRC2 validation suite running...\n\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rc2val.dat", true, new HexDecoder); HexEncoder output(new FileSink(std::cout)); SecByteBlock plain(RC2Encryption::BLOCKSIZE), cipher(RC2Encryption::BLOCKSIZE), out(RC2Encryption::BLOCKSIZE), outplain(RC2Encryption::BLOCKSIZE); SecByteBlock key(128); bool pass=true, fail; while (valdata.MaxRetrievable()) { byte keyLen, effectiveLen; valdata.Get(keyLen); valdata.Get(effectiveLen); valdata.Get(key, keyLen); valdata.Get(plain, RC2Encryption::BLOCKSIZE); valdata.Get(cipher, RC2Encryption::BLOCKSIZE); member_ptr<BlockTransformation> transE(new RC2Encryption(key, keyLen, effectiveLen)); transE->ProcessBlock(plain, out); fail = memcmp(out, cipher, RC2Encryption::BLOCKSIZE) != 0; member_ptr<BlockTransformation> transD(new RC2Decryption(key, keyLen, effectiveLen)); transD->ProcessBlock(out, outplain); fail=fail || memcmp(outplain, plain, RC2Encryption::BLOCKSIZE); pass = pass && !fail; std::cout << (fail ? "FAILED " : "passed "); output.Put(key, keyLen); std::cout << " "; output.Put(outplain, RC2Encryption::BLOCKSIZE); std::cout << " "; output.Put(out, RC2Encryption::BLOCKSIZE); std::cout << std::endl; } return pass; } bool ValidateARC4() { unsigned char Key0[] = {0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef }; unsigned char Input0[]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; unsigned char Output0[] = {0x75,0xb7,0x87,0x80,0x99,0xe0,0xc5,0x96}; unsigned char Key1[]={0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}; unsigned char Input1[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Output1[]={0x74,0x94,0xc2,0xe7,0x10,0x4b,0x08,0x79}; unsigned char Key2[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Input2[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Output2[]={0xde,0x18,0x89,0x41,0xa3,0x37,0x5d,0x3a}; unsigned char Key3[]={0xef,0x01,0x23,0x45}; unsigned char Input3[]={0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}; unsigned char Output3[]={0xd6,0xa1,0x41,0xa7,0xec,0x3c,0x38,0xdf,0xbd,0x61}; unsigned char Key4[]={ 0x01,0x23,0x45,0x67,0x89,0xab, 0xcd,0xef }; unsigned char Input4[] = {0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01, 0x01}; unsigned char Output4[]= { 0x75,0x95,0xc3,0xe6,0x11,0x4a,0x09,0x78,0x0c,0x4a,0xd4, 0x52,0x33,0x8e,0x1f,0xfd,0x9a,0x1b,0xe9,0x49,0x8f, 0x81,0x3d,0x76,0x53,0x34,0x49,0xb6,0x77,0x8d,0xca, 0xd8,0xc7,0x8a,0x8d,0x2b,0xa9,0xac,0x66,0x08,0x5d, 0x0e,0x53,0xd5,0x9c,0x26,0xc2,0xd1,0xc4,0x90,0xc1, 0xeb,0xbe,0x0c,0xe6,0x6d,0x1b,0x6b,0x1b,0x13,0xb6, 0xb9,0x19,0xb8,0x47,0xc2,0x5a,0x91,0x44,0x7a,0x95, 0xe7,0x5e,0x4e,0xf1,0x67,0x79,0xcd,0xe8,0xbf,0x0a, 0x95,0x85,0x0e,0x32,0xaf,0x96,0x89,0x44,0x4f,0xd3, 0x77,0x10,0x8f,0x98,0xfd,0xcb,0xd4,0xe7,0x26,0x56, 0x75,0x00,0x99,0x0b,0xcc,0x7e,0x0c,0xa3,0xc4,0xaa, 0xa3,0x04,0xa3,0x87,0xd2,0x0f,0x3b,0x8f,0xbb,0xcd, 0x42,0xa1,0xbd,0x31,0x1d,0x7a,0x43,0x03,0xdd,0xa5, 0xab,0x07,0x88,0x96,0xae,0x80,0xc1,0x8b,0x0a,0xf6, 0x6d,0xff,0x31,0x96,0x16,0xeb,0x78,0x4e,0x49,0x5a, 0xd2,0xce,0x90,0xd7,0xf7,0x72,0xa8,0x17,0x47,0xb6, 0x5f,0x62,0x09,0x3b,0x1e,0x0d,0xb9,0xe5,0xba,0x53, 0x2f,0xaf,0xec,0x47,0x50,0x83,0x23,0xe6,0x71,0x32, 0x7d,0xf9,0x44,0x44,0x32,0xcb,0x73,0x67,0xce,0xc8, 0x2f,0x5d,0x44,0xc0,0xd0,0x0b,0x67,0xd6,0x50,0xa0, 0x75,0xcd,0x4b,0x70,0xde,0xdd,0x77,0xeb,0x9b,0x10, 0x23,0x1b,0x6b,0x5b,0x74,0x13,0x47,0x39,0x6d,0x62, 0x89,0x74,0x21,0xd4,0x3d,0xf9,0xb4,0x2e,0x44,0x6e, 0x35,0x8e,0x9c,0x11,0xa9,0xb2,0x18,0x4e,0xcb,0xef, 0x0c,0xd8,0xe7,0xa8,0x77,0xef,0x96,0x8f,0x13,0x90, 0xec,0x9b,0x3d,0x35,0xa5,0x58,0x5c,0xb0,0x09,0x29, 0x0e,0x2f,0xcd,0xe7,0xb5,0xec,0x66,0xd9,0x08,0x4b, 0xe4,0x40,0x55,0xa6,0x19,0xd9,0xdd,0x7f,0xc3,0x16, 0x6f,0x94,0x87,0xf7,0xcb,0x27,0x29,0x12,0x42,0x64, 0x45,0x99,0x85,0x14,0xc1,0x5d,0x53,0xa1,0x8c,0x86, 0x4c,0xe3,0xa2,0xb7,0x55,0x57,0x93,0x98,0x81,0x26, 0x52,0x0e,0xac,0xf2,0xe3,0x06,0x6e,0x23,0x0c,0x91, 0xbe,0xe4,0xdd,0x53,0x04,0xf5,0xfd,0x04,0x05,0xb3, 0x5b,0xd9,0x9c,0x73,0x13,0x5d,0x3d,0x9b,0xc3,0x35, 0xee,0x04,0x9e,0xf6,0x9b,0x38,0x67,0xbf,0x2d,0x7b, 0xd1,0xea,0xa5,0x95,0xd8,0xbf,0xc0,0x06,0x6f,0xf8, 0xd3,0x15,0x09,0xeb,0x0c,0x6c,0xaa,0x00,0x6c,0x80, 0x7a,0x62,0x3e,0xf8,0x4c,0x3d,0x33,0xc1,0x95,0xd2, 0x3e,0xe3,0x20,0xc4,0x0d,0xe0,0x55,0x81,0x57,0xc8, 0x22,0xd4,0xb8,0xc5,0x69,0xd8,0x49,0xae,0xd5,0x9d, 0x4e,0x0f,0xd7,0xf3,0x79,0x58,0x6b,0x4b,0x7f,0xf6, 0x84,0xed,0x6a,0x18,0x9f,0x74,0x86,0xd4,0x9b,0x9c, 0x4b,0xad,0x9b,0xa2,0x4b,0x96,0xab,0xf9,0x24,0x37, 0x2c,0x8a,0x8f,0xff,0xb1,0x0d,0x55,0x35,0x49,0x00, 0xa7,0x7a,0x3d,0xb5,0xf2,0x05,0xe1,0xb9,0x9f,0xcd, 0x86,0x60,0x86,0x3a,0x15,0x9a,0xd4,0xab,0xe4,0x0f, 0xa4,0x89,0x34,0x16,0x3d,0xdd,0xe5,0x42,0xa6,0x58, 0x55,0x40,0xfd,0x68,0x3c,0xbf,0xd8,0xc0,0x0f,0x12, 0x12,0x9a,0x28,0x4d,0xea,0xcc,0x4c,0xde,0xfe,0x58, 0xbe,0x71,0x37,0x54,0x1c,0x04,0x71,0x26,0xc8,0xd4, 0x9e,0x27,0x55,0xab,0x18,0x1a,0xb7,0xe9,0x40,0xb0, 0xc0}; member_ptr<Weak::ARC4> arc4; bool pass=true, fail; unsigned int i; std::cout << "\nARC4 validation suite running...\n\n"; arc4.reset(new Weak::ARC4(Key0, sizeof(Key0))); arc4->ProcessString(Input0, sizeof(Input0)); fail = memcmp(Input0, Output0, sizeof(Input0)) != 0; std::cout << (fail ? "FAILED" : "passed") << " Test 0" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key1, sizeof(Key1))); arc4->ProcessString(Key1, Input1, sizeof(Key1)); fail = memcmp(Output1, Key1, sizeof(Key1)) != 0; std::cout << (fail ? "FAILED" : "passed") << " Test 1" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key2, sizeof(Key2))); for (i=0, fail=false; i<sizeof(Input2); i++) if (arc4->ProcessByte(Input2[i]) != Output2[i]) fail = true; std::cout << (fail ? "FAILED" : "passed") << " Test 2" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key3, sizeof(Key3))); for (i=0, fail=false; i<sizeof(Input3); i++) if (arc4->ProcessByte(Input3[i]) != Output3[i]) fail = true; std::cout << (fail ? "FAILED" : "passed") << " Test 3" << std::endl; pass = pass && !fail; arc4.reset(new Weak::ARC4(Key4, sizeof(Key4))); for (i=0, fail=false; i<sizeof(Input4); i++) if (arc4->ProcessByte(Input4[i]) != Output4[i]) fail = true; std::cout << (fail ? "FAILED" : "passed") << " Test 4" << std::endl; pass = pass && !fail; return pass; } bool ValidateRC5() { std::cout << "\nRC5 validation suite running...\n\n"; bool pass1 = true, pass2 = true; RC5Encryption enc; // 0 to 2040-bits (255-bytes) pass1 = RC5Encryption::DEFAULT_KEYLENGTH == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == 0 && pass1; pass1 = enc.StaticGetValidKeyLength(254) == 254 && pass1; pass1 = enc.StaticGetValidKeyLength(255) == 255 && pass1; pass1 = enc.StaticGetValidKeyLength(256) == 255 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; RC5Decryption dec; pass2 = RC5Decryption::DEFAULT_KEYLENGTH == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == 0 && pass2; pass2 = dec.StaticGetValidKeyLength(254) == 254 && pass2; pass2 = dec.StaticGetValidKeyLength(255) == 255 && pass2; pass2 = dec.StaticGetValidKeyLength(256) == 255 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rc5val.dat", true, new HexDecoder); return BlockTransformationTest(VariableRoundsCipherFactory<RC5Encryption, RC5Decryption>(16, 12), valdata) && pass1 && pass2; } bool ValidateRC6() { std::cout << "\nRC6 validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; RC6Encryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; RC6Decryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rc6val.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RC6Encryption, RC6Decryption>(16), valdata, 2) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RC6Encryption, RC6Decryption>(24), valdata, 2) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RC6Encryption, RC6Decryption>(32), valdata, 2) && pass3; return pass1 && pass2 && pass3; } bool ValidateMARS() { std::cout << "\nMARS validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; MARSEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 56 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 56 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; MARSDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 56 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 56 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/marsval.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<MARSEncryption, MARSDecryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<MARSEncryption, MARSDecryption>(24), valdata, 3) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<MARSEncryption, MARSDecryption>(32), valdata, 2) && pass3; return pass1 && pass2 && pass3; } bool ValidateRijndael() { std::cout << "\nRijndael (AES) validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; RijndaelEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; RijndaelDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/rijndael.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RijndaelEncryption, RijndaelDecryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RijndaelEncryption, RijndaelDecryption>(24), valdata, 3) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<RijndaelEncryption, RijndaelDecryption>(32), valdata, 2) && pass3; pass3 = RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/aes.txt") && pass3; return pass1 && pass2 && pass3; } bool ValidateTwofish() { std::cout << "\nTwofish validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; TwofishEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; TwofishDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/twofishv.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<TwofishEncryption, TwofishDecryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<TwofishEncryption, TwofishDecryption>(24), valdata, 3) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<TwofishEncryption, TwofishDecryption>(32), valdata, 2) && pass3; return pass1 && pass2 && pass3; } bool ValidateSerpent() { std::cout << "\nSerpent validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; SerpentEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; SerpentDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/serpentv.dat", true, new HexDecoder); bool pass = true; pass = BlockTransformationTest(FixedRoundsCipherFactory<SerpentEncryption, SerpentDecryption>(16), valdata, 5) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<SerpentEncryption, SerpentDecryption>(24), valdata, 4) && pass; pass = BlockTransformationTest(FixedRoundsCipherFactory<SerpentEncryption, SerpentDecryption>(32), valdata, 3) && pass; return pass1 && pass2 && pass3; } bool ValidateBlowfish() { std::cout << "\nBlowfish validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true, fail; BlowfishEncryption enc1; // 32 to 448-bits (4 to 56-bytes) pass1 = enc1.StaticGetValidKeyLength(3) == 4 && pass1; pass1 = enc1.StaticGetValidKeyLength(4) == 4 && pass1; pass1 = enc1.StaticGetValidKeyLength(5) == 5 && pass1; pass1 = enc1.StaticGetValidKeyLength(8) == 8 && pass1; pass1 = enc1.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc1.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc1.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc1.StaticGetValidKeyLength(56) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(57) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(60) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(64) == 56 && pass1; pass1 = enc1.StaticGetValidKeyLength(128) == 56 && pass1; BlowfishDecryption dec1; // 32 to 448-bits (4 to 56-bytes) pass2 = dec1.StaticGetValidKeyLength(3) == 4 && pass2; pass2 = dec1.StaticGetValidKeyLength(4) == 4 && pass2; pass2 = dec1.StaticGetValidKeyLength(5) == 5 && pass2; pass2 = dec1.StaticGetValidKeyLength(8) == 8 && pass2; pass2 = dec1.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec1.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec1.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec1.StaticGetValidKeyLength(56) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(57) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(60) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(64) == 56 && pass2; pass2 = dec1.StaticGetValidKeyLength(128) == 56 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; HexEncoder output(new FileSink(std::cout)); const char *key[]={"abcdefghijklmnopqrstuvwxyz", "Who is John Galt?"}; byte *plain[]={(byte *)"BLOWFISH", (byte *)"\xfe\xdc\xba\x98\x76\x54\x32\x10"}; byte *cipher[]={(byte *)"\x32\x4e\xd0\xfe\xf4\x13\xa2\x03", (byte *)"\xcc\x91\x73\x2b\x80\x22\xf6\x84"}; byte out[8], outplain[8]; for (int i=0; i<2; i++) { ECB_Mode<Blowfish>::Encryption enc2((byte *)key[i], strlen(key[i])); enc2.ProcessData(out, plain[i], 8); fail = memcmp(out, cipher[i], 8) != 0; ECB_Mode<Blowfish>::Decryption dec2((byte *)key[i], strlen(key[i])); dec2.ProcessData(outplain, cipher[i], 8); fail = fail || memcmp(outplain, plain[i], 8); pass3 = pass3 && !fail; std::cout << (fail ? "FAILED " : "passed "); std::cout << '\"' << key[i] << '\"'; for (int j=0; j<(signed int)(30-strlen(key[i])); j++) std::cout << ' '; output.Put(outplain, 8); std::cout << " "; output.Put(out, 8); std::cout << std::endl; } return pass1 && pass2 && pass3; } bool ValidateThreeWay() { std::cout << "\n3-WAY validation suite running...\n\n"; bool pass1 = true, pass2 = true; ThreeWayEncryption enc; // 96-bit only pass1 = ThreeWayEncryption::KEYLENGTH == 12 && pass1; pass1 = enc.StaticGetValidKeyLength(8) == 12 && pass1; pass1 = enc.StaticGetValidKeyLength(12) == 12 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 12 && pass1; ThreeWayDecryption dec; // 96-bit only pass2 = ThreeWayDecryption::KEYLENGTH == 12 && pass2; pass2 = dec.StaticGetValidKeyLength(8) == 12 && pass2; pass2 = dec.StaticGetValidKeyLength(12) == 12 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 12 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/3wayval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<ThreeWayEncryption, ThreeWayDecryption>(), valdata) && pass1 && pass2; } bool ValidateGOST() { std::cout << "\nGOST validation suite running...\n\n"; bool pass1 = true, pass2 = true; GOSTEncryption enc; // 256-bit only pass1 = GOSTEncryption::KEYLENGTH == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(40) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; GOSTDecryption dec; // 256-bit only pass2 = GOSTDecryption::KEYLENGTH == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(40) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/gostval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<GOSTEncryption, GOSTDecryption>(), valdata) && pass1 && pass2; } bool ValidateSHARK() { std::cout << "\nSHARK validation suite running...\n\n"; bool pass1 = true, pass2 = true; SHARKEncryption enc; // 128-bit only pass1 = SHARKEncryption::KEYLENGTH == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(15) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(17) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 16 && pass1; SHARKDecryption dec; // 128-bit only pass2 = SHARKDecryption::KEYLENGTH == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(15) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(17) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 16 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/sharkval.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<SHARKEncryption, SHARKDecryption>(), valdata) && pass1 && pass2; } bool ValidateCAST() { std::cout << "\nCAST-128 validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; CAST128Encryption enc1; // 40 to 128-bits (5 to 16-bytes) pass1 = CAST128Encryption::DEFAULT_KEYLENGTH == 16 && pass1; pass1 = enc1.StaticGetValidKeyLength(4) == 5 && pass1; pass1 = enc1.StaticGetValidKeyLength(5) == 5 && pass1; pass1 = enc1.StaticGetValidKeyLength(15) == 15 && pass1; pass1 = enc1.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc1.StaticGetValidKeyLength(17) == 16 && pass1; CAST128Decryption dec1; // 40 to 128-bits (5 to 16-bytes) pass2 = CAST128Decryption::DEFAULT_KEYLENGTH == 16 && pass2; pass2 = dec1.StaticGetValidKeyLength(4) == 5 && pass2; pass2 = dec1.StaticGetValidKeyLength(5) == 5 && pass2; pass2 = dec1.StaticGetValidKeyLength(15) == 15 && pass2; pass2 = dec1.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec1.StaticGetValidKeyLength(17) == 16 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource val128(CRYPTOPP_DATA_DIR "TestData/cast128v.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CAST128Encryption, CAST128Decryption>(16), val128, 1) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CAST128Encryption, CAST128Decryption>(10), val128, 1) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CAST128Encryption, CAST128Decryption>(5), val128, 1) && pass3; std::cout << "\nCAST-256 validation suite running...\n\n"; bool pass4 = true, pass5 = true, pass6 = true; CAST256Encryption enc2; // 128, 160, 192, 224, or 256-bits (16 to 32-bytes, step 4) pass1 = CAST128Encryption::DEFAULT_KEYLENGTH == 16 && pass1; pass4 = enc2.StaticGetValidKeyLength(15) == 16 && pass4; pass4 = enc2.StaticGetValidKeyLength(16) == 16 && pass4; pass4 = enc2.StaticGetValidKeyLength(17) == 20 && pass4; pass4 = enc2.StaticGetValidKeyLength(20) == 20 && pass4; pass4 = enc2.StaticGetValidKeyLength(24) == 24 && pass4; pass4 = enc2.StaticGetValidKeyLength(28) == 28 && pass4; pass4 = enc2.StaticGetValidKeyLength(31) == 32 && pass4; pass4 = enc2.StaticGetValidKeyLength(32) == 32 && pass4; pass4 = enc2.StaticGetValidKeyLength(33) == 32 && pass4; CAST256Decryption dec2; // 128, 160, 192, 224, or 256-bits (16 to 32-bytes, step 4) pass2 = CAST256Decryption::DEFAULT_KEYLENGTH == 16 && pass2; pass5 = dec2.StaticGetValidKeyLength(15) == 16 && pass5; pass5 = dec2.StaticGetValidKeyLength(16) == 16 && pass5; pass5 = dec2.StaticGetValidKeyLength(17) == 20 && pass5; pass5 = dec2.StaticGetValidKeyLength(20) == 20 && pass5; pass5 = dec2.StaticGetValidKeyLength(24) == 24 && pass5; pass5 = dec2.StaticGetValidKeyLength(28) == 28 && pass5; pass5 = dec2.StaticGetValidKeyLength(31) == 32 && pass5; pass5 = dec2.StaticGetValidKeyLength(32) == 32 && pass5; pass5 = dec2.StaticGetValidKeyLength(33) == 32 && pass5; std::cout << (pass4 && pass5 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource val256(CRYPTOPP_DATA_DIR "TestData/cast256v.dat", true, new HexDecoder); pass6 = BlockTransformationTest(FixedRoundsCipherFactory<CAST256Encryption, CAST256Decryption>(16), val256, 1) && pass6; pass6 = BlockTransformationTest(FixedRoundsCipherFactory<CAST256Encryption, CAST256Decryption>(24), val256, 1) && pass6; pass6 = BlockTransformationTest(FixedRoundsCipherFactory<CAST256Encryption, CAST256Decryption>(32), val256, 1) && pass6; return pass1 && pass2 && pass3 && pass4 && pass5 && pass6; } bool ValidateSquare() { std::cout << "\nSquare validation suite running...\n\n"; bool pass1 = true, pass2 = true; SquareEncryption enc; // 128-bits only pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(15) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(17) == 16 && pass1; SquareDecryption dec; // 128-bits only pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(15) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(17) == 16 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/squareva.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<SquareEncryption, SquareDecryption>(), valdata) && pass1 && pass2; } bool ValidateSKIPJACK() { std::cout << "\nSKIPJACK validation suite running...\n\n"; bool pass1 = true, pass2 = true; SKIPJACKEncryption enc; // 80-bits only pass1 = enc.StaticGetValidKeyLength(8) == 10 && pass1; pass1 = enc.StaticGetValidKeyLength(9) == 10 && pass1; pass1 = enc.StaticGetValidKeyLength(10) == 10 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 10 && pass1; SKIPJACKDecryption dec; // 80-bits only pass2 = dec.StaticGetValidKeyLength(8) == 10 && pass2; pass2 = dec.StaticGetValidKeyLength(9) == 10 && pass2; pass2 = dec.StaticGetValidKeyLength(10) == 10 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 10 && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/skipjack.dat", true, new HexDecoder); return BlockTransformationTest(FixedRoundsCipherFactory<SKIPJACKEncryption, SKIPJACKDecryption>(), valdata) && pass1 && pass2; } bool ValidateSEAL() { const byte input[] = {0x37,0xa0,0x05,0x95,0x9b,0x84,0xc4,0x9c,0xa4,0xbe,0x1e,0x05,0x06,0x73,0x53,0x0f,0x5f,0xb0,0x97,0xfd,0xf6,0xa1,0x3f,0xbd,0x6c,0x2c,0xde,0xcd,0x81,0xfd,0xee,0x7c}; const byte key[] = {0x67, 0x45, 0x23, 0x01, 0xef, 0xcd, 0xab, 0x89, 0x98, 0xba, 0xdc, 0xfe, 0x10, 0x32, 0x54, 0x76, 0xc3, 0xd2, 0xe1, 0xf0}; const byte iv[] = {0x01, 0x35, 0x77, 0xaf}; byte output[32]; std::cout << "\nSEAL validation suite running...\n\n"; SEAL<>::Encryption seal(key, sizeof(key), iv); unsigned int size = sizeof(input); bool pass = true; memset(output, 1, size); seal.ProcessString(output, input, size); for (unsigned int i=0; i<size; i++) if (output[i] != 0) pass = false; seal.Seek(1); output[1] = seal.ProcessByte(output[1]); seal.ProcessString(output+2, size-2); pass = pass && memcmp(output+1, input+1, size-1) == 0; std::cout << (pass ? "passed" : "FAILED") << std::endl; return pass; } bool ValidateBaseCode() { bool pass = true, fail; byte data[255]; for (unsigned int i=0; i<255; i++) data[i] = byte(i); const char hexEncoded[] = "000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F2021222324252627" "28292A2B2C2D2E2F303132333435363738393A3B3C3D3E3F404142434445464748494A4B4C4D4E4F" "505152535455565758595A5B5C5D5E5F606162636465666768696A6B6C6D6E6F7071727374757677" "78797A7B7C7D7E7F808182838485868788898A8B8C8D8E8F909192939495969798999A9B9C9D9E9F" "A0A1A2A3A4A5A6A7A8A9AAABACADAEAFB0B1B2B3B4B5B6B7B8B9BABBBCBDBEBFC0C1C2C3C4C5C6C7" "C8C9CACBCCCDCECFD0D1D2D3D4D5D6D7D8D9DADBDCDDDEDFE0E1E2E3E4E5E6E7E8E9EAEBECEDEEEF" "F0F1F2F3F4F5F6F7F8F9FAFBFCFDFE"; const char base32Encoded[] = "AAASEA2EAWDAQCAJBIFS2DIQB6IBCESVCSKTNF22DEPBYHA7D2RUAIJCENUCKJTHFAWUWK3NFWZC8NBT" "GI3VIPJYG66DUQT5HS8V6R4AIFBEGTCFI3DWSUKKJPGE4VURKBIXEW4WKXMFQYC3MJPX2ZK8M7SGC2VD" "NTUYN35IPFXGY5DPP3ZZA6MUQP4HK7VZRB6ZW856RX9H9AEBSKB2JBNGS8EIVCWMTUG27D6SUGJJHFEX" "U4M3TGN4VQQJ5HW9WCS4FI7EWYVKRKFJXKX43MPQX82MDNXVYU45PP72ZG7MZRF7Z496BSQC2RCNMTYH" "3DE6XU8N3ZHN9WGT4MJ7JXQY49NPVYY55VQ77Z9A6HTQH3HF65V8T4RK7RYQ55ZR8D29F69W8Z5RR8H3" "9M7939R8"; const char base64AndHexEncoded[] = "41414543417751464267634943516F4C4441304F4478415245684D554652595847426B6147787764" "486838674953496A4A43556D4A7967704B6973734C5334764D4445794D7A51310A4E6A63344F546F" "375044302B50304242516B4E4552555A4853456C4B5330784E546B395155564A5456465657563168" "5A576C746358563566594746695932526C5A6D646F615770720A6247317562334278636E4E306458" "5A3365486C3665337839666E2B4167594B44684957476834694A696F754D6A5936506B4A47536B35" "53566C7065596D5A71626E4A32656E3643680A6F714F6B7061616E714B6D717136797472712B7773" "624B7A744C573274376935757275387662362F774D484377385446787366497963724C7A4D334F7A" "39445230745055316462580A324E6E6132397A6433742F6734654C6A354F586D352B6A7036757673" "3765377638504879382F5431397666342B6672372F50332B0A"; const char base64URLAndHexEncoded[] = "41414543417751464267634943516F4C4441304F4478415245684D554652595847426B6147787764" "486838674953496A4A43556D4A7967704B6973734C5334764D4445794D7A51314E6A63344F546F37" "5044302D50304242516B4E4552555A4853456C4B5330784E546B395155564A54564656575631685A" "576C746358563566594746695932526C5A6D646F615770726247317562334278636E4E3064585A33" "65486C3665337839666E2D4167594B44684957476834694A696F754D6A5936506B4A47536B355356" "6C7065596D5A71626E4A32656E3643686F714F6B7061616E714B6D717136797472712D7773624B7A" "744C573274376935757275387662365F774D484377385446787366497963724C7A4D334F7A394452" "3074505531646258324E6E6132397A6433745F6734654C6A354F586D352D6A703675767337653776" "38504879385F5431397666342D6672375F50332D"; std::cout << "\nBase64, Base64URL, Base32 and Base16 coding validation suite running...\n\n"; fail = !TestFilter(HexEncoder().Ref(), data, 255, (const byte *)hexEncoded, strlen(hexEncoded)); try {HexEncoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Hex Encoding\n"; pass = pass && !fail; fail = !TestFilter(HexDecoder().Ref(), (const byte *)hexEncoded, strlen(hexEncoded), data, 255); try {HexDecoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Hex Decoding\n"; pass = pass && !fail; fail = !TestFilter(Base32Encoder().Ref(), data, 255, (const byte *)base32Encoded, strlen(base32Encoded)); try {Base32Encoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base32 Encoding\n"; pass = pass && !fail; fail = !TestFilter(Base32Decoder().Ref(), (const byte *)base32Encoded, strlen(base32Encoded), data, 255); try {Base32Decoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base32 Decoding\n"; pass = pass && !fail; fail = !TestFilter(Base64Encoder(new HexEncoder).Ref(), data, 255, (const byte *)base64AndHexEncoded, strlen(base64AndHexEncoded)); try {Base64Encoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 Encoding\n"; pass = pass && !fail; fail = !TestFilter(HexDecoder(new Base64Decoder).Ref(), (const byte *)base64AndHexEncoded, strlen(base64AndHexEncoded), data, 255); try {Base64Decoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 Decoding\n"; pass = pass && !fail; fail = !TestFilter(Base64URLEncoder(new HexEncoder).Ref(), data, 255, (const byte *)base64URLAndHexEncoded, strlen(base64URLAndHexEncoded)); try {Base64URLEncoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 URL Encoding\n"; pass = pass && !fail; fail = !TestFilter(HexDecoder(new Base64URLDecoder).Ref(), (const byte *)base64URLAndHexEncoded, strlen(base64URLAndHexEncoded), data, 255); try {Base64URLDecoder().IsolatedInitialize(g_nullNameValuePairs);} catch (const Exception&) {fail=true;} std::cout << (fail ? "FAILED:" : "passed:"); std::cout << " Base64 URL Decoding\n"; pass = pass && !fail; return pass; } bool ValidateSHACAL2() { std::cout << "\nSHACAL-2 validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; SHACAL2Encryption enc; // 128 to 512-bits (16 to 64-bytes) pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(15) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 64 && pass1; pass1 = enc.StaticGetValidKeyLength(65) == 64 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 64 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; SHACAL2Decryption dec; // 128 to 512-bits (16 to 64-bytes) pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(15) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 64 && pass2; pass2 = dec.StaticGetValidKeyLength(65) == 64 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 64 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/shacal2v.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<SHACAL2Encryption, SHACAL2Decryption>(16), valdata, 4) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<SHACAL2Encryption, SHACAL2Decryption>(64), valdata, 10) && pass3; return pass1 && pass2 && pass3; } bool ValidateARIA() { std::cout << "\nARIA validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; ARIAEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; ARIADecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/aria.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<ARIAEncryption, ARIADecryption>(16), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<ARIAEncryption, ARIADecryption>(24), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<ARIAEncryption, ARIADecryption>(32), valdata, 15) && pass3; return pass1 && pass2 && pass3; } bool ValidateCamellia() { std::cout << "\nCamellia validation suite running...\n\n"; bool pass1 = true, pass2 = true, pass3 = true; CamelliaEncryption enc; pass1 = enc.StaticGetValidKeyLength(8) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(16) == 16 && pass1; pass1 = enc.StaticGetValidKeyLength(24) == 24 && pass1; pass1 = enc.StaticGetValidKeyLength(32) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(64) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(128) == 32 && pass1; pass1 = enc.StaticGetValidKeyLength(0) == enc.MinKeyLength() && pass1; pass1 = enc.StaticGetValidKeyLength(SIZE_MAX) == enc.MaxKeyLength() && pass1; CamelliaDecryption dec; pass2 = dec.StaticGetValidKeyLength(8) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(16) == 16 && pass2; pass2 = dec.StaticGetValidKeyLength(24) == 24 && pass2; pass2 = dec.StaticGetValidKeyLength(32) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(64) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(128) == 32 && pass2; pass2 = dec.StaticGetValidKeyLength(0) == dec.MinKeyLength() && pass2; pass2 = dec.StaticGetValidKeyLength(SIZE_MAX) == dec.MaxKeyLength() && pass2; std::cout << (pass1 && pass2 ? "passed:" : "FAILED:") << " Algorithm key lengths\n"; FileSource valdata(CRYPTOPP_DATA_DIR "TestData/camellia.dat", true, new HexDecoder); pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CamelliaEncryption, CamelliaDecryption>(16), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CamelliaEncryption, CamelliaDecryption>(24), valdata, 15) && pass3; pass3 = BlockTransformationTest(FixedRoundsCipherFactory<CamelliaEncryption, CamelliaDecryption>(32), valdata, 15) && pass3; return pass1 && pass2 && pass3; } bool ValidateSalsa() { std::cout << "\nSalsa validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/salsa.txt"); } bool ValidateSosemanuk() { std::cout << "\nSosemanuk validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/sosemanuk.txt"); } bool ValidateVMAC() { std::cout << "\nVMAC validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/vmac.txt"); } bool ValidateCCM() { std::cout << "\nAES/CCM validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/ccm.txt"); } bool ValidateGCM() { std::cout << "\nAES/GCM validation suite running...\n"; std::cout << "\n2K tables:"; bool pass = RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)2048)); std::cout << "\n64K tables:"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/gcm.txt", MakeParameters(Name::TableSize(), (int)64*1024)) && pass; } bool ValidateCMAC() { std::cout << "\nCMAC validation suite running...\n"; return RunTestDataFile(CRYPTOPP_DATA_DIR "TestVectors/cmac.txt"); } NAMESPACE_END // Test NAMESPACE_END // CryptoPP
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_3390_0
crossvul-cpp_data_bad_4251_0
/* JSON_parser.c */ /* 2005-12-30 */ /* Copyright (c) 2005 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // If we have json-c then don't use this library since that one has a more // permissive licence #ifndef HAVE_JSONC #include "hphp/runtime/ext/json/JSON_parser.h" #include <folly/FBVector.h> #include "hphp/runtime/base/array-provenance.h" #include "hphp/runtime/base/builtin-functions.h" #include "hphp/runtime/base/collections.h" #include "hphp/runtime/base/string-buffer.h" #include "hphp/runtime/base/request-info.h" #include "hphp/runtime/base/tv-refcount.h" #include "hphp/runtime/base/init-fini-node.h" #include "hphp/runtime/base/utf8-decode.h" #include "hphp/runtime/ext/json/ext_json.h" #include "hphp/runtime/ext/collections/ext_collections-map.h" #include "hphp/runtime/ext/collections/ext_collections-vector.h" #include "hphp/system/systemlib.h" #include "hphp/util/fast_strtoll_base10.h" #include "hphp/zend/zend-strtod.h" #define MAX_LENGTH_OF_LONG 20 static const char long_min_digits[] = "9223372036854775808"; namespace HPHP { /* Characters are mapped into these 32 symbol classes. This allows for significant reductions in the size of the state transition table. */ /* error */ #define S_ERR -1 /* space */ #define S_SPA 0 /* other whitespace */ #define S_WSP 1 /* { */ #define S_LBE 2 /* } */ #define S_RBE 3 /* [ */ #define S_LBT 4 /* ] */ #define S_RBT 5 /* : */ #define S_COL 6 /* , */ #define S_COM 7 /* " */ #define S_QUO 8 /* \ */ #define S_BAC 9 /* / */ #define S_SLA 10 /* + */ #define S_PLU 11 /* - */ #define S_MIN 12 /* . */ #define S_DOT 13 /* 0 */ #define S_ZER 14 /* 123456789 */ #define S_DIG 15 /* a */ #define S__A_ 16 /* b */ #define S__B_ 17 /* c */ #define S__C_ 18 /* d */ #define S__D_ 19 /* e */ #define S__E_ 20 /* f */ #define S__F_ 21 /* l */ #define S__L_ 22 /* n */ #define S__N_ 23 /* r */ #define S__R_ 24 /* s */ #define S__S_ 25 /* t */ #define S__T_ 26 /* u */ #define S__U_ 27 /* ABCDF */ #define S_A_F 28 /* E */ #define S_E 29 /* everything else */ #define S_ETC 30 /* This table maps the 128 ASCII characters into the 32 character classes. The remaining Unicode characters should be mapped to S_ETC. */ alignas(64) static const int8_t ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*<fb>*/ alignas(64) static const int8_t loose_ascii_class[128] = { S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_WSP, S_WSP, S_ERR, S_ERR, S_WSP, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_ERR, S_SPA, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_ETC, S_QUO, S_ETC, S_ETC, S_ETC, S_PLU, S_COM, S_MIN, S_DOT, S_SLA, S_ZER, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_DIG, S_COL, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_A_F, S_A_F, S_A_F, S_A_F, S_E , S_A_F, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBT, S_BAC, S_RBT, S_ETC, S_ETC, S_ETC, S__A_, S__B_, S__C_, S__D_, S__E_, S__F_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S__L_, S_ETC, S__N_, S_ETC, S_ETC, S_ETC, S__R_, S__S_, S__T_, S__U_, S_ETC, S_ETC, S_ETC, S_ETC, S_ETC, S_LBE, S_ETC, S_RBE, S_ETC, S_ETC }; /*</fb>*/ /* The state transition table takes the current state and the current symbol, and returns either a new state or an action. A new state is a number between 0 and 29. An action is a negative number between -1 and -9. A JSON text is accepted if the end of the text is in state 9 and mode is Mode::DONE. */ alignas(64) static const int8_t state_transition_table[30][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1} }; /*<fb>*/ /* Alternate "loose" transition table to support unquoted keys. Note: State 3 has same outgoing transitions in both transition tables. This is used below in the fast-case for appending simple characters (3 -> 3). */ alignas(64) static const int8_t loose_state_transition_table[31][32] = { /* 0*/ { 0, 0,-8,-1,-6,-1,-1,-1, 3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /* 1*/ { 1, 1,-1,-9,-1,-1,-1,-1, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /* 2*/ { 2, 2,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /* 3*/ { 3,-1, 3, 3, 3, 3, 3, 3,-4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, /* 4*/ {-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3,-1,-1,-1, 3,-1, 3, 3,-1, 3, 5,-1,-1,-1}, /* 5*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 6, 6, 6, 6, 6, 6, 6, 6,-1,-1,-1,-1,-1,-1, 6, 6,-1}, /* 6*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 7, 7, 7, 7, 7, 7, 7, 7,-1,-1,-1,-1,-1,-1, 7, 7,-1}, /* 7*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 8, 8, 8, 8, 8, 8, 8, 8,-1,-1,-1,-1,-1,-1, 8, 8,-1}, /* 8*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 3, 3, 3, 3, 3, 3, 3, 3,-1,-1,-1,-1,-1,-1, 3, 3,-1}, /* 9*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*10*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,11,-1,-1,-1,-1,-1,-1}, /*11*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,12,-1,-1,-1}, /*12*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*13*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,14,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*14*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,15,-1,-1,-1,-1,-1,-1,-1,-1}, /*15*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,16,-1,-1,-1,-1,-1}, /*16*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*17*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,18,-1,-1,-1}, /*18*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,19,-1,-1,-1,-1,-1,-1,-1,-1}, /*19*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 9,-1,-1,-1,-1,-1,-1,-1,-1}, /*20*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,21,22,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*21*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,-1,-1,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*22*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,23,22,22,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*23*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,23,23,-1,-1,-1,-1,24,-1,-1,-1,-1,-1,-1,-1,-1,24,-1}, /*24*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,25,25,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*25*/ {-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*26*/ { 9, 9,-1,-7,-1,-5,-1,-3,-1,-1,-1,-1,-1,-1,26,26,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*27*/ {27,27,-1,-1,-1,-1,-2,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1}, /*28*/ {28,28,-8,-1,-6,-5,-1,-1, 3,-1,-1,-1,20,-1,21,22,-1,-1,-1,-1,-1,13,-1,17,-1,-1,10,-1,-1,-1,-1}, /*29*/ {29,29,-1,-7,-1,-1,-1,-7, 3,-1,-1,-1,-1,-1,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30}, /*30*/ {30,-1,30,30,30,30,-10,30,-4,4,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30} }; /*</fb>*/ /** * These modes can be pushed on the PDA stack. */ enum class Mode { INVALID = 0, DONE = 1, KEY = 2, OBJECT = 3, ARRAY = 4 }; namespace { int dehexchar(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - ('A' - 10); if (c >= 'a' && c <= 'f') return c - ('a' - 10); return -1; } NEVER_INLINE static void tvDecRefRange(TypedValue* begin, TypedValue* end) { assertx(begin <= end); for (auto tv = begin; tv != end; ++tv) { tvDecRefGen(tv); } } /* * Parses a subset of JSON. Currently unsupported: * - Non-ASCII * - Character escape sequences * - Non-string array keys * - Arrays nested > 255 levels */ struct SimpleParser { static constexpr int kMaxArrayDepth = 255; /* * Returns buffer size in bytes needed to handle any input up to given length. */ static size_t BufferBytesForLength(int length) { return (length + 1) * sizeof(TypedValue) / 2; // Worst case: "[0,0,...,0]" } /* * Returns false for unsupported or malformed input (does not distinguish). */ static bool TryParse(const char* inp, int length, TypedValue* buf, Variant& out, JSONContainerType container_type, bool is_tsimplejson) { SimpleParser parser(inp, length, buf, container_type, is_tsimplejson); bool ok = parser.parseValue(); if (!ok || (parser.skipSpace(), parser.p != inp + length)) { // Unsupported, malformed, or trailing garbage. Release entire stack. tvDecRefRange(buf, parser.top); return false; } out = Variant::attach(*--parser.top); return true; } private: SimpleParser(const char* input, int length, TypedValue* buffer, JSONContainerType container_type, bool is_tsimplejson) : p(input) , top(buffer) , array_depth(-kMaxArrayDepth) /* Start negative to simplify check. */ , container_type(container_type) , is_tsimplejson(is_tsimplejson) { assertx(input[length] == 0); // Parser relies on sentinel to avoid checks. } /* * Skip whitespace, then if next char is 'ch', consume it and return true, * otherwise let it be and return false. */ bool matchSeparator(char ch) { if (LIKELY(*p++ == ch)) return true; return matchSeparatorSlow(ch); } NEVER_INLINE bool matchSeparatorSlow(char ch) { --p; skipSpace(); if (LIKELY(*p++ == ch)) return true; --p; return false; } NEVER_INLINE void skipSpace() { while (isSpace(*p)) p++; } bool isSpace(char ch) const { return ch == ' ' || ch == '\n' || ch == '\t' || ch == '\f'; } /* * Variant parser. * * JSON arrays don't permit leading 0's in numbers, so we have to thread that * context through here to parseNumber(). */ bool parseValue(bool array_elem = false) { auto const ch = *p++; if (ch == '{') return parseMixed(); else if (ch == '[') return parsePacked(); else if (ch == '\"') return parseString(); else if ((ch >= '0' && ch <= '9') || ch == '-') return parseNumber(ch, array_elem); else if (ch == 't') return parseRue(); else if (ch == 'f') return parseAlse(); else if (ch == 'n') return parseUll(); else if (isSpace(ch)) { skipSpace(); return parseValue(array_elem); } else return false; } bool parseRue() { if (*p++ != 'r') return false; if (*p++ != 'u') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = true; return true; } bool parseAlse() { if (*p++ != 'a') return false; if (*p++ != 'l') return false; if (*p++ != 's') return false; if (*p++ != 'e') return false; auto const tv = top++; tv->m_type = KindOfBoolean; tv->m_data.num = false; return true; } bool parseUll() { if (*p++ != 'u') return false; if (*p++ != 'l') return false; if (*p++ != 'l') return false; top++->m_type = KindOfNull; return true; } bool handleBackslash(signed char& out) { char ch = *p++; switch (ch) { case 0: return false; case '"': out = ch; return true; case '\\': out = ch; return true; case '/': out = ch; return true; case 'b': out = '\b'; return true; case 'f': out = '\f'; return true; case 'n': out = '\n'; return true; case 'r': out = '\r'; return true; case 't': out = '\t'; return true; case 'u': { if (UNLIKELY(is_tsimplejson)) { auto const ch1 = *p++; auto const ch2 = *p++; auto const dch3 = dehexchar(*p++); auto const dch4 = dehexchar(*p++); if (UNLIKELY(ch1 != '0' || ch2 != '0' || dch3 < 0 || dch4 < 0)) { return false; } out = (dch3 << 4) | dch4; return true; } else { uint16_t u16cp = 0; for (int i = 0; i < 4; i++) { auto const hexv = dehexchar(*p++); if (hexv < 0) return false; // includes check for end of string u16cp <<= 4; u16cp |= hexv; } if (u16cp > 0x7f) { return false; } else { out = u16cp; return true; } } } default: return false; } } bool parseRawString(int* len) { assertx(p[-1] == '"'); // SimpleParser only handles "-quoted strings *len = 0; auto const charTop = reinterpret_cast<signed char*>(top); for (signed char ch = *p++; ch != '\"'; ch = *p++) { charTop[(*len)++] = ch; // overwritten later if `ch == '\\'` if (ch < ' ') { // `ch < ' '` catches null and also non-ASCII (since signed char) return false; } else if (ch == '\\') { if (!handleBackslash(charTop[*len - 1])) return false; } } return true; } bool parseString() { int len; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); pushStringData(StringData::Make(start, len, CopyString)); return true; } bool parseMixedKey() { int len; int64_t num; if (!parseRawString(&len)) return false; auto const start = reinterpret_cast<char*>(top); auto const slice = folly::StringPiece(start, len); start[len] = '\0'; if (container_type != JSONContainerType::HACK_ARRAYS && container_type != JSONContainerType::LEGACY_HACK_ARRAYS && is_strictly_integer(start, len, num)) { pushInt64(num); } else if (auto const str = lookupStaticString(slice)) { auto const tv = top++; tv->m_type = KindOfPersistentString; tv->m_data.pstr = str; } else { pushStringData(StringData::Make(start, len, CopyString)); } return true; } bool parsePacked() { auto const fp = top; if (!matchSeparator(']')) { if (++array_depth >= 0) return false; do { if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator(']')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateVec() : PackedArray::MakeVecNatural(top - fp, fp); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyVecArray()->copy() : PackedArray::MakeVecNatural(top - fp, fp); ret->setLegacyArray(true); return ret; } if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { return top == fp ? ArrayData::CreateVArray() : PackedArray::MakeVArrayNatural(top - fp, fp); } assertx(container_type == JSONContainerType::DARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArrayNatural(top - fp, fp); }(); top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } bool parseMixed() { auto const fp = top; if (!matchSeparator('}')) { if (++array_depth >= 0) return false; do { if (!matchSeparator('\"')) return false; // Only support string keys. if (!parseMixedKey()) return false; // TODO(14491721): Precompute and save hash to avoid deref in MakeMixed. if (!matchSeparator(':')) return false; if (!parseValue(true)) return false; } while (matchSeparator(',')); --array_depth; if (!matchSeparator('}')) return false; // Trailing ',' not supported. } auto arr = [&] { if (container_type == JSONContainerType::HACK_ARRAYS) { return top == fp ? ArrayData::CreateDict() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); } if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto ret = top == fp ? staticEmptyDictArray()->copy() : MixedArray::MakeDict((top - fp) >> 1, fp)->asArrayData(); ret->setLegacyArray(true); return ret; } assertx(container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS); return top == fp ? ArrayData::CreateDArray() : MixedArray::MakeDArray((top - fp) >> 1, fp)->asArrayData(); }(); // MixedArray::MakeMixed can return nullptr if there are duplicate keys if (!arr) return false; top = fp; pushArrayData(arr); check_non_safepoint_surprise(); return true; } /* * Parse remainder of number after initial character firstChar (maybe '-'). */ bool parseNumber(char firstChar, bool array_elem = false) { uint64_t x = 0; bool neg = false; const char* begin = p - 1; if (firstChar == '-') { neg = true; } else { x = firstChar - '0'; // first digit } // Parse maximal digit sequence into x (non-negative). while (*p >= '0' && *p <= '9') { x = (x * 10) + (*p - '0'); ++p; } if (*p == '.' || *p == 'e' || *p == 'E') { pushDouble(zend_strtod(begin, &p)); return true; } auto len = p - begin; // JSON arrays don't permit leading 0's in numbers. if (UNLIKELY(len > 1 && firstChar == '0' && array_elem)) { return false; } // Now 'x' is the usigned absolute value of a naively parsed integer, but // potentially overflowed mod 2^64. if (LIKELY(len < 19) || (len == 19 && firstChar <= '8')) { int64_t sx = x; pushInt64(neg ? -sx : sx); } else { parseBigInt(len); } return true; } /* * Assuming 'len' characters ('0'-'9', maybe prefix '-') have been read, * re-parse and push as an int64_t if possible, otherwise as a double. */ void parseBigInt(int len) { assertx(*p > '9' || *p < '0'); // Aleady read maximal digit sequence. errno = 0; const int64_t sx = strtoll(p - len, nullptr, 10); if (errno == ERANGE) { const double dval = zend_strtod(p - len, nullptr); assertx(dval == floor(dval)); pushDouble(dval); } else { pushInt64(sx); } } void pushDouble(double data) { auto const tv = top++; tv->m_type = KindOfDouble; tv->m_data.dbl = data; } void pushInt64(int64_t data) { auto const tv = top++; tv->m_type = KindOfInt64; tv->m_data.num = data; } void pushStringData(StringData* data) { auto const tv = top++; tv->m_type = KindOfString; tv->m_data.pstr = data; } void pushArrayData(ArrayData* data) { auto const tv = top++; tv->m_type = data->toDataType(); tv->m_data.parr = data; assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } const char* p; TypedValue* top; int array_depth; JSONContainerType container_type; bool is_tsimplejson; }; /* * String buffer wrapper that does NOT check its capacity in release mode. User * supplies the allocation and must ensure to never append past the end. */ struct UncheckedBuffer { void clear() { p = begin; } // Use given buffer with space for 'cap' chars, including '\0'. void setBuf(char* buf, size_t cap) { begin = p = buf; #ifndef NDEBUG end = begin + cap; #endif } void append(char c) { assertx(p < end); *p++ = c; } void shrinkBy(int decrease) { p -= decrease; assertx(p >= begin); } int size() { return p - begin; } // NUL-terminates the output before returning it, for backward-compatibility. char* data() { assertx(p < end); *p = 0; return begin; } String copy() { return String(data(), size(), CopyString); } char* p{nullptr}; char* begin{nullptr}; #ifndef NDEBUG char* end{nullptr}; #endif }; } /** * A stack maintains the states of nested structures. */ struct json_parser { struct json_state { Mode mode; String key; Variant val; }; folly::fbvector<json_state> stack; // check_non_safepoint_surprise() above will not trigger gc TYPE_SCAN_IGNORE_FIELD(stack); int top; int mark; // the watermark int depth; json_error_codes error_code; // Thread-local buffer; reused on each call. JSON parsing cannot lead to code // execution and is not re-entrant. SimpleParser assumes no surprise checks. union { TypedValue* tv{nullptr}; // SimpleParser's stack. char* raw; // sb_buf/key } tl_buffer; TYPE_SCAN_IGNORE_FIELD(tv); UncheckedBuffer sb_buf; UncheckedBuffer sb_key; int sb_cap{0}; // Capacity of each of sb_buf/key. void initSb(int length) { if (UNLIKELY(length >= sb_cap)) { // No decoded string in the output can use more bytes than input size. const auto new_cap = length + 1; size_t bufSize = length <= RuntimeOption::EvalSimpleJsonMaxLength ? SimpleParser::BufferBytesForLength(length) : new_cap * 2; if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; if (!tl_heap->preAllocOOM(bufSize)) { tl_buffer.raw = (char*)json_malloc(bufSize); if (!tl_buffer.raw) tl_heap->forceOOM(); } check_non_safepoint_surprise(); always_assert(tl_buffer.raw); sb_buf.setBuf(tl_buffer.raw, new_cap); sb_key.setBuf(tl_buffer.raw + new_cap, new_cap); // Set new capacity if and ony if allocations succeed. sb_cap = new_cap; } else { sb_buf.clear(); sb_key.clear(); } } void flushSb() { if (tl_buffer.raw) { json_free(tl_buffer.raw); tl_buffer.raw = nullptr; } sb_cap = 0; sb_buf.setBuf(nullptr, 0); sb_key.setBuf(nullptr, 0); } private: static void* json_malloc(size_t size) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_malloc(size); } else { return malloc(size); } } static void json_free(void* ptr) { if (RuntimeOption::EvalJsonParserUseLocalArena) { return local_free(ptr); } else { return free(ptr); } } }; RDS_LOCAL(json_parser, s_json_parser); // In Zend, the json_parser struct is publicly // accessible. Thus the fields could be accessed // directly. Just using setter/accessor functions // to get around that. json_error_codes json_get_last_error_code() { return s_json_parser->error_code; } void json_set_last_error_code(json_error_codes ec) { s_json_parser->error_code = ec; } const char *json_get_last_error_msg() { switch (s_json_parser->error_code) { case JSON_ERROR_NONE: return "No error"; case JSON_ERROR_DEPTH: return "Maximum stack depth exceeded"; case JSON_ERROR_STATE_MISMATCH: return "State mismatch (invalid or malformed JSON)"; case JSON_ERROR_CTRL_CHAR: return "Control character error, possibly incorrectly encoded"; case JSON_ERROR_SYNTAX: return "Syntax error"; case JSON_ERROR_UTF8: return "Malformed UTF-8 characters, possibly incorrectly encoded"; case json_error_codes::JSON_ERROR_RECURSION: return "Recursion detected"; case json_error_codes::JSON_ERROR_INF_OR_NAN: return "Inf and NaN cannot be JSON encoded"; case json_error_codes::JSON_ERROR_UNSUPPORTED_TYPE: return "Type is not supported"; default: return "Unknown error"; } } // For each request, make sure we start with the default error code. void json_parser_init() { s_json_parser->error_code = JSON_ERROR_NONE; } void json_parser_flush_caches() { s_json_parser->flushSb(); } /** * Push a mode onto the stack. Return false if there is overflow. */ static int push(json_parser *json, Mode mode) { if (json->top + 1 >= json->depth) { return false; } json->top += 1; json->stack[json->top].mode = mode; if (json->top > json->mark) { json->mark = json->top; } return true; } /** * Pop the stack, assuring that the current mode matches the expectation. * Return false if there is underflow or if the modes mismatch. */ static int pop(json_parser *json, Mode mode) { if (json->top < 0 || json->stack[json->top].mode != mode) { return false; } json->stack[json->top].mode = Mode::INVALID; json->top -= 1; return true; } static String copy_and_clear(UncheckedBuffer &buf) { auto ret = buf.size() > 0 ? buf.copy() : empty_string(); buf.clear(); return ret; } static Variant to_double(UncheckedBuffer &buf) { auto data = buf.data(); auto ret = data ? zend_strtod(data, nullptr) : 0.0; buf.clear(); return ret; } static void json_create_zval(Variant &z, UncheckedBuffer &buf, DataType type, int64_t options) { switch (type) { case KindOfBoolean: z = (buf.data() && (*buf.data() == 't')); return; case KindOfInt64: { bool bigint = false; const char *p = buf.data(); assertx(p); if (p == NULL) { z = int64_t(0); return; } bool neg = *buf.data() == '-'; int len = buf.size(); if (neg) len--; if (len >= MAX_LENGTH_OF_LONG - 1) { if (len == MAX_LENGTH_OF_LONG - 1) { int cmp = strcmp(p + (neg ? 1 : 0), long_min_digits); if (!(cmp < 0 || (cmp == 0 && neg))) { bigint = true; } } else { bigint = true; } } if (bigint) { if (!(options & k_JSON_BIGINT_AS_STRING)) { // See KindOfDouble (below) z = to_double(buf); } else { z = copy_and_clear(buf); } } else { z = fast_strtoll_base10(buf.data()); } return; } case KindOfDouble: // Use zend_strtod() instead of strtod() here since JSON specifies using // a '.' for decimal separators regardless of locale. z = to_double(buf); return; case KindOfString: z = copy_and_clear(buf); return; case KindOfUninit: case KindOfNull: case KindOfPersistentString: case KindOfPersistentDArray: case KindOfDArray: case KindOfPersistentVArray: case KindOfVArray: case KindOfPersistentArray: case KindOfArray: case KindOfPersistentVec: case KindOfVec: case KindOfPersistentDict: case KindOfDict: case KindOfPersistentKeyset: case KindOfKeyset: case KindOfObject: case KindOfResource: case KindOfFunc: case KindOfClass: case KindOfClsMeth: case KindOfRecord: z = uninit_null(); return; } not_reached(); } NEVER_INLINE void utf16_to_utf8_tail(UncheckedBuffer &buf, unsigned short utf16) { if (utf16 < 0x800) { buf.append((char)(0xc0 | (utf16 >> 6))); buf.append((char)(0x80 | (utf16 & 0x3f))); } else if ((utf16 & 0xfc00) == 0xdc00 && buf.size() >= 3 && ((unsigned char)buf.data()[buf.size() - 3]) == 0xed && ((unsigned char)buf.data()[buf.size() - 2] & 0xf0) == 0xa0 && ((unsigned char)buf.data()[buf.size() - 1] & 0xc0) == 0x80) { /* found surrogate pair */ unsigned long utf32; utf32 = (((buf.data()[buf.size() - 2] & 0xf) << 16) | ((buf.data()[buf.size() - 1] & 0x3f) << 10) | (utf16 & 0x3ff)) + 0x10000; buf.shrinkBy(3); buf.append((char)(0xf0 | (utf32 >> 18))); buf.append((char)(0x80 | ((utf32 >> 12) & 0x3f))); buf.append((char)(0x80 | ((utf32 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf32 & 0x3f))); } else { buf.append((char)(0xe0 | (utf16 >> 12))); buf.append((char)(0x80 | ((utf16 >> 6) & 0x3f))); buf.append((char)(0x80 | (utf16 & 0x3f))); } } ALWAYS_INLINE void utf16_to_utf8(UncheckedBuffer &buf, unsigned short utf16) { if (LIKELY(utf16 < 0x80)) { buf.append((char)utf16); return; } return utf16_to_utf8_tail(buf, utf16); } StaticString s__empty_("_empty_"); static void object_set(const json_parser* json, Variant &var, const String& key, const Variant& value, int assoc, JSONContainerType container_type) { if (!assoc) { // We know it is stdClass, and everything is public (and dynamic). if (key.empty()) { var.getObjectData()->setProp(nullptr, s__empty_.get(), *value.asTypedValue()); } else { var.getObjectData()->o_set(key, value); } } else { if (container_type == JSONContainerType::COLLECTIONS) { auto keyTV = make_tv<KindOfString>(key.get()); collections::set(var.getObjectData(), &keyTV, value.asTypedValue()); } else if (container_type == JSONContainerType::HACK_ARRAYS || container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { forceToDict(var).set(key, value); } else { int64_t i; if (key.get()->isStrictlyInteger(i)) { forceToDArray(var).set(i, value); } else { forceToDArray(var).set(key, value); } } if (var.isArray()) { DEBUG_ONLY auto const data = var.getArrayData(); assertx(IMPLIES(arrprov::arrayWantsTag(data), arrprov::getTag(data))); } } } static void attach_zval(json_parser *json, const String& key, int assoc, JSONContainerType container_type) { if (json->top < 1) { return; } auto& root = json->stack[json->top - 1].val; auto& child = json->stack[json->top].val; auto up_mode = json->stack[json->top - 1].mode; if (up_mode == Mode::ARRAY) { if (container_type == JSONContainerType::COLLECTIONS) { collections::append(root.getObjectData(), child.asTypedValue()); } else { root.asArrRef().append(child); } } else if (up_mode == Mode::OBJECT) { object_set(json, root, key, child, assoc, container_type); } } JSONContainerType get_container_type_from_options(int64_t options) { if ((options & k_JSON_FB_STABLE_MAPS) || (options & k_JSON_FB_COLLECTIONS)) { return JSONContainerType::COLLECTIONS; } if (options & k_JSON_FB_HACK_ARRAYS) { return JSONContainerType::HACK_ARRAYS; } if (options & k_JSON_FB_DARRAYS) { return JSONContainerType::DARRAYS; } if (options & k_JSON_FB_DARRAYS_AND_VARRAYS) { return JSONContainerType::DARRAYS_AND_VARRAYS; } if (options & k_JSON_FB_LEGACY_HACK_ARRAYS) { return JSONContainerType::LEGACY_HACK_ARRAYS; } return JSONContainerType::DARRAYS; } /** * The JSON_parser takes a UTF-8 encoded string and determines if it is a * syntactically correct JSON text. Along the way, it creates a PHP variable. * * It is implemented as a Pushdown Automaton; that means it is a finite state * machine with a stack. * * The behavior is as follows: * Container Type | is_assoc | JSON input => output type * * COLLECTIONS | true | "{}" => c_Map * COLLECTIONS | false | "{}" => c_Map * COLLECTIONS | true | "[]" => c_Vector * COLLECTIONS | false | "[]" => c_Vector * * HACK_ARRAYS | true | "{}" => dict * HACK_ARRAYS | false | "{}" => stdClass * HACK_ARRAYS | true | "[]" => vec * HACK_ARRAYS | false | "[]" => stdClass * * DARRAYS | true | "{}" => darray * DARRAYS | false | "{}" => stdClass * DARRAYS | true | "[]" => darray * DARRAYS | false | "[]" => stdClass * * DARRAYS_AND_VARRAYS | true | "{}" => darray * DARRAYS_AND_VARRAYS | false | "{}" => stdClass * DARRAYS_AND_VARRAYS | true | "[]" => varray * DARRAYS_AND_VARRAYS | false | "[]" => stdClass */ bool JSON_parser(Variant &z, const char *p, int length, bool const assoc, int depth, int64_t options) { // No GC safepoints during JSON parsing, please. Code is not re-entrant. NoHandleSurpriseScope no_surprise(SafepointFlags); json_parser *json = s_json_parser.get(); /* the parser state */ // Clear and reuse the thread-local string buffers. They are only freed if // they exceed kMaxPersistentStringBufferCapacity at exit or if the thread // is explicitly flushed (e.g., due to being idle). json->initSb(length); if (depth <= 0) { json->error_code = json_error_codes::JSON_ERROR_DEPTH; return false; } SCOPE_EXIT { constexpr int kMaxPersistentStringBufferCapacity = 256 * 1024; if (json->sb_cap > kMaxPersistentStringBufferCapacity) json->flushSb(); }; // SimpleParser only handles the most common set of options. Also, only use it // if its array nesting depth check is *more* restrictive than what the user // asks for, to ensure that the precise semantics of the general case is // applied for all nesting overflows. if (assoc && options == (options & (k_JSON_FB_LOOSE | k_JSON_FB_DARRAYS | k_JSON_FB_DARRAYS_AND_VARRAYS | k_JSON_FB_HACK_ARRAYS | k_JSON_FB_THRIFT_SIMPLE_JSON | k_JSON_FB_LEGACY_HACK_ARRAYS)) && depth >= SimpleParser::kMaxArrayDepth && length <= RuntimeOption::EvalSimpleJsonMaxLength && SimpleParser::TryParse(p, length, json->tl_buffer.tv, z, get_container_type_from_options(options), options & k_JSON_FB_THRIFT_SIMPLE_JSON)) { return true; } int b; /* the next character */ int c; /* the next character class */ int s; /* the next state */ int state = 0; /*<fb>*/ bool const loose = options & k_JSON_FB_LOOSE; JSONContainerType const container_type = get_container_type_from_options(options); int qchr = 0; int8_t const *byte_class; int8_t const (*next_state_table)[32]; if (loose) { byte_class = loose_ascii_class; next_state_table = loose_state_transition_table; } else { byte_class = ascii_class; next_state_table = state_transition_table; } /*</fb>*/ UncheckedBuffer *buf = &json->sb_buf; UncheckedBuffer *key = &json->sb_key; DataType type = kInvalidDataType; unsigned short escaped_bytes = 0; auto reset_type = [&] { type = kInvalidDataType; }; json->depth = depth; // Since the stack is maintainined on a per request basis, for performance // reasons, it only makes sense to expand if necessary and cycles are wasted // contracting. Calls with a depth other than default should be rare. if (depth > json->stack.size()) { json->stack.resize(depth); } SCOPE_EXIT { if (json->stack.empty()) return; for (int i = 0; i <= json->mark; i++) { json->stack[i].key.reset(); json->stack[i].val.unset(); } json->mark = -1; }; json->mark = json->top = -1; push(json, Mode::DONE); UTF8To16Decoder decoder(p, length, loose); for (;;) { b = decoder.decode(); // Fast-case most common transition: append a simple string character. if (state == 3 && type == KindOfString) { while (b != '\"' && b != '\\' && b != '\'' && b <= 127 && b >= ' ') { buf->append((char)b); b = decoder.decode(); } } if (b == UTF8_END) break; // UTF-8 decoding finishes successfully. if (b == UTF8_ERROR) { s_json_parser->error_code = JSON_ERROR_UTF8; return false; } assertx(b >= 0); if ((b & 127) == b) { /*<fb>*/ c = byte_class[b]; /*</fb>*/ if (c <= S_ERR) { s_json_parser->error_code = JSON_ERROR_CTRL_CHAR; return false; } } else { c = S_ETC; } /* Get the next state from the transition table. */ /*<fb>*/ s = next_state_table[state][c]; if (s == -4) { if (b != qchr) { s = 3; } else { qchr = 0; } } /*</fb>*/ if (s < 0) { /* Perform one of the predefined actions. */ switch (s) { /* empty } */ case -9: /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::KEY)) { return false; } state = 9; break; /* { */ case -8: if (!push(json, Mode::KEY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 1; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { // stable_maps is meaningless top = req::make<c_Map>(); } else { /*</fb>*/ if (!assoc) { top = SystemLib::AllocStdClassObject(); /* <fb> */ } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateDict(); } else if (container_type == JSONContainerType::DARRAYS || container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateDArray(); /* </fb> */ } else if ( container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyDictArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*<fb>*/ } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* } */ case -7: /*** BEGIN Facebook: json_utf8_loose ***/ /* If this is a trailing comma in an object definition, we're in Mode::KEY. In that case, throw that off the stack and restore Mode::OBJECT so that we pretend the trailing comma just didn't happen. */ if (loose) { if (pop(json, Mode::KEY)) { push(json, Mode::OBJECT); } } /*** END Facebook: json_utf8_loose ***/ if (type != kInvalidDataType && json->stack[json->top].mode == Mode::OBJECT) { Variant mval; json_create_zval(mval, *buf, type, options); Variant &top = json->stack[json->top].val; object_set(json, top, copy_and_clear(*key), mval, assoc, container_type); buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::OBJECT)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; break; /* [ */ case -6: if (!push(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_DEPTH; return false; } state = 2; if (json->top > 0) { Variant &top = json->stack[json->top].val; /*<fb>*/ if (container_type == JSONContainerType::COLLECTIONS) { top = req::make<c_Vector>(); } else if (container_type == JSONContainerType::HACK_ARRAYS) { top = Array::CreateVec(); } else if (container_type == JSONContainerType::DARRAYS_AND_VARRAYS) { top = Array::CreateVArray(); } else if (container_type == JSONContainerType::DARRAYS) { top = Array::CreateDArray(); } else if (container_type == JSONContainerType::LEGACY_HACK_ARRAYS) { auto arr = staticEmptyVecArray()->copy(); arr->setLegacyArray(true); top = arr; } else { top = Array::CreateDArray(); } /*</fb>*/ json->stack[json->top].key = copy_and_clear(*key); reset_type(); } break; /* ] */ case -5: { if (type != kInvalidDataType && json->stack[json->top].mode == Mode::ARRAY) { Variant mval; json_create_zval(mval, *buf, type, options); auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } buf->clear(); reset_type(); } /*<fb>*/ if (json->top == 1) z = json->stack[json->top].val; else { /*</fb>*/ attach_zval(json, json->stack[json->top].key, assoc, container_type); /*<fb>*/ } /*</fb>*/ if (!pop(json, Mode::ARRAY)) { s_json_parser->error_code = JSON_ERROR_STATE_MISMATCH; return false; } state = 9; } break; /* " */ case -4: switch (json->stack[json->top].mode) { case Mode::KEY: state = 27; std::swap(buf, key); reset_type(); break; case Mode::ARRAY: case Mode::OBJECT: state = 9; break; case Mode::DONE: if (type == KindOfString) { z = copy_and_clear(*buf); state = 9; break; } /* fall through if not KindOfString */ default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } break; /* , */ case -3: { Variant mval; if (type != kInvalidDataType && (json->stack[json->top].mode == Mode::OBJECT || json->stack[json->top].mode == Mode::ARRAY)) { json_create_zval(mval, *buf, type, options); } switch (json->stack[json->top].mode) { case Mode::OBJECT: if (pop(json, Mode::OBJECT) && push(json, Mode::KEY)) { if (type != kInvalidDataType) { Variant &top = json->stack[json->top].val; object_set( json, top, copy_and_clear(*key), mval, assoc, container_type ); } state = 29; } break; case Mode::ARRAY: if (type != kInvalidDataType) { auto& top = json->stack[json->top].val; if (container_type == JSONContainerType::COLLECTIONS) { collections::append(top.getObjectData(), mval.asTypedValue()); } else { top.asArrRef().append(mval); } } state = 28; break; default: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } buf->clear(); reset_type(); check_non_safepoint_surprise(); } break; /*<fb>*/ /* : (after unquoted string) */ case -10: if (json->stack[json->top].mode == Mode::KEY) { state = 27; std::swap(buf, key); reset_type(); s = -2; } else { s = 3; break; } /*</fb>*/ /* : */ case -2: if (pop(json, Mode::KEY) && push(json, Mode::OBJECT)) { state = 28; break; } /* syntax error */ case -1: s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { /* Change the state and iterate. */ bool is_tsimplejson = options & k_JSON_FB_THRIFT_SIMPLE_JSON; if (type == KindOfString) { if (/*<fb>*/(/*</fb>*/s == 3/*<fb>*/ || s == 30)/*</fb>*/ && state != 8) { if (state != 4) { utf16_to_utf8(*buf, b); } else { switch (b) { case 'b': buf->append('\b'); break; case 't': buf->append('\t'); break; case 'n': buf->append('\n'); break; case 'f': buf->append('\f'); break; case 'r': buf->append('\r'); break; default: utf16_to_utf8(*buf, b); break; } } } else if (s == 6) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } escaped_bytes = 0; } else { escaped_bytes = dehexchar(b) << 12; } } else if (s == 7) { if (UNLIKELY(is_tsimplejson)) { if (UNLIKELY(b != '0')) { s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } else { escaped_bytes += dehexchar(b) << 8; } } else if (s == 8) { escaped_bytes += dehexchar(b) << 4; } else if (s == 3 && state == 8) { escaped_bytes += dehexchar(b); if (UNLIKELY(is_tsimplejson)) { buf->append((char)escaped_bytes); } else { utf16_to_utf8(*buf, escaped_bytes); } } } else if ((type == kInvalidDataType || type == KindOfNull) && (c == S_DIG || c == S_ZER)) { type = KindOfInt64; buf->append((char)b); } else if (type == KindOfInt64 && s == 24) { type = KindOfDouble; buf->append((char)b); } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64) && c == S_DOT) { type = KindOfDouble; buf->append((char)b); } else if (type != KindOfString && c == S_QUO) { type = KindOfString; /*<fb>*/qchr = b;/*</fb>*/ } else if ((type == kInvalidDataType || type == KindOfNull || type == KindOfInt64 || type == KindOfDouble) && ((state == 12 && s == 9) || (state == 16 && s == 9))) { type = KindOfBoolean; } else if (type == kInvalidDataType && state == 19 && s == 9) { type = KindOfNull; } else if (type != KindOfString && c > S_WSP) { utf16_to_utf8(*buf, b); } state = s; } } if (state == 9 && pop(json, Mode::DONE)) { s_json_parser->error_code = JSON_ERROR_NONE; return true; } s_json_parser->error_code = JSON_ERROR_SYNTAX; return false; } } #endif /* HAVE_JSONC */
./CrossVul/dataset_final_sorted/CWE-125/cpp/bad_4251_0
crossvul-cpp_data_good_849_0
/* * Copyright (c) Facebook, Inc. and its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/io/async/AsyncSSLSocket.h> #include <folly/io/async/EventBase.h> #include <folly/portability/Sockets.h> #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <chrono> #include <memory> #include <folly/Format.h> #include <folly/Indestructible.h> #include <folly/SocketAddress.h> #include <folly/SpinLock.h> #include <folly/io/Cursor.h> #include <folly/io/IOBuf.h> #include <folly/io/async/ssl/BasicTransportCertificate.h> #include <folly/lang/Bits.h> #include <folly/portability/OpenSSL.h> using folly::SocketAddress; using folly::SSLContext; using std::shared_ptr; using std::string; using folly::Endian; using folly::IOBuf; using folly::SpinLock; using folly::SpinLockGuard; using folly::io::Cursor; using std::bind; using std::unique_ptr; namespace { using folly::AsyncSocket; using folly::AsyncSocketException; using folly::AsyncSSLSocket; using folly::Optional; using folly::SSLContext; // For OpenSSL portability API using namespace folly::ssl; using folly::ssl::OpenSSLUtils; // We have one single dummy SSL context so that we can implement attach // and detach methods in a thread safe fashion without modifying opnessl. static SSLContext* dummyCtx = nullptr; static SpinLock dummyCtxLock; // If given min write size is less than this, buffer will be allocated on // stack, otherwise it is allocated on heap const size_t MAX_STACK_BUF_SIZE = 2048; // This converts "illegal" shutdowns into ZERO_RETURN inline bool zero_return(int error, int rc, int errno_copy) { if (error == SSL_ERROR_ZERO_RETURN || (rc == 0 && errno_copy == 0)) { return true; } #ifdef _WIN32 // on windows underlying TCP socket may error with this code // if the sending/receiving client crashes or is killed if (error == SSL_ERROR_SYSCALL && errno_copy == WSAECONNRESET) { return true; } #endif return false; } class AsyncSSLSocketConnector : public AsyncSocket::ConnectCallback, public AsyncSSLSocket::HandshakeCB { private: AsyncSSLSocket* sslSocket_; AsyncSSLSocket::ConnectCallback* callback_; std::chrono::milliseconds timeout_; std::chrono::steady_clock::time_point startTime_; protected: ~AsyncSSLSocketConnector() override {} public: AsyncSSLSocketConnector( AsyncSSLSocket* sslSocket, AsyncSocket::ConnectCallback* callback, std::chrono::milliseconds timeout) : sslSocket_(sslSocket), callback_(callback), timeout_(timeout), startTime_(std::chrono::steady_clock::now()) {} void preConnect(folly::NetworkSocket fd) override { VLOG(7) << "client preConnect hook is invoked"; if (callback_) { callback_->preConnect(fd); } } void connectSuccess() noexcept override { VLOG(7) << "client socket connected"; std::chrono::milliseconds timeoutLeft{0}; if (timeout_ > std::chrono::milliseconds::zero()) { auto curTime = std::chrono::steady_clock::now(); timeoutLeft = std::chrono::duration_cast<std::chrono::milliseconds>( timeout_ - (curTime - startTime_)); if (timeoutLeft <= std::chrono::milliseconds::zero()) { AsyncSocketException ex( AsyncSocketException::TIMED_OUT, folly::sformat( "SSL connect timed out after {}ms", timeout_.count())); fail(ex); delete this; return; } } sslSocket_->sslConn(this, timeoutLeft); } void connectErr(const AsyncSocketException& ex) noexcept override { VLOG(1) << "TCP connect failed: " << ex.what(); fail(ex); delete this; } void handshakeSuc(AsyncSSLSocket* /* sock */) noexcept override { VLOG(7) << "client handshake success"; if (callback_) { callback_->connectSuccess(); } delete this; } void handshakeErr( AsyncSSLSocket* /* socket */, const AsyncSocketException& ex) noexcept override { VLOG(1) << "client handshakeErr: " << ex.what(); fail(ex); delete this; } void fail(const AsyncSocketException& ex) { // fail is a noop if called twice if (callback_) { AsyncSSLSocket::ConnectCallback* cb = callback_; callback_ = nullptr; cb->connectErr(ex); sslSocket_->closeNow(); // closeNow can call handshakeErr if it hasn't been called already. // So this may have been deleted, no member variable access beyond this // point // Note that closeNow may invoke writeError callbacks if the socket had // write data pending connection completion. } } }; void setup_SSL_CTX(SSL_CTX* ctx) { #ifdef SSL_MODE_RELEASE_BUFFERS SSL_CTX_set_mode( ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_RELEASE_BUFFERS); #else SSL_CTX_set_mode( ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE); #endif // SSL_CTX_set_mode is a Macro #ifdef SSL_MODE_WRITE_IOVEC SSL_CTX_set_mode(ctx, SSL_CTX_get_mode(ctx) | SSL_MODE_WRITE_IOVEC); #endif } // Note: This is a Leaky Meyer's Singleton. The reason we can't use a non-leaky // thing is because we will be setting this BIO_METHOD* inside BIOs owned by // various SSL objects which may get callbacks even during teardown. We may // eventually try to fix this static BIO_METHOD* getSSLBioMethod() { static auto const instance = OpenSSLUtils::newSocketBioMethod().release(); return instance; } void* initsslBioMethod() { auto sslBioMethod = getSSLBioMethod(); // override the bwrite method for MSG_EOR support OpenSSLUtils::setCustomBioWriteMethod(sslBioMethod, AsyncSSLSocket::bioWrite); OpenSSLUtils::setCustomBioReadMethod(sslBioMethod, AsyncSSLSocket::bioRead); // Note that the sslBioMethod.type and sslBioMethod.name are not // set here. openssl code seems to be checking ".type == BIO_TYPE_SOCKET" and // then have specific handlings. The sslWriteBioWrite should be compatible // with the one in openssl. // Return something here to enable AsyncSSLSocket to call this method using // a function-scoped static. return nullptr; } } // namespace namespace folly { /** * Create a client AsyncSSLSocket */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, bool deferSecurityNegotiation) : AsyncSocket(evb), ctx_(ctx), handshakeTimeout_(this, evb), connectionTimeout_(this, evb) { init(); if (deferSecurityNegotiation) { sslState_ = STATE_UNENCRYPTED; } } /** * Create a server/client AsyncSSLSocket */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, NetworkSocket fd, bool server, bool deferSecurityNegotiation) : AsyncSocket(evb, fd), server_(server), ctx_(ctx), handshakeTimeout_(this, evb), connectionTimeout_(this, evb) { noTransparentTls_ = true; init(); if (server) { SSL_CTX_set_info_callback( ctx_->getSSLCtx(), AsyncSSLSocket::sslInfoCallback); } if (deferSecurityNegotiation) { sslState_ = STATE_UNENCRYPTED; } } AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, AsyncSocket::UniquePtr oldAsyncSocket, bool server, bool deferSecurityNegotiation) : AsyncSocket(std::move(oldAsyncSocket)), server_(server), ctx_(ctx), handshakeTimeout_(this, AsyncSocket::getEventBase()), connectionTimeout_(this, AsyncSocket::getEventBase()) { noTransparentTls_ = true; init(); if (server) { SSL_CTX_set_info_callback( ctx_->getSSLCtx(), AsyncSSLSocket::sslInfoCallback); } if (deferSecurityNegotiation) { sslState_ = STATE_UNENCRYPTED; } } #if FOLLY_OPENSSL_HAS_SNI /** * Create a client AsyncSSLSocket and allow tlsext_hostname * to be sent in Client Hello. */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, const std::string& serverName, bool deferSecurityNegotiation) : AsyncSSLSocket(ctx, evb, deferSecurityNegotiation) { tlsextHostname_ = serverName; } /** * Create a client AsyncSSLSocket from an already connected fd * and allow tlsext_hostname to be sent in Client Hello. */ AsyncSSLSocket::AsyncSSLSocket( const shared_ptr<SSLContext>& ctx, EventBase* evb, NetworkSocket fd, const std::string& serverName, bool deferSecurityNegotiation) : AsyncSSLSocket(ctx, evb, fd, false, deferSecurityNegotiation) { tlsextHostname_ = serverName; } #endif // FOLLY_OPENSSL_HAS_SNI AsyncSSLSocket::~AsyncSSLSocket() { VLOG(3) << "actual destruction of AsyncSSLSocket(this=" << this << ", evb=" << eventBase_ << ", fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << ")"; } void AsyncSSLSocket::init() { // Do this here to ensure we initialize this once before any use of // AsyncSSLSocket instances and not as part of library load. static const auto sslBioMethodInitializer = initsslBioMethod(); (void)sslBioMethodInitializer; setup_SSL_CTX(ctx_->getSSLCtx()); } void AsyncSSLSocket::closeNow() { // Close the SSL connection. if (ssl_ != nullptr && fd_ != NetworkSocket() && !waitingOnAccept_) { int rc = SSL_shutdown(ssl_.get()); if (rc == 0) { rc = SSL_shutdown(ssl_.get()); } if (rc < 0) { ERR_clear_error(); } } if (sslSession_ != nullptr) { SSL_SESSION_free(sslSession_); sslSession_ = nullptr; } sslState_ = STATE_CLOSED; if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } DestructorGuard dg(this); static const Indestructible<AsyncSocketException> ex( AsyncSocketException::END_OF_FILE, "SSL connection closed locally"); invokeHandshakeErr(*ex); // Close the socket. AsyncSocket::closeNow(); } void AsyncSSLSocket::shutdownWrite() { // SSL sockets do not support half-shutdown, so just perform a full shutdown. // // (Performing a full shutdown here is more desirable than doing nothing at // all. The purpose of shutdownWrite() is normally to notify the other end // of the connection that no more data will be sent. If we do nothing, the // other end will never know that no more data is coming, and this may result // in protocol deadlock.) close(); } void AsyncSSLSocket::shutdownWriteNow() { closeNow(); } bool AsyncSSLSocket::good() const { return ( AsyncSocket::good() && (sslState_ == STATE_ACCEPTING || sslState_ == STATE_CONNECTING || sslState_ == STATE_ESTABLISHED || sslState_ == STATE_UNENCRYPTED || sslState_ == STATE_UNINIT)); } // The TAsyncTransport definition of 'good' states that the transport is // ready to perform reads and writes, so sslState_ == UNINIT must report !good. // connecting can be true when the sslState_ == UNINIT because the AsyncSocket // is connected but we haven't initiated the call to SSL_connect. bool AsyncSSLSocket::connecting() const { return ( !server_ && (AsyncSocket::connecting() || (AsyncSocket::good() && (sslState_ == STATE_UNINIT || sslState_ == STATE_CONNECTING)))); } std::string AsyncSSLSocket::getApplicationProtocol() const noexcept { const unsigned char* protoName = nullptr; unsigned protoLength; if (getSelectedNextProtocolNoThrow(&protoName, &protoLength)) { return std::string(reinterpret_cast<const char*>(protoName), protoLength); } return ""; } void AsyncSSLSocket::setEorTracking(bool track) { if (isEorTrackingEnabled() != track) { AsyncSocket::setEorTracking(track); appEorByteNo_ = 0; appEorByteWriteFlags_ = {}; minEorRawByteNo_ = 0; } } size_t AsyncSSLSocket::getRawBytesWritten() const { // The bio(s) in the write path are in a chain // each bio flushes to the next and finally written into the socket // to get the rawBytesWritten on the socket, // get the write bytes of the last bio BIO* b; if (!ssl_ || !(b = SSL_get_wbio(ssl_.get()))) { return 0; } BIO* next = BIO_next(b); while (next != nullptr) { b = next; next = BIO_next(b); } return BIO_number_written(b); } size_t AsyncSSLSocket::getRawBytesReceived() const { BIO* b; if (!ssl_ || !(b = SSL_get_rbio(ssl_.get()))) { return 0; } return BIO_number_read(b); } void AsyncSSLSocket::invalidState(HandshakeCB* callback) { LOG(ERROR) << "AsyncSSLSocket(this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", " << "events=" << eventFlags_ << ", server=" << short(server_) << "): " << "sslAccept/Connect() called in invalid " << "state, handshake callback " << handshakeCallback_ << ", new callback " << callback; assert(!handshakeTimeout_.isScheduled()); sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INVALID_STATE, "sslAccept() called with socket in invalid state"); handshakeEndTime_ = std::chrono::steady_clock::now(); if (callback) { callback->handshakeErr(this, *ex); } failHandshake(__func__, *ex); } void AsyncSSLSocket::sslAccept( HandshakeCB* callback, std::chrono::milliseconds timeout, const SSLContext::SSLVerifyPeerEnum& verifyPeer) { DestructorGuard dg(this); eventBase_->dcheckIsInEventBaseThread(); verifyPeer_ = verifyPeer; // Make sure we're in the uninitialized state if (!server_ || (sslState_ != STATE_UNINIT && sslState_ != STATE_UNENCRYPTED) || handshakeCallback_ != nullptr) { return invalidState(callback); } // Cache local and remote socket addresses to keep them available // after socket file descriptor is closed. if (cacheAddrOnFailure_) { cacheAddresses(); } handshakeStartTime_ = std::chrono::steady_clock::now(); // Make end time at least >= start time. handshakeEndTime_ = handshakeStartTime_; sslState_ = STATE_ACCEPTING; handshakeCallback_ = callback; if (timeout > std::chrono::milliseconds::zero()) { handshakeTimeout_.scheduleTimeout(timeout); } /* register for a read operation (waiting for CLIENT HELLO) */ updateEventRegistration(EventHandler::READ, EventHandler::WRITE); checkForImmediateRead(); } void AsyncSSLSocket::attachSSLContext(const std::shared_ptr<SSLContext>& ctx) { // Check to ensure we are in client mode. Changing a server's ssl // context doesn't make sense since clients of that server would likely // become confused when the server's context changes. DCHECK(!server_); DCHECK(!ctx_); DCHECK(ctx); DCHECK(ctx->getSSLCtx()); ctx_ = ctx; // It's possible this could be attached before ssl_ is set up if (!ssl_) { return; } // In order to call attachSSLContext, detachSSLContext must have been // previously called. // We need to update the initial_ctx if necessary // The 'initial_ctx' inside an SSL* points to the context that it was created // with, which is also where session callbacks and servername callbacks // happen. // When we switch to a different SSL_CTX, we want to update the initial_ctx as // well so that any callbacks don't go to a different object // NOTE: this will only work if we have access to ssl_ internals, so it may // not work on // OpenSSL version >= 1.1.0 auto sslCtx = ctx->getSSLCtx(); OpenSSLUtils::setSSLInitialCtx(ssl_.get(), sslCtx); // Detach sets the socket's context to the dummy context. Thus we must acquire // this lock. SpinLockGuard guard(dummyCtxLock); SSL_set_SSL_CTX(ssl_.get(), sslCtx); } void AsyncSSLSocket::detachSSLContext() { DCHECK(ctx_); ctx_.reset(); // It's possible for this to be called before ssl_ has been // set up if (!ssl_) { return; } // The 'initial_ctx' inside an SSL* points to the context that it was created // with, which is also where session callbacks and servername callbacks // happen. // Detach the initial_ctx as well. It will be reattached in attachSSLContext // it is used for session info. // NOTE: this will only work if we have access to ssl_ internals, so it may // not work on // OpenSSL version >= 1.1.0 SSL_CTX* initialCtx = OpenSSLUtils::getSSLInitialCtx(ssl_.get()); if (initialCtx) { SSL_CTX_free(initialCtx); OpenSSLUtils::setSSLInitialCtx(ssl_.get(), nullptr); } SpinLockGuard guard(dummyCtxLock); if (nullptr == dummyCtx) { // We need to lazily initialize the dummy context so we don't // accidentally override any programmatic settings to openssl dummyCtx = new SSLContext; } // We must remove this socket's references to its context right now // since this socket could get passed to any thread. If the context has // had its locking disabled, just doing a set in attachSSLContext() // would not be thread safe. SSL_set_SSL_CTX(ssl_.get(), dummyCtx->getSSLCtx()); } #if FOLLY_OPENSSL_HAS_SNI void AsyncSSLSocket::switchServerSSLContext( const std::shared_ptr<SSLContext>& handshakeCtx) { CHECK(server_); if (sslState_ != STATE_ACCEPTING) { // We log it here and allow the switch. // It should not affect our re-negotiation support (which // is not supported now). VLOG(6) << "fd=" << getNetworkSocket() << " renegotation detected when switching SSL_CTX"; } setup_SSL_CTX(handshakeCtx->getSSLCtx()); SSL_CTX_set_info_callback( handshakeCtx->getSSLCtx(), AsyncSSLSocket::sslInfoCallback); handshakeCtx_ = handshakeCtx; SSL_set_SSL_CTX(ssl_.get(), handshakeCtx->getSSLCtx()); } bool AsyncSSLSocket::isServerNameMatch() const { CHECK(!server_); if (!ssl_) { return false; } SSL_SESSION* ss = SSL_get_session(ssl_.get()); if (!ss) { return false; } auto tlsextHostname = SSL_SESSION_get0_hostname(ss); return (tlsextHostname && !tlsextHostname_.compare(tlsextHostname)); } void AsyncSSLSocket::setServerName(std::string serverName) noexcept { tlsextHostname_ = std::move(serverName); } #endif // FOLLY_OPENSSL_HAS_SNI void AsyncSSLSocket::timeoutExpired( std::chrono::milliseconds timeout) noexcept { if (state_ == StateEnum::ESTABLISHED && sslState_ == STATE_ASYNC_PENDING) { sslState_ = STATE_ERROR; // We are expecting a callback in restartSSLAccept. The cache lookup // and rsa-call necessarily have pointers to this ssl socket, so delay // the cleanup until he calls us back. } else if (state_ == StateEnum::CONNECTING) { assert(sslState_ == STATE_CONNECTING); DestructorGuard dg(this); static const Indestructible<AsyncSocketException> ex( AsyncSocketException::TIMED_OUT, "Fallback connect timed out during TFO"); failHandshake(__func__, *ex); } else { assert( state_ == StateEnum::ESTABLISHED && (sslState_ == STATE_CONNECTING || sslState_ == STATE_ACCEPTING)); DestructorGuard dg(this); AsyncSocketException ex( AsyncSocketException::TIMED_OUT, folly::sformat( "SSL {} timed out after {}ms", (sslState_ == STATE_CONNECTING) ? "connect" : "accept", timeout.count())); failHandshake(__func__, ex); } } int AsyncSSLSocket::getSSLExDataIndex() { static auto index = SSL_get_ex_new_index( 0, (void*)"AsyncSSLSocket data index", nullptr, nullptr, nullptr); return index; } AsyncSSLSocket* AsyncSSLSocket::getFromSSL(const SSL* ssl) { return static_cast<AsyncSSLSocket*>( SSL_get_ex_data(ssl, getSSLExDataIndex())); } void AsyncSSLSocket::failHandshake( const char* /* fn */, const AsyncSocketException& ex) { startFail(); if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } invokeHandshakeErr(ex); finishFail(); } void AsyncSSLSocket::invokeHandshakeErr(const AsyncSocketException& ex) { handshakeEndTime_ = std::chrono::steady_clock::now(); if (handshakeCallback_ != nullptr) { HandshakeCB* callback = handshakeCallback_; handshakeCallback_ = nullptr; callback->handshakeErr(this, ex); } } void AsyncSSLSocket::invokeHandshakeCB() { handshakeEndTime_ = std::chrono::steady_clock::now(); if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } if (handshakeCallback_) { HandshakeCB* callback = handshakeCallback_; handshakeCallback_ = nullptr; callback->handshakeSuc(this); } } void AsyncSSLSocket::connect( ConnectCallback* callback, const folly::SocketAddress& address, int timeout, const OptionMap& options, const folly::SocketAddress& bindAddr) noexcept { auto timeoutChrono = std::chrono::milliseconds(timeout); connect(callback, address, timeoutChrono, timeoutChrono, options, bindAddr); } void AsyncSSLSocket::connect( ConnectCallback* callback, const folly::SocketAddress& address, std::chrono::milliseconds connectTimeout, std::chrono::milliseconds totalConnectTimeout, const OptionMap& options, const folly::SocketAddress& bindAddr) noexcept { assert(!server_); assert(state_ == StateEnum::UNINIT); assert(sslState_ == STATE_UNINIT || sslState_ == STATE_UNENCRYPTED); noTransparentTls_ = true; totalConnectTimeout_ = totalConnectTimeout; if (sslState_ != STATE_UNENCRYPTED) { callback = new AsyncSSLSocketConnector(this, callback, totalConnectTimeout); } AsyncSocket::connect( callback, address, int(connectTimeout.count()), options, bindAddr); } bool AsyncSSLSocket::needsPeerVerification() const { if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) { return ctx_->needsPeerVerification(); } return ( verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY || verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT); } void AsyncSSLSocket::applyVerificationOptions(const ssl::SSLUniquePtr& ssl) { // apply the settings specified in verifyPeer_ if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::USE_CTX) { if (ctx_->needsPeerVerification()) { SSL_set_verify( ssl.get(), ctx_->getVerificationMode(), AsyncSSLSocket::sslVerifyCallback); } } else { if (verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY || verifyPeer_ == SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT) { SSL_set_verify( ssl.get(), SSLContext::getVerificationMode(verifyPeer_), AsyncSSLSocket::sslVerifyCallback); } } } bool AsyncSSLSocket::setupSSLBio() { auto sslBio = BIO_new(getSSLBioMethod()); if (!sslBio) { return false; } OpenSSLUtils::setBioAppData(sslBio, this); OpenSSLUtils::setBioFd(sslBio, fd_, BIO_NOCLOSE); SSL_set_bio(ssl_.get(), sslBio, sslBio); return true; } void AsyncSSLSocket::sslConn( HandshakeCB* callback, std::chrono::milliseconds timeout, const SSLContext::SSLVerifyPeerEnum& verifyPeer) { DestructorGuard dg(this); eventBase_->dcheckIsInEventBaseThread(); // Cache local and remote socket addresses to keep them available // after socket file descriptor is closed. if (cacheAddrOnFailure_) { cacheAddresses(); } verifyPeer_ = verifyPeer; // Make sure we're in the uninitialized state if (server_ || (sslState_ != STATE_UNINIT && sslState_ != STATE_UNENCRYPTED) || handshakeCallback_ != nullptr) { return invalidState(callback); } sslState_ = STATE_CONNECTING; handshakeCallback_ = callback; try { ssl_.reset(ctx_->createSSL()); } catch (std::exception& e) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error calling SSLContext::createSSL()"); LOG(ERROR) << "AsyncSSLSocket::sslConn(this=" << this << ", fd=" << fd_ << "): " << e.what(); return failHandshake(__func__, *ex); } if (!setupSSLBio()) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error creating SSL bio"); return failHandshake(__func__, *ex); } applyVerificationOptions(ssl_); if (sslSession_ != nullptr) { sessionResumptionAttempted_ = true; SSL_set_session(ssl_.get(), sslSession_); SSL_SESSION_free(sslSession_); sslSession_ = nullptr; } #if FOLLY_OPENSSL_HAS_SNI if (tlsextHostname_.size()) { SSL_set_tlsext_host_name(ssl_.get(), tlsextHostname_.c_str()); } #endif SSL_set_ex_data(ssl_.get(), getSSLExDataIndex(), this); handshakeConnectTimeout_ = timeout; startSSLConnect(); } // This could be called multiple times, during normal ssl connections // and after TFO fallback. void AsyncSSLSocket::startSSLConnect() { handshakeStartTime_ = std::chrono::steady_clock::now(); // Make end time at least >= start time. handshakeEndTime_ = handshakeStartTime_; if (handshakeConnectTimeout_ > std::chrono::milliseconds::zero()) { handshakeTimeout_.scheduleTimeout(handshakeConnectTimeout_); } handleConnect(); } SSL_SESSION* AsyncSSLSocket::getSSLSession() { if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) { return SSL_get1_session(ssl_.get()); } return sslSession_; } const SSL* AsyncSSLSocket::getSSL() const { return ssl_.get(); } void AsyncSSLSocket::setSSLSession(SSL_SESSION* session, bool takeOwnership) { if (sslSession_) { SSL_SESSION_free(sslSession_); } sslSession_ = session; if (!takeOwnership && session != nullptr) { // Increment the reference count // This API exists in BoringSSL and OpenSSL 1.1.0 SSL_SESSION_up_ref(session); } } void AsyncSSLSocket::getSelectedNextProtocol( const unsigned char** protoName, unsigned* protoLen) const { if (!getSelectedNextProtocolNoThrow(protoName, protoLen)) { throw AsyncSocketException( AsyncSocketException::NOT_SUPPORTED, "ALPN not supported"); } } bool AsyncSSLSocket::getSelectedNextProtocolNoThrow( const unsigned char** protoName, unsigned* protoLen) const { *protoName = nullptr; *protoLen = 0; #if FOLLY_OPENSSL_HAS_ALPN SSL_get0_alpn_selected(ssl_.get(), protoName, protoLen); return true; #else return false; #endif } bool AsyncSSLSocket::getSSLSessionReused() const { if (ssl_ != nullptr && sslState_ == STATE_ESTABLISHED) { return SSL_session_reused(ssl_.get()); } return false; } const char* AsyncSSLSocket::getNegotiatedCipherName() const { return (ssl_ != nullptr) ? SSL_get_cipher_name(ssl_.get()) : nullptr; } /* static */ const char* AsyncSSLSocket::getSSLServerNameFromSSL(SSL* ssl) { if (ssl == nullptr) { return nullptr; } #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB return SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); #else return nullptr; #endif } const char* AsyncSSLSocket::getSSLServerName() const { if (clientHelloInfo_ && !clientHelloInfo_->clientHelloSNIHostname_.empty()) { return clientHelloInfo_->clientHelloSNIHostname_.c_str(); } #ifdef SSL_CTRL_SET_TLSEXT_SERVERNAME_CB return getSSLServerNameFromSSL(ssl_.get()); #else throw AsyncSocketException( AsyncSocketException::NOT_SUPPORTED, "SNI not supported"); #endif } const char* AsyncSSLSocket::getSSLServerNameNoThrow() const { if (clientHelloInfo_ && !clientHelloInfo_->clientHelloSNIHostname_.empty()) { return clientHelloInfo_->clientHelloSNIHostname_.c_str(); } return getSSLServerNameFromSSL(ssl_.get()); } int AsyncSSLSocket::getSSLVersion() const { return (ssl_ != nullptr) ? SSL_version(ssl_.get()) : 0; } const char* AsyncSSLSocket::getSSLCertSigAlgName() const { X509* cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_.get()) : nullptr; if (cert) { int nid = X509_get_signature_nid(cert); return OBJ_nid2ln(nid); } return nullptr; } int AsyncSSLSocket::getSSLCertSize() const { int certSize = 0; X509* cert = (ssl_ != nullptr) ? SSL_get_certificate(ssl_.get()) : nullptr; if (cert) { EVP_PKEY* key = X509_get_pubkey(cert); certSize = EVP_PKEY_bits(key); EVP_PKEY_free(key); } return certSize; } const AsyncTransportCertificate* AsyncSSLSocket::getPeerCertificate() const { if (peerCertData_) { return peerCertData_.get(); } if (ssl_ != nullptr) { auto peerX509 = SSL_get_peer_certificate(ssl_.get()); if (peerX509) { // already up ref'd folly::ssl::X509UniquePtr peer(peerX509); auto cn = OpenSSLUtils::getCommonName(peerX509); peerCertData_ = std::make_unique<BasicTransportCertificate>( std::move(cn), std::move(peer)); } } return peerCertData_.get(); } const AsyncTransportCertificate* AsyncSSLSocket::getSelfCertificate() const { if (selfCertData_) { return selfCertData_.get(); } if (ssl_ != nullptr) { auto selfX509 = SSL_get_certificate(ssl_.get()); if (selfX509) { // need to upref X509_up_ref(selfX509); folly::ssl::X509UniquePtr peer(selfX509); auto cn = OpenSSLUtils::getCommonName(selfX509); selfCertData_ = std::make_unique<BasicTransportCertificate>( std::move(cn), std::move(peer)); } } return selfCertData_.get(); } bool AsyncSSLSocket::willBlock( int ret, int* sslErrorOut, unsigned long* errErrorOut) noexcept { *errErrorOut = 0; int error = *sslErrorOut = SSL_get_error(ssl_.get(), ret); if (error == SSL_ERROR_WANT_READ) { // Register for read event if not already. updateEventRegistration(EventHandler::READ, EventHandler::WRITE); return true; } else if (error == SSL_ERROR_WANT_WRITE) { VLOG(3) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "SSL_ERROR_WANT_WRITE"; // Register for write event if not already. updateEventRegistration(EventHandler::WRITE, EventHandler::READ); return true; } else if ((false #ifdef SSL_ERROR_WANT_ASYNC // OpenSSL 1.1.0 Async API || error == SSL_ERROR_WANT_ASYNC #endif )) { // An asynchronous request has been kicked off. On completion, it will // invoke a callback to re-call handleAccept sslState_ = STATE_ASYNC_PENDING; // Unregister for all events while blocked here updateEventRegistration( EventHandler::NONE, EventHandler::READ | EventHandler::WRITE); #ifdef SSL_ERROR_WANT_ASYNC if (error == SSL_ERROR_WANT_ASYNC) { size_t numfds; if (SSL_get_all_async_fds(ssl_.get(), NULL, &numfds) <= 0) { VLOG(4) << "SSL_ERROR_WANT_ASYNC but no async FDs set!"; return false; } if (numfds != 1) { VLOG(4) << "SSL_ERROR_WANT_ASYNC expected exactly 1 async fd, got " << numfds; return false; } OSSL_ASYNC_FD ofd; // This should just be an int in POSIX if (SSL_get_all_async_fds(ssl_.get(), &ofd, &numfds) <= 0) { VLOG(4) << "SSL_ERROR_WANT_ASYNC cant get async fd"; return false; } // On POSIX systems, OSSL_ASYNC_FD is type int, but on win32 // it has type HANDLE. // Our NetworkSocket::native_handle_type is type SOCKET on // win32, which means that we need to explicitly construct // a native handle type to pass to the constructor. auto native_handle = NetworkSocket::native_handle_type(ofd); auto asyncPipeReader = AsyncPipeReader::newReader(eventBase_, NetworkSocket(native_handle)); auto asyncPipeReaderPtr = asyncPipeReader.get(); if (!asyncOperationFinishCallback_) { asyncOperationFinishCallback_.reset( new DefaultOpenSSLAsyncFinishCallback( std::move(asyncPipeReader), this, DestructorGuard(this))); } asyncPipeReaderPtr->setReadCB(asyncOperationFinishCallback_.get()); } #endif // The timeout (if set) keeps running here return true; } else { unsigned long lastError = *errErrorOut = ERR_get_error(); VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", " << "state=" << state_ << ", " << "sslState=" << sslState_ << ", " << "events=" << std::hex << eventFlags_ << "): " << "SSL error: " << error << ", " << "errno: " << errno << ", " << "ret: " << ret << ", " << "read: " << BIO_number_read(SSL_get_rbio(ssl_.get())) << ", " << "written: " << BIO_number_written(SSL_get_wbio(ssl_.get())) << ", " << "func: " << ERR_func_error_string(lastError) << ", " << "reason: " << ERR_reason_error_string(lastError); return false; } } void AsyncSSLSocket::checkForImmediateRead() noexcept { // openssl may have buffered data that it read from the socket already. // In this case we have to process it immediately, rather than waiting for // the socket to become readable again. if (ssl_ != nullptr && SSL_pending(ssl_.get()) > 0) { AsyncSocket::handleRead(); } else { AsyncSocket::checkForImmediateRead(); } } void AsyncSSLSocket::restartSSLAccept() { VLOG(3) << "AsyncSSLSocket::restartSSLAccept() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; DestructorGuard dg(this); assert( sslState_ == STATE_ASYNC_PENDING || sslState_ == STATE_ERROR || sslState_ == STATE_CLOSED); if (sslState_ == STATE_CLOSED) { // I sure hope whoever closed this socket didn't delete it already, // but this is not strictly speaking an error return; } if (sslState_ == STATE_ERROR) { // go straight to fail if timeout expired during lookup static const Indestructible<AsyncSocketException> ex( AsyncSocketException::TIMED_OUT, "SSL accept timed out"); failHandshake(__func__, *ex); return; } sslState_ = STATE_ACCEPTING; this->handleAccept(); } void AsyncSSLSocket::handleAccept() noexcept { VLOG(3) << "AsyncSSLSocket::handleAccept() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; assert(server_); assert(state_ == StateEnum::ESTABLISHED && sslState_ == STATE_ACCEPTING); if (!ssl_) { /* lazily create the SSL structure */ try { ssl_.reset(ctx_->createSSL()); } catch (std::exception& e) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error calling SSLContext::createSSL()"); LOG(ERROR) << "AsyncSSLSocket::handleAccept(this=" << this << ", fd=" << fd_ << "): " << e.what(); return failHandshake(__func__, *ex); } if (!setupSSLBio()) { sslState_ = STATE_ERROR; static const Indestructible<AsyncSocketException> ex( AsyncSocketException::INTERNAL_ERROR, "error creating write bio"); return failHandshake(__func__, *ex); } SSL_set_ex_data(ssl_.get(), getSSLExDataIndex(), this); applyVerificationOptions(ssl_); } if (server_ && parseClientHello_) { SSL_set_msg_callback( ssl_.get(), &AsyncSSLSocket::clientHelloParsingCallback); SSL_set_msg_callback_arg(ssl_.get(), this); } DCHECK(ctx_->sslAcceptRunner()); updateEventRegistration( EventHandler::NONE, EventHandler::READ | EventHandler::WRITE); DelayedDestruction::DestructorGuard dg(this); ctx_->sslAcceptRunner()->run( [this, dg]() { waitingOnAccept_ = true; return SSL_accept(ssl_.get()); }, [this, dg](int ret) { waitingOnAccept_ = false; handleReturnFromSSLAccept(ret); }); } void AsyncSSLSocket::handleReturnFromSSLAccept(int ret) { if (sslState_ != STATE_ACCEPTING) { return; } if (ret <= 0) { VLOG(3) << "SSL_accept returned: " << ret; int sslError; unsigned long errError; int errnoCopy = errno; if (willBlock(ret, &sslError, &errError)) { return; } else { sslState_ = STATE_ERROR; SSLException ex(sslError, errError, ret, errnoCopy); return failHandshake(__func__, ex); } } handshakeComplete_ = true; updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE); // Move into STATE_ESTABLISHED in the normal case that we are in // STATE_ACCEPTING. sslState_ = STATE_ESTABLISHED; VLOG(3) << "AsyncSSLSocket " << this << ": fd " << fd_ << " successfully accepted; state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_; // Remember the EventBase we are attached to, before we start invoking any // callbacks (since the callbacks may call detachEventBase()). EventBase* originalEventBase = eventBase_; // Call the accept callback. invokeHandshakeCB(); // Note that the accept callback may have changed our state. // (set or unset the read callback, called write(), closed the socket, etc.) // The following code needs to handle these situations correctly. // // If the socket has been closed, readCallback_ and writeReqHead_ will // always be nullptr, so that will prevent us from trying to read or write. // // The main thing to check for is if eventBase_ is still originalEventBase. // If not, we have been detached from this event base, so we shouldn't // perform any more operations. if (eventBase_ != originalEventBase) { return; } AsyncSocket::handleInitialReadWrite(); } void AsyncSSLSocket::handleConnect() noexcept { VLOG(3) << "AsyncSSLSocket::handleConnect() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; assert(!server_); if (state_ < StateEnum::ESTABLISHED) { return AsyncSocket::handleConnect(); } assert( (state_ == StateEnum::FAST_OPEN || state_ == StateEnum::ESTABLISHED) && sslState_ == STATE_CONNECTING); assert(ssl_); auto originalState = state_; int ret = SSL_connect(ssl_.get()); if (ret <= 0) { int sslError; unsigned long errError; int errnoCopy = errno; if (willBlock(ret, &sslError, &errError)) { // We fell back to connecting state due to TFO if (state_ == StateEnum::CONNECTING) { DCHECK_EQ(StateEnum::FAST_OPEN, originalState); if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } } return; } else { sslState_ = STATE_ERROR; SSLException ex(sslError, errError, ret, errnoCopy); return failHandshake(__func__, ex); } } handshakeComplete_ = true; updateEventRegistration(0, EventHandler::READ | EventHandler::WRITE); // Move into STATE_ESTABLISHED in the normal case that we are in // STATE_CONNECTING. sslState_ = STATE_ESTABLISHED; VLOG(3) << "AsyncSSLSocket " << this << ": " << "fd " << fd_ << " successfully connected; " << "state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_; // Remember the EventBase we are attached to, before we start invoking any // callbacks (since the callbacks may call detachEventBase()). EventBase* originalEventBase = eventBase_; // Call the handshake callback. invokeHandshakeCB(); // Note that the connect callback may have changed our state. // (set or unset the read callback, called write(), closed the socket, etc.) // The following code needs to handle these situations correctly. // // If the socket has been closed, readCallback_ and writeReqHead_ will // always be nullptr, so that will prevent us from trying to read or write. // // The main thing to check for is if eventBase_ is still originalEventBase. // If not, we have been detached from this event base, so we shouldn't // perform any more operations. if (eventBase_ != originalEventBase) { return; } AsyncSocket::handleInitialReadWrite(); } void AsyncSSLSocket::invokeConnectErr(const AsyncSocketException& ex) { connectionTimeout_.cancelTimeout(); AsyncSocket::invokeConnectErr(ex); if (sslState_ == SSLStateEnum::STATE_CONNECTING) { if (handshakeTimeout_.isScheduled()) { handshakeTimeout_.cancelTimeout(); } // If we fell back to connecting state during TFO and the connection // failed, it would be an SSL failure as well. invokeHandshakeErr(ex); } } void AsyncSSLSocket::invokeConnectSuccess() { connectionTimeout_.cancelTimeout(); if (sslState_ == SSLStateEnum::STATE_CONNECTING) { assert(tfoAttempted_); // If we failed TFO, we'd fall back to trying to connect the socket, // to setup things like timeouts. startSSLConnect(); } // still invoke the base class since it re-sets the connect time. AsyncSocket::invokeConnectSuccess(); } void AsyncSSLSocket::scheduleConnectTimeout() { if (sslState_ == SSLStateEnum::STATE_CONNECTING) { // We fell back from TFO, and need to set the timeouts. // We will not have a connect callback in this case, thus if the timer // expires we would have no-one to notify. // Thus we should reset even the connect timers to point to the handshake // timeouts. assert(connectCallback_ == nullptr); // We use a different connect timeout here than the handshake timeout, so // that we can disambiguate the 2 timers. if (connectTimeout_.count() > 0) { if (!connectionTimeout_.scheduleTimeout(connectTimeout_)) { throw AsyncSocketException( AsyncSocketException::INTERNAL_ERROR, withAddr("failed to schedule AsyncSSLSocket connect timeout")); } } return; } AsyncSocket::scheduleConnectTimeout(); } void AsyncSSLSocket::handleRead() noexcept { VLOG(5) << "AsyncSSLSocket::handleRead() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; if (state_ < StateEnum::ESTABLISHED) { return AsyncSocket::handleRead(); } if (sslState_ == STATE_ACCEPTING) { assert(server_); handleAccept(); return; } else if (sslState_ == STATE_CONNECTING) { assert(!server_); handleConnect(); return; } // Normal read AsyncSocket::handleRead(); } AsyncSocket::ReadResult AsyncSSLSocket::performRead(void** buf, size_t* buflen, size_t* offset) { VLOG(4) << "AsyncSSLSocket::performRead() this=" << this << ", buf=" << *buf << ", buflen=" << *buflen; if (sslState_ == STATE_UNENCRYPTED) { return AsyncSocket::performRead(buf, buflen, offset); } int numToRead = 0; if (*buflen > std::numeric_limits<int>::max()) { numToRead = std::numeric_limits<int>::max(); VLOG(4) << "Clamping SSL_read to " << numToRead; } else { numToRead = int(*buflen); } int bytes = SSL_read(ssl_.get(), *buf, numToRead); if (server_ && renegotiateAttempted_) { LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslstate=" << sslState_ << ", events=" << eventFlags_ << "): client intitiated SSL renegotiation not permitted"; return ReadResult( READ_ERROR, std::make_unique<SSLException>(SSLError::CLIENT_RENEGOTIATION)); } if (bytes <= 0) { int error = SSL_get_error(ssl_.get(), bytes); if (error == SSL_ERROR_WANT_READ) { // The caller will register for read event if not already. if (errno == EWOULDBLOCK || errno == EAGAIN) { return ReadResult(READ_BLOCKING); } else { return ReadResult(READ_ERROR); } } else if (error == SSL_ERROR_WANT_WRITE) { // TODO: Even though we are attempting to read data, SSL_read() may // need to write data if renegotiation is being performed. We currently // don't support this and just fail the read. LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): unsupported SSL renegotiation during read"; return ReadResult( READ_ERROR, std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION)); } else { if (zero_return(error, bytes, errno)) { return ReadResult(bytes); } auto errError = ERR_get_error(); VLOG(6) << "AsyncSSLSocket(fd=" << fd_ << ", " << "state=" << state_ << ", " << "sslState=" << sslState_ << ", " << "events=" << std::hex << eventFlags_ << "): " << "bytes: " << bytes << ", " << "error: " << error << ", " << "errno: " << errno << ", " << "func: " << ERR_func_error_string(errError) << ", " << "reason: " << ERR_reason_error_string(errError); return ReadResult( READ_ERROR, std::make_unique<SSLException>(error, errError, bytes, errno)); } } else { appBytesReceived_ += bytes; return ReadResult(bytes); } } void AsyncSSLSocket::handleWrite() noexcept { VLOG(5) << "AsyncSSLSocket::handleWrite() this=" << this << ", fd=" << fd_ << ", state=" << int(state_) << ", " << "sslState=" << sslState_ << ", events=" << eventFlags_; if (state_ < StateEnum::ESTABLISHED) { return AsyncSocket::handleWrite(); } if (sslState_ == STATE_ACCEPTING) { assert(server_); handleAccept(); return; } if (sslState_ == STATE_CONNECTING) { assert(!server_); handleConnect(); return; } // Normal write AsyncSocket::handleWrite(); } AsyncSocket::WriteResult AsyncSSLSocket::interpretSSLError(int rc, int error) { if (error == SSL_ERROR_WANT_READ) { // Even though we are attempting to write data, SSL_write() may // need to read data if renegotiation is being performed. We currently // don't support this and just fail the write. LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "unsupported SSL renegotiation during write"; return WriteResult( WRITE_ERROR, std::make_unique<SSLException>(SSLError::INVALID_RENEGOTIATION)); } else { auto errError = ERR_get_error(); VLOG(3) << "ERROR: AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "SSL error: " << error << ", errno: " << errno << ", func: " << ERR_func_error_string(errError) << ", reason: " << ERR_reason_error_string(errError); return WriteResult( WRITE_ERROR, std::make_unique<SSLException>(error, errError, rc, errno)); } } AsyncSocket::WriteResult AsyncSSLSocket::performWrite( const iovec* vec, uint32_t count, WriteFlags flags, uint32_t* countWritten, uint32_t* partialWritten) { if (sslState_ == STATE_UNENCRYPTED) { return AsyncSocket::performWrite( vec, count, flags, countWritten, partialWritten); } if (sslState_ != STATE_ESTABLISHED) { LOG(ERROR) << "AsyncSSLSocket(fd=" << fd_ << ", state=" << int(state_) << ", sslState=" << sslState_ << ", events=" << eventFlags_ << "): " << "TODO: AsyncSSLSocket currently does not support calling " << "write() before the handshake has fully completed"; return WriteResult( WRITE_ERROR, std::make_unique<SSLException>(SSLError::EARLY_WRITE)); } // Declare a buffer used to hold small write requests. It could point to a // memory block either on stack or on heap. If it is on heap, we release it // manually when scope exits char* combinedBuf{nullptr}; SCOPE_EXIT { // Note, always keep this check consistent with what we do below if (combinedBuf != nullptr && minWriteSize_ > MAX_STACK_BUF_SIZE) { delete[] combinedBuf; } }; *countWritten = 0; *partialWritten = 0; ssize_t totalWritten = 0; size_t bytesStolenFromNextBuffer = 0; for (uint32_t i = 0; i < count; i++) { const iovec* v = vec + i; size_t offset = bytesStolenFromNextBuffer; bytesStolenFromNextBuffer = 0; size_t len = v->iov_len - offset; const void* buf; if (len == 0) { (*countWritten)++; continue; } buf = ((const char*)v->iov_base) + offset; ssize_t bytes; uint32_t buffersStolen = 0; auto sslWriteBuf = buf; if ((len < minWriteSize_) && ((i + 1) < count)) { // Combine this buffer with part or all of the next buffers in // order to avoid really small-grained calls to SSL_write(). // Each call to SSL_write() produces a separate record in // the egress SSL stream, and we've found that some low-end // mobile clients can't handle receiving an HTTP response // header and the first part of the response body in two // separate SSL records (even if those two records are in // the same TCP packet). if (combinedBuf == nullptr) { if (minWriteSize_ > MAX_STACK_BUF_SIZE) { // Allocate the buffer on heap combinedBuf = new char[minWriteSize_]; } else { // Allocate the buffer on stack combinedBuf = (char*)alloca(minWriteSize_); } } assert(combinedBuf != nullptr); sslWriteBuf = combinedBuf; memcpy(combinedBuf, buf, len); do { // INVARIANT: i + buffersStolen == complete chunks serialized uint32_t nextIndex = i + buffersStolen + 1; bytesStolenFromNextBuffer = std::min(vec[nextIndex].iov_len, minWriteSize_ - len); if (bytesStolenFromNextBuffer > 0) { assert(vec[nextIndex].iov_base != nullptr); ::memcpy( combinedBuf + len, vec[nextIndex].iov_base, bytesStolenFromNextBuffer); } len += bytesStolenFromNextBuffer; if (bytesStolenFromNextBuffer < vec[nextIndex].iov_len) { // couldn't steal the whole buffer break; } else { bytesStolenFromNextBuffer = 0; buffersStolen++; } } while ((i + buffersStolen + 1) < count && (len < minWriteSize_)); } // Advance any empty buffers immediately after. if (bytesStolenFromNextBuffer == 0) { while ((i + buffersStolen + 1) < count && vec[i + buffersStolen + 1].iov_len == 0) { buffersStolen++; } } // cork the current write if the original flags included CORK or if there // are remaining iovec to write corkCurrentWrite_ = isSet(flags, WriteFlags::CORK) || (i + buffersStolen + 1 < count); // track the EoR if: // (1) there are write flags that require EoR tracking (EOR / TIMESTAMP_TX) // (2) if the buffer includes the EOR byte appEorByteWriteFlags_ = flags & kEorRelevantWriteFlags; bool trackEor = appEorByteWriteFlags_ != folly::WriteFlags::NONE && (i + buffersStolen + 1 == count); bytes = eorAwareSSLWrite(ssl_, sslWriteBuf, int(len), trackEor); if (bytes <= 0) { int error = SSL_get_error(ssl_.get(), int(bytes)); if (error == SSL_ERROR_WANT_WRITE) { // The caller will register for write event if not already. *partialWritten = uint32_t(offset); return WriteResult(totalWritten); } return interpretSSLError(int(bytes), error); } totalWritten += bytes; if (bytes == (ssize_t)len) { // The full iovec is written. (*countWritten) += 1 + buffersStolen; i += buffersStolen; // continue } else { bytes += offset; // adjust bytes to account for all of v while (bytes >= (ssize_t)v->iov_len) { // We combined this buf with part or all of the next one, and // we managed to write all of this buf but not all of the bytes // from the next one that we'd hoped to write. bytes -= v->iov_len; (*countWritten)++; v = &(vec[++i]); } *partialWritten = uint32_t(bytes); return WriteResult(totalWritten); } } return WriteResult(totalWritten); } int AsyncSSLSocket::eorAwareSSLWrite( const ssl::SSLUniquePtr& ssl, const void* buf, int n, bool eor) { if (eor && isEorTrackingEnabled()) { if (appEorByteNo_) { // cannot track for more than one app byte EOR CHECK(appEorByteNo_ == appBytesWritten_ + n); } else { appEorByteNo_ = appBytesWritten_ + n; } // 1. It is fine to keep updating minEorRawByteNo_. // 2. It is _min_ in the sense that SSL record will add some overhead. minEorRawByteNo_ = getRawBytesWritten() + n; } n = sslWriteImpl(ssl.get(), buf, n); if (n > 0) { appBytesWritten_ += n; if (appEorByteNo_) { if (getRawBytesWritten() >= minEorRawByteNo_) { minEorRawByteNo_ = 0; } if (appBytesWritten_ == appEorByteNo_) { appEorByteNo_ = 0; appEorByteWriteFlags_ = {}; } else { CHECK(appBytesWritten_ < appEorByteNo_); } } } return n; } void AsyncSSLSocket::sslInfoCallback(const SSL* ssl, int where, int ret) { AsyncSSLSocket* sslSocket = AsyncSSLSocket::getFromSSL(ssl); if (sslSocket->handshakeComplete_ && (where & SSL_CB_HANDSHAKE_START)) { sslSocket->renegotiateAttempted_ = true; } if (sslSocket->handshakeComplete_ && (where & SSL_CB_WRITE_ALERT)) { const char* desc = SSL_alert_desc_string(ret); if (desc && strcmp(desc, "NR") == 0) { sslSocket->renegotiateAttempted_ = true; } } if (where & SSL_CB_READ_ALERT) { const char* type = SSL_alert_type_string(ret); if (type) { const char* desc = SSL_alert_desc_string(ret); sslSocket->alertsReceived_.emplace_back( *type, StringPiece(desc, std::strlen(desc))); } } } int AsyncSSLSocket::bioWrite(BIO* b, const char* in, int inl) { struct msghdr msg; struct iovec iov; AsyncSSLSocket* tsslSock; iov.iov_base = const_cast<char*>(in); iov.iov_len = size_t(inl); memset(&msg, 0, sizeof(msg)); msg.msg_iov = &iov; msg.msg_iovlen = 1; auto appData = OpenSSLUtils::getBioAppData(b); CHECK(appData); tsslSock = reinterpret_cast<AsyncSSLSocket*>(appData); CHECK(tsslSock); WriteFlags flags = WriteFlags::NONE; if (tsslSock->isEorTrackingEnabled() && tsslSock->minEorRawByteNo_ && tsslSock->minEorRawByteNo_ <= BIO_number_written(b) + inl) { flags |= tsslSock->appEorByteWriteFlags_; } if (tsslSock->corkCurrentWrite_) { flags |= WriteFlags::CORK; } int msg_flags = tsslSock->getSendMsgParamsCB()->getFlags( flags, false /*zeroCopyEnabled*/); msg.msg_controllen = tsslSock->getSendMsgParamsCB()->getAncillaryDataSize(flags); CHECK_GE( AsyncSocket::SendMsgParamsCallback::maxAncillaryDataSize, msg.msg_controllen); if (msg.msg_controllen != 0) { msg.msg_control = reinterpret_cast<char*>(alloca(msg.msg_controllen)); tsslSock->getSendMsgParamsCB()->getAncillaryData(flags, msg.msg_control); } auto result = tsslSock->sendSocketMessage(OpenSSLUtils::getBioFd(b), &msg, msg_flags); BIO_clear_retry_flags(b); if (!result.exception && result.writeReturn <= 0) { if (OpenSSLUtils::getBioShouldRetryWrite(int(result.writeReturn))) { BIO_set_retry_write(b); } } return int(result.writeReturn); } int AsyncSSLSocket::bioRead(BIO* b, char* out, int outl) { if (!out) { return 0; } BIO_clear_retry_flags(b); auto appData = OpenSSLUtils::getBioAppData(b); CHECK(appData); auto sslSock = reinterpret_cast<AsyncSSLSocket*>(appData); if (sslSock->preReceivedData_ && !sslSock->preReceivedData_->empty()) { VLOG(5) << "AsyncSSLSocket::bioRead() this=" << sslSock << ", reading pre-received data"; Cursor cursor(sslSock->preReceivedData_.get()); auto len = cursor.pullAtMost(out, outl); IOBufQueue queue; queue.append(std::move(sslSock->preReceivedData_)); queue.trimStart(len); sslSock->preReceivedData_ = queue.move(); return static_cast<int>(len); } else { auto result = int(netops::recv(OpenSSLUtils::getBioFd(b), out, outl, 0)); if (result <= 0 && OpenSSLUtils::getBioShouldRetryWrite(result)) { BIO_set_retry_read(b); } return result; } } int AsyncSSLSocket::sslVerifyCallback( int preverifyOk, X509_STORE_CTX* x509Ctx) { SSL* ssl = (SSL*)X509_STORE_CTX_get_ex_data( x509Ctx, SSL_get_ex_data_X509_STORE_CTX_idx()); AsyncSSLSocket* self = AsyncSSLSocket::getFromSSL(ssl); VLOG(3) << "AsyncSSLSocket::sslVerifyCallback() this=" << self << ", " << "fd=" << self->fd_ << ", preverifyOk=" << preverifyOk; return (self->handshakeCallback_) ? self->handshakeCallback_->handshakeVer(self, preverifyOk, x509Ctx) : preverifyOk; } void AsyncSSLSocket::enableClientHelloParsing() { parseClientHello_ = true; clientHelloInfo_ = std::make_unique<ssl::ClientHelloInfo>(); } void AsyncSSLSocket::resetClientHelloParsing(SSL* ssl) { SSL_set_msg_callback(ssl, nullptr); SSL_set_msg_callback_arg(ssl, nullptr); clientHelloInfo_->clientHelloBuf_.clear(); } void AsyncSSLSocket::clientHelloParsingCallback( int written, int /* version */, int contentType, const void* buf, size_t len, SSL* ssl, void* arg) { AsyncSSLSocket* sock = static_cast<AsyncSSLSocket*>(arg); if (written != 0) { sock->resetClientHelloParsing(ssl); return; } if (contentType != SSL3_RT_HANDSHAKE) { return; } if (len == 0) { return; } auto& clientHelloBuf = sock->clientHelloInfo_->clientHelloBuf_; clientHelloBuf.append(IOBuf::wrapBuffer(buf, len)); try { Cursor cursor(clientHelloBuf.front()); if (cursor.read<uint8_t>() != SSL3_MT_CLIENT_HELLO) { sock->resetClientHelloParsing(ssl); return; } if (cursor.totalLength() < 3) { clientHelloBuf.trimEnd(len); clientHelloBuf.append(IOBuf::copyBuffer(buf, len)); return; } uint32_t messageLength = cursor.read<uint8_t>(); messageLength <<= 8; messageLength |= cursor.read<uint8_t>(); messageLength <<= 8; messageLength |= cursor.read<uint8_t>(); if (cursor.totalLength() < messageLength) { clientHelloBuf.trimEnd(len); clientHelloBuf.append(IOBuf::copyBuffer(buf, len)); return; } sock->clientHelloInfo_->clientHelloMajorVersion_ = cursor.read<uint8_t>(); sock->clientHelloInfo_->clientHelloMinorVersion_ = cursor.read<uint8_t>(); cursor.skip(4); // gmt_unix_time cursor.skip(28); // random_bytes cursor.skip(cursor.read<uint8_t>()); // session_id uint16_t cipherSuitesLength = cursor.readBE<uint16_t>(); for (int i = 0; i < cipherSuitesLength; i += 2) { sock->clientHelloInfo_->clientHelloCipherSuites_.push_back( cursor.readBE<uint16_t>()); } uint8_t compressionMethodsLength = cursor.read<uint8_t>(); for (int i = 0; i < compressionMethodsLength; ++i) { sock->clientHelloInfo_->clientHelloCompressionMethods_.push_back( cursor.readBE<uint8_t>()); } if (cursor.totalLength() > 0) { uint16_t extensionsLength = cursor.readBE<uint16_t>(); while (extensionsLength) { ssl::TLSExtension extensionType = static_cast<ssl::TLSExtension>(cursor.readBE<uint16_t>()); sock->clientHelloInfo_->clientHelloExtensions_.push_back(extensionType); extensionsLength -= 2; uint16_t extensionDataLength = cursor.readBE<uint16_t>(); extensionsLength -= 2; extensionsLength -= extensionDataLength; if (extensionType == ssl::TLSExtension::SIGNATURE_ALGORITHMS) { cursor.skip(2); extensionDataLength -= 2; while (extensionDataLength) { ssl::HashAlgorithm hashAlg = static_cast<ssl::HashAlgorithm>(cursor.readBE<uint8_t>()); ssl::SignatureAlgorithm sigAlg = static_cast<ssl::SignatureAlgorithm>(cursor.readBE<uint8_t>()); extensionDataLength -= 2; sock->clientHelloInfo_->clientHelloSigAlgs_.emplace_back( hashAlg, sigAlg); } } else if (extensionType == ssl::TLSExtension::SUPPORTED_VERSIONS) { cursor.skip(1); extensionDataLength -= 1; while (extensionDataLength) { sock->clientHelloInfo_->clientHelloSupportedVersions_.push_back( cursor.readBE<uint16_t>()); extensionDataLength -= 2; } } else if (extensionType == ssl::TLSExtension::SERVER_NAME) { cursor.skip(2); extensionDataLength -= 2; while (extensionDataLength) { static_assert( std::is_same< typename std::underlying_type<ssl::NameType>::type, uint8_t>::value, "unexpected underlying type"); ssl::NameType typ = static_cast<ssl::NameType>(cursor.readBE<uint8_t>()); uint16_t nameLength = cursor.readBE<uint16_t>(); if (typ == NameType::HOST_NAME && sock->clientHelloInfo_->clientHelloSNIHostname_.empty() && cursor.canAdvance(nameLength)) { sock->clientHelloInfo_->clientHelloSNIHostname_ = cursor.readFixedString(nameLength); } else { // Must attempt to skip |nameLength| in order to keep cursor // in sync. If the remaining buffer length is smaller than // nameLength, this will throw. cursor.skip(nameLength); } extensionDataLength -= sizeof(typ) + sizeof(nameLength) + nameLength; } } else { cursor.skip(extensionDataLength); } } } } catch (std::out_of_range&) { // we'll use what we found and cleanup below. VLOG(4) << "AsyncSSLSocket::clientHelloParsingCallback(): " << "buffer finished unexpectedly." << " AsyncSSLSocket socket=" << sock; } sock->resetClientHelloParsing(ssl); } void AsyncSSLSocket::getSSLClientCiphers( std::string& clientCiphers, bool convertToString) const { std::string ciphers; if (parseClientHello_ == false || clientHelloInfo_->clientHelloCipherSuites_.empty()) { clientCiphers = ""; return; } bool first = true; for (auto originalCipherCode : clientHelloInfo_->clientHelloCipherSuites_) { if (first) { first = false; } else { ciphers += ":"; } bool nameFound = convertToString; if (convertToString) { const auto& name = OpenSSLUtils::getCipherName(originalCipherCode); if (name.empty()) { nameFound = false; } else { ciphers += name; } } if (!nameFound) { folly::hexlify( std::array<uint8_t, 2>{ {static_cast<uint8_t>((originalCipherCode >> 8) & 0xffL), static_cast<uint8_t>(originalCipherCode & 0x00ffL)}}, ciphers, /* append to ciphers = */ true); } } clientCiphers = std::move(ciphers); } std::string AsyncSSLSocket::getSSLClientComprMethods() const { if (!parseClientHello_) { return ""; } return folly::join(":", clientHelloInfo_->clientHelloCompressionMethods_); } std::string AsyncSSLSocket::getSSLClientExts() const { if (!parseClientHello_) { return ""; } return folly::join(":", clientHelloInfo_->clientHelloExtensions_); } std::string AsyncSSLSocket::getSSLClientSigAlgs() const { if (!parseClientHello_) { return ""; } std::string sigAlgs; sigAlgs.reserve(clientHelloInfo_->clientHelloSigAlgs_.size() * 4); for (size_t i = 0; i < clientHelloInfo_->clientHelloSigAlgs_.size(); i++) { if (i) { sigAlgs.push_back(':'); } sigAlgs.append( folly::to<std::string>(clientHelloInfo_->clientHelloSigAlgs_[i].first)); sigAlgs.push_back(','); sigAlgs.append(folly::to<std::string>( clientHelloInfo_->clientHelloSigAlgs_[i].second)); } return sigAlgs; } std::string AsyncSSLSocket::getSSLClientSupportedVersions() const { if (!parseClientHello_) { return ""; } return folly::join(":", clientHelloInfo_->clientHelloSupportedVersions_); } std::string AsyncSSLSocket::getSSLAlertsReceived() const { std::string ret; for (const auto& alert : alertsReceived_) { if (!ret.empty()) { ret.append(","); } ret.append(folly::to<std::string>(alert.first, ": ", alert.second)); } return ret; } void AsyncSSLSocket::setSSLCertVerificationAlert(std::string alert) { sslVerificationAlert_ = std::move(alert); } std::string AsyncSSLSocket::getSSLCertVerificationAlert() const { return sslVerificationAlert_; } void AsyncSSLSocket::getSSLSharedCiphers(std::string& sharedCiphers) const { char ciphersBuffer[1024]; ciphersBuffer[0] = '\0'; SSL_get_shared_ciphers(ssl_.get(), ciphersBuffer, sizeof(ciphersBuffer) - 1); sharedCiphers = ciphersBuffer; } void AsyncSSLSocket::getSSLServerCiphers(std::string& serverCiphers) const { serverCiphers = SSL_get_cipher_list(ssl_.get(), 0); int i = 1; const char* cipher; while ((cipher = SSL_get_cipher_list(ssl_.get(), i)) != nullptr) { serverCiphers.append(":"); serverCiphers.append(cipher); i++; } } } // namespace folly
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_849_0
crossvul-cpp_data_good_2946_1
/* Copyright 2008-2017 LibRaw LLC (info@libraw.org) LibRaw is free software; you can redistribute it and/or modify it under the terms of the one of two licenses as you choose: 1. GNU LESSER GENERAL PUBLIC LICENSE version 2.1 (See file LICENSE.LGPL provided in LibRaw distribution archive for details). 2. COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 (See file LICENSE.CDDL provided in LibRaw distribution archive for details). This file is generated from Dave Coffin's dcraw.c dcraw.c -- Dave Coffin's raw photo decoder Copyright 1997-2010 by Dave Coffin, dcoffin a cybercom o net Look into dcraw homepage (probably http://cybercom.net/~dcoffin/dcraw/) for more information */ #include <math.h> #define CLASS LibRaw:: #include "libraw/libraw_types.h" #define LIBRAW_LIBRARY_BUILD #define LIBRAW_IO_REDEFINED #include "libraw/libraw.h" #include "internal/defines.h" #include "internal/var_defines.h" int CLASS fcol(int row, int col) { static const char filter[16][16] = { {2, 1, 1, 3, 2, 3, 2, 0, 3, 2, 3, 0, 1, 2, 1, 0}, {0, 3, 0, 2, 0, 1, 3, 1, 0, 1, 1, 2, 0, 3, 3, 2}, {2, 3, 3, 2, 3, 1, 1, 3, 3, 1, 2, 1, 2, 0, 0, 3}, {0, 1, 0, 1, 0, 2, 0, 2, 2, 0, 3, 0, 1, 3, 2, 1}, {3, 1, 1, 2, 0, 1, 0, 2, 1, 3, 1, 3, 0, 1, 3, 0}, {2, 0, 0, 3, 3, 2, 3, 1, 2, 0, 2, 0, 3, 2, 2, 1}, {2, 3, 3, 1, 2, 1, 2, 1, 2, 1, 1, 2, 3, 0, 0, 1}, {1, 0, 0, 2, 3, 0, 0, 3, 0, 3, 0, 3, 2, 1, 2, 3}, {2, 3, 3, 1, 1, 2, 1, 0, 3, 2, 3, 0, 2, 3, 1, 3}, {1, 0, 2, 0, 3, 0, 3, 2, 0, 1, 1, 2, 0, 1, 0, 2}, {0, 1, 1, 3, 3, 2, 2, 1, 1, 3, 3, 0, 2, 1, 3, 2}, {2, 3, 2, 0, 0, 1, 3, 0, 2, 0, 1, 2, 3, 0, 1, 0}, {1, 3, 1, 2, 3, 2, 3, 2, 0, 2, 0, 1, 1, 0, 3, 0}, {0, 2, 0, 3, 1, 0, 0, 1, 1, 3, 3, 2, 3, 2, 2, 1}, {2, 1, 3, 2, 3, 1, 2, 1, 0, 3, 0, 2, 0, 2, 0, 2}, {0, 3, 1, 0, 0, 2, 0, 3, 2, 1, 3, 1, 1, 3, 1, 3}}; if (filters == 1) return filter[(row + top_margin) & 15][(col + left_margin) & 15]; if (filters == 9) return xtrans[(row + 6) % 6][(col + 6) % 6]; return FC(row, col); } #if !defined(__FreeBSD__) static size_t local_strnlen(const char *s, size_t n) { const char *p = (const char *)memchr(s, 0, n); return (p ? p - s : n); } /* add OS X version check here ?? */ #define strnlen(a, b) local_strnlen(a, b) #endif #ifdef LIBRAW_LIBRARY_BUILD static int Fuji_wb_list1[] = {LIBRAW_WBI_FineWeather, LIBRAW_WBI_Shade, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_L, LIBRAW_WBI_FL_W, LIBRAW_WBI_Tungsten}; static int nFuji_wb_list1 = sizeof(Fuji_wb_list1) / sizeof(int); static int FujiCCT_K[31] = {2500, 2550, 2650, 2700, 2800, 2850, 2950, 3000, 3100, 3200, 3300, 3400, 3600, 3700, 3800, 4000, 4200, 4300, 4500, 4800, 5000, 5300, 5600, 5900, 6300, 6700, 7100, 7700, 8300, 9100, 10000}; static int Fuji_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Custom, 6, LIBRAW_WBI_FineWeather, 1, LIBRAW_WBI_Shade, 8, LIBRAW_WBI_FL_D, 10, LIBRAW_WBI_FL_L, 11, LIBRAW_WBI_FL_W, 12, LIBRAW_WBI_Tungsten, 2, LIBRAW_WBI_Underwater, 35, LIBRAW_WBI_Ill_A, 82, LIBRAW_WBI_D65, 83}; static int nFuji_wb_list2 = sizeof(Fuji_wb_list2) / sizeof(int); static int Oly_wb_list1[] = {LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_FineWeather, LIBRAW_WBI_Tungsten, LIBRAW_WBI_Sunset, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_FL_WW}; static int Oly_wb_list2[] = {LIBRAW_WBI_Auto, 0, LIBRAW_WBI_Tungsten, 3000, 0x100, 3300, 0x100, 3600, 0x100, 3900, LIBRAW_WBI_FL_W, 4000, 0x100, 4300, LIBRAW_WBI_FL_D, 4500, 0x100, 4800, LIBRAW_WBI_FineWeather, 5300, LIBRAW_WBI_Cloudy, 6000, LIBRAW_WBI_FL_N, 6600, LIBRAW_WBI_Shade, 7500, LIBRAW_WBI_Custom1, 0, LIBRAW_WBI_Custom2, 0, LIBRAW_WBI_Custom3, 0, LIBRAW_WBI_Custom4, 0}; static int Pentax_wb_list1[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash}; static int Pentax_wb_list2[] = {LIBRAW_WBI_Daylight, LIBRAW_WBI_Shade, LIBRAW_WBI_Cloudy, LIBRAW_WBI_Tungsten, LIBRAW_WBI_FL_D, LIBRAW_WBI_FL_N, LIBRAW_WBI_FL_W, LIBRAW_WBI_Flash, LIBRAW_WBI_FL_L}; static int nPentax_wb_list2 = sizeof(Pentax_wb_list2) / sizeof(int); static int stread(char *buf, size_t len, LibRaw_abstract_datastream *fp) { int r = fp->read(buf, len, 1); buf[len - 1] = 0; return r; } #define stmread(buf, maxlen, fp) stread(buf, MIN(maxlen, sizeof(buf)), fp) #endif #if !defined(__GLIBC__) && !defined(__FreeBSD__) char *my_memmem(char *haystack, size_t haystacklen, char *needle, size_t needlelen) { char *c; for (c = haystack; c <= haystack + haystacklen - needlelen; c++) if (!memcmp(c, needle, needlelen)) return c; return 0; } #define memmem my_memmem char *my_strcasestr(char *haystack, const char *needle) { char *c; for (c = haystack; *c; c++) if (!strncasecmp(c, needle, strlen(needle))) return c; return 0; } #define strcasestr my_strcasestr #endif #define strbuflen(buf) strnlen(buf, sizeof(buf) - 1) ushort CLASS sget2(uchar *s) { if (order == 0x4949) /* "II" means little-endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian */ return s[0] << 8 | s[1]; } // DNG was written by: #define nonDNG 0 #define CameraDNG 1 #define AdobeDNG 2 #ifdef LIBRAW_LIBRARY_BUILD static int getwords(char *line, char *words[], int maxwords, int maxlen) { line[maxlen - 1] = 0; char *p = line; int nwords = 0; while (1) { while (isspace(*p)) p++; if (*p == '\0') return nwords; words[nwords++] = p; while (!isspace(*p) && *p != '\0') p++; if (*p == '\0') return nwords; *p++ = '\0'; if (nwords >= maxwords) return nwords; } } static ushort saneSonyCameraInfo(uchar a, uchar b, uchar c, uchar d, uchar e, uchar f) { if ((a >> 4) > 9) return 0; else if ((a & 0x0f) > 9) return 0; else if ((b >> 4) > 9) return 0; else if ((b & 0x0f) > 9) return 0; else if ((c >> 4) > 9) return 0; else if ((c & 0x0f) > 9) return 0; else if ((d >> 4) > 9) return 0; else if ((d & 0x0f) > 9) return 0; else if ((e >> 4) > 9) return 0; else if ((e & 0x0f) > 9) return 0; else if ((f >> 4) > 9) return 0; else if ((f & 0x0f) > 9) return 0; return 1; } static ushort bcd2dec(uchar data) { if ((data >> 4) > 9) return 0; else if ((data & 0x0f) > 9) return 0; else return (data >> 4) * 10 + (data & 0x0f); } static uchar SonySubstitution[257] = "\x00\x01\x32\xb1\x0a\x0e\x87\x28\x02\xcc\xca\xad\x1b\xdc\x08\xed\x64\x86\xf0\x4f\x8c\x6c\xb8\xcb\x69\xc4\x2c\x03" "\x97\xb6\x93\x7c\x14\xf3\xe2\x3e\x30\x8e\xd7\x60\x1c\xa1\xab\x37\xec\x75\xbe\x23\x15\x6a\x59\x3f\xd0\xb9\x96\xb5" "\x50\x27\x88\xe3\x81\x94\xe0\xc0\x04\x5c\xc6\xe8\x5f\x4b\x70\x38\x9f\x82\x80\x51\x2b\xc5\x45\x49\x9b\x21\x52\x53" "\x54\x85\x0b\x5d\x61\xda\x7b\x55\x26\x24\x07\x6e\x36\x5b\x47\xb7\xd9\x4a\xa2\xdf\xbf\x12\x25\xbc\x1e\x7f\x56\xea" "\x10\xe6\xcf\x67\x4d\x3c\x91\x83\xe1\x31\xb3\x6f\xf4\x05\x8a\x46\xc8\x18\x76\x68\xbd\xac\x92\x2a\x13\xe9\x0f\xa3" "\x7a\xdb\x3d\xd4\xe7\x3a\x1a\x57\xaf\x20\x42\xb2\x9e\xc3\x8b\xf2\xd5\xd3\xa4\x7e\x1f\x98\x9c\xee\x74\xa5\xa6\xa7" "\xd8\x5e\xb0\xb4\x34\xce\xa8\x79\x77\x5a\xc1\x89\xae\x9a\x11\x33\x9d\xf5\x39\x19\x65\x78\x16\x71\xd2\xa9\x44\x63" "\x40\x29\xba\xa0\x8f\xe4\xd6\x3b\x84\x0d\xc2\x4e\x58\xdd\x99\x22\x6b\xc9\xbb\x17\x06\xe5\x7d\x66\x43\x62\xf6\xcd" "\x35\x90\x2e\x41\x8d\x6d\xaa\x09\x73\x95\x0c\xf1\x1d\xde\x4c\x2f\x2d\xf7\xd1\x72\xeb\xef\x48\xc7\xf8\xf9\xfa\xfb" "\xfc\xfd\xfe\xff"; ushort CLASS sget2Rev(uchar *s) // specific to some Canon Makernotes fields, where they have endian in reverse { if (order == 0x4d4d) /* "II" means little-endian, and we reverse to "MM" - big endian */ return s[0] | s[1] << 8; else /* "MM" means big-endian... */ return s[0] << 8 | s[1]; } #endif ushort CLASS get2() { uchar str[2] = {0xff, 0xff}; fread(str, 1, 2, ifp); return sget2(str); } unsigned CLASS sget4(uchar *s) { if (order == 0x4949) return s[0] | s[1] << 8 | s[2] << 16 | s[3] << 24; else return s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]; } #define sget4(s) sget4((uchar *)s) unsigned CLASS get4() { uchar str[4] = {0xff, 0xff, 0xff, 0xff}; fread(str, 1, 4, ifp); return sget4(str); } unsigned CLASS getint(int type) { return type == 3 ? get2() : get4(); } float CLASS int_to_float(int i) { union { int i; float f; } u; u.i = i; return u.f; } double CLASS getreal(int type) { union { char c[8]; double d; } u, v; int i, rev; switch (type) { case 3: return (unsigned short)get2(); case 4: return (unsigned int)get4(); case 5: u.d = (unsigned int)get4(); v.d = (unsigned int)get4(); return u.d / (v.d ? v.d : 1); case 8: return (signed short)get2(); case 9: return (signed int)get4(); case 10: u.d = (signed int)get4(); v.d = (signed int)get4(); return u.d / (v.d ? v.d : 1); case 11: return int_to_float(get4()); case 12: rev = 7 * ((order == 0x4949) == (ntohs(0x1234) == 0x1234)); for (i = 0; i < 8; i++) u.c[i ^ rev] = fgetc(ifp); return u.d; default: return fgetc(ifp); } } void CLASS read_shorts(ushort *pixel, int count) { if (fread(pixel, 2, count, ifp) < count) derror(); if ((order == 0x4949) == (ntohs(0x1234) == 0x1234)) swab((char *)pixel, (char *)pixel, count * 2); } void CLASS cubic_spline(const int *x_, const int *y_, const int len) { float **A, *b, *c, *d, *x, *y; int i, j; A = (float **)calloc(((2 * len + 4) * sizeof **A + sizeof *A), 2 * len); if (!A) return; A[0] = (float *)(A + 2 * len); for (i = 1; i < 2 * len; i++) A[i] = A[0] + 2 * len * i; y = len + (x = i + (d = i + (c = i + (b = A[0] + i * i)))); for (i = 0; i < len; i++) { x[i] = x_[i] / 65535.0; y[i] = y_[i] / 65535.0; } for (i = len - 1; i > 0; i--) { b[i] = (y[i] - y[i - 1]) / (x[i] - x[i - 1]); d[i - 1] = x[i] - x[i - 1]; } for (i = 1; i < len - 1; i++) { A[i][i] = 2 * (d[i - 1] + d[i]); if (i > 1) { A[i][i - 1] = d[i - 1]; A[i - 1][i] = d[i - 1]; } A[i][len - 1] = 6 * (b[i + 1] - b[i]); } for (i = 1; i < len - 2; i++) { float v = A[i + 1][i] / A[i][i]; for (j = 1; j <= len - 1; j++) A[i + 1][j] -= v * A[i][j]; } for (i = len - 2; i > 0; i--) { float acc = 0; for (j = i; j <= len - 2; j++) acc += A[i][j] * c[j]; c[i] = (A[i][len - 1] - acc) / A[i][i]; } for (i = 0; i < 0x10000; i++) { float x_out = (float)(i / 65535.0); float y_out = 0; for (j = 0; j < len - 1; j++) { if (x[j] <= x_out && x_out <= x[j + 1]) { float v = x_out - x[j]; y_out = y[j] + ((y[j + 1] - y[j]) / d[j] - (2 * d[j] * c[j] + c[j + 1] * d[j]) / 6) * v + (c[j] * 0.5) * v * v + ((c[j + 1] - c[j]) / (6 * d[j])) * v * v * v; } } curve[i] = y_out < 0.0 ? 0 : (y_out >= 1.0 ? 65535 : (ushort)(y_out * 65535.0 + 0.5)); } free(A); } void CLASS canon_600_fixed_wb(int temp) { static const short mul[4][5] = { {667, 358, 397, 565, 452}, {731, 390, 367, 499, 517}, {1119, 396, 348, 448, 537}, {1399, 485, 431, 508, 688}}; int lo, hi, i; float frac = 0; for (lo = 4; --lo;) if (*mul[lo] <= temp) break; for (hi = 0; hi < 3; hi++) if (*mul[hi] >= temp) break; if (lo != hi) frac = (float)(temp - *mul[lo]) / (*mul[hi] - *mul[lo]); for (i = 1; i < 5; i++) pre_mul[i - 1] = 1 / (frac * mul[hi][i] + (1 - frac) * mul[lo][i]); } /* Return values: 0 = white 1 = near white 2 = not white */ int CLASS canon_600_color(int ratio[2], int mar) { int clipped = 0, target, miss; if (flash_used) { if (ratio[1] < -104) { ratio[1] = -104; clipped = 1; } if (ratio[1] > 12) { ratio[1] = 12; clipped = 1; } } else { if (ratio[1] < -264 || ratio[1] > 461) return 2; if (ratio[1] < -50) { ratio[1] = -50; clipped = 1; } if (ratio[1] > 307) { ratio[1] = 307; clipped = 1; } } target = flash_used || ratio[1] < 197 ? -38 - (398 * ratio[1] >> 10) : -123 + (48 * ratio[1] >> 10); if (target - mar <= ratio[0] && target + 20 >= ratio[0] && !clipped) return 0; miss = target - ratio[0]; if (abs(miss) >= mar * 4) return 2; if (miss < -20) miss = -20; if (miss > mar) miss = mar; ratio[0] = target - miss; return 1; } void CLASS canon_600_auto_wb() { int mar, row, col, i, j, st, count[] = {0, 0}; int test[8], total[2][8], ratio[2][2], stat[2]; memset(&total, 0, sizeof total); i = canon_ev + 0.5; if (i < 10) mar = 150; else if (i > 12) mar = 20; else mar = 280 - 20 * i; if (flash_used) mar = 80; for (row = 14; row < height - 14; row += 4) for (col = 10; col < width; col += 2) { for (i = 0; i < 8; i++) test[(i & 4) + FC(row + (i >> 1), col + (i & 1))] = BAYER(row + (i >> 1), col + (i & 1)); for (i = 0; i < 8; i++) if (test[i] < 150 || test[i] > 1500) goto next; for (i = 0; i < 4; i++) if (abs(test[i] - test[i + 4]) > 50) goto next; for (i = 0; i < 2; i++) { for (j = 0; j < 4; j += 2) ratio[i][j >> 1] = ((test[i * 4 + j + 1] - test[i * 4 + j]) << 10) / test[i * 4 + j]; stat[i] = canon_600_color(ratio[i], mar); } if ((st = stat[0] | stat[1]) > 1) goto next; for (i = 0; i < 2; i++) if (stat[i]) for (j = 0; j < 2; j++) test[i * 4 + j * 2 + 1] = test[i * 4 + j * 2] * (0x400 + ratio[i][j]) >> 10; for (i = 0; i < 8; i++) total[st][i] += test[i]; count[st]++; next:; } if (count[0] | count[1]) { st = count[0] * 200 < count[1]; for (i = 0; i < 4; i++) pre_mul[i] = 1.0 / (total[st][i] + total[st][i + 4]); } } void CLASS canon_600_coeff() { static const short table[6][12] = {{-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-1203, 1715, -1136, 1648, 1388, -876, 267, 245, -1641, 2153, 3921, -3409}, {-615, 1127, -1563, 2075, 1437, -925, 509, 3, -756, 1268, 2519, -2007}, {-190, 702, -1886, 2398, 2153, -1641, 763, -251, -452, 964, 3040, -2528}, {-190, 702, -1878, 2390, 1861, -1349, 905, -393, -432, 944, 2617, -2105}, {-807, 1319, -1785, 2297, 1388, -876, 769, -257, -230, 742, 2067, -1555}}; int t = 0, i, c; float mc, yc; mc = pre_mul[1] / pre_mul[2]; yc = pre_mul[3] / pre_mul[2]; if (mc > 1 && mc <= 1.28 && yc < 0.8789) t = 1; if (mc > 1.28 && mc <= 2) { if (yc < 0.8789) t = 3; else if (yc <= 2) t = 4; } if (flash_used) t = 5; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[t][i * 4 + c] / 1024.0; } void CLASS canon_600_load_raw() { uchar data[1120], *dp; ushort *pix; int irow, row; for (irow = row = 0; irow < height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data, 1, 1120, ifp) < 1120) derror(); pix = raw_image + row * raw_width; for (dp = data; dp < data + 1120; dp += 10, pix += 8) { pix[0] = (dp[0] << 2) + (dp[1] >> 6); pix[1] = (dp[2] << 2) + (dp[1] >> 4 & 3); pix[2] = (dp[3] << 2) + (dp[1] >> 2 & 3); pix[3] = (dp[4] << 2) + (dp[1] & 3); pix[4] = (dp[5] << 2) + (dp[9] & 3); pix[5] = (dp[6] << 2) + (dp[9] >> 2 & 3); pix[6] = (dp[7] << 2) + (dp[9] >> 4 & 3); pix[7] = (dp[8] << 2) + (dp[9] >> 6); } if ((row += 2) > height) row = 1; } } void CLASS canon_600_correct() { int row, col, val; static const short mul[4][2] = {{1141, 1145}, {1128, 1109}, {1178, 1149}, {1128, 1109}}; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) { if ((val = BAYER(row, col) - black) < 0) val = 0; val = val * mul[row & 3][col & 1] >> 9; BAYER(row, col) = val; } } canon_600_fixed_wb(1311); canon_600_auto_wb(); canon_600_coeff(); maximum = (0x3ff - black) * 1109 >> 9; black = 0; } int CLASS canon_s2is() { unsigned row; for (row = 0; row < 100; row++) { fseek(ifp, row * 3340 + 3284, SEEK_SET); if (getc(ifp) > 15) return 1; } return 0; } unsigned CLASS getbithuff(int nbits, ushort *huff) { #ifdef LIBRAW_NOTHREADS static unsigned bitbuf = 0; static int vbits = 0, reset = 0; #else #define bitbuf tls->getbits.bitbuf #define vbits tls->getbits.vbits #define reset tls->getbits.reset #endif unsigned c; if (nbits > 25) return 0; if (nbits < 0) return bitbuf = vbits = reset = 0; if (nbits == 0 || vbits < 0) return 0; while (!reset && vbits < nbits && (c = fgetc(ifp)) != EOF && !(reset = zero_after_ff && c == 0xff && fgetc(ifp))) { bitbuf = (bitbuf << 8) + (uchar)c; vbits += 8; } c = bitbuf << (32 - vbits) >> (32 - nbits); if (huff) { vbits -= huff[c] >> 8; c = (uchar)huff[c]; } else vbits -= nbits; if (vbits < 0) derror(); return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #undef reset #endif } #define getbits(n) getbithuff(n, 0) #define gethuff(h) getbithuff(*h, h + 1) /* Construct a decode tree according the specification in *source. The first 16 bytes specify how many codes should be 1-bit, 2-bit 3-bit, etc. Bytes after that are the leaf values. For example, if the source is { 0,1,4,2,3,1,2,0,0,0,0,0,0,0,0,0, 0x04,0x03,0x05,0x06,0x02,0x07,0x01,0x08,0x09,0x00,0x0a,0x0b,0xff }, then the code is 00 0x04 010 0x03 011 0x05 100 0x06 101 0x02 1100 0x07 1101 0x01 11100 0x08 11101 0x09 11110 0x00 111110 0x0a 1111110 0x0b 1111111 0xff */ ushort *CLASS make_decoder_ref(const uchar **source) { int max, len, h, i, j; const uchar *count; ushort *huff; count = (*source += 16) - 17; for (max = 16; max && !count[max]; max--) ; huff = (ushort *)calloc(1 + (1 << max), sizeof *huff); merror(huff, "make_decoder()"); huff[0] = max; for (h = len = 1; len <= max; len++) for (i = 0; i < count[len]; i++, ++*source) for (j = 0; j < 1 << (max - len); j++) if (h <= 1 << max) huff[h++] = len << 8 | **source; return huff; } ushort *CLASS make_decoder(const uchar *source) { return make_decoder_ref(&source); } void CLASS crw_init_tables(unsigned table, ushort *huff[2]) { static const uchar first_tree[3][29] = { {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x04, 0x03, 0x05, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x00, 0x0a, 0x0b, 0xff}, {0, 2, 2, 3, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0x03, 0x02, 0x04, 0x01, 0x05, 0x00, 0x06, 0x07, 0x09, 0x08, 0x0a, 0x0b, 0xff}, {0, 0, 6, 3, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x06, 0x05, 0x07, 0x04, 0x08, 0x03, 0x09, 0x02, 0x00, 0x0a, 0x01, 0x0b, 0xff}, }; static const uchar second_tree[3][180] = { {0, 2, 2, 2, 1, 4, 2, 1, 2, 5, 1, 1, 0, 0, 0, 139, 0x03, 0x04, 0x02, 0x05, 0x01, 0x06, 0x07, 0x08, 0x12, 0x13, 0x11, 0x14, 0x09, 0x15, 0x22, 0x00, 0x21, 0x16, 0x0a, 0xf0, 0x23, 0x17, 0x24, 0x31, 0x32, 0x18, 0x19, 0x33, 0x25, 0x41, 0x34, 0x42, 0x35, 0x51, 0x36, 0x37, 0x38, 0x29, 0x79, 0x26, 0x1a, 0x39, 0x56, 0x57, 0x28, 0x27, 0x52, 0x55, 0x58, 0x43, 0x76, 0x59, 0x77, 0x54, 0x61, 0xf9, 0x71, 0x78, 0x75, 0x96, 0x97, 0x49, 0xb7, 0x53, 0xd7, 0x74, 0xb6, 0x98, 0x47, 0x48, 0x95, 0x69, 0x99, 0x91, 0xfa, 0xb8, 0x68, 0xb5, 0xb9, 0xd6, 0xf7, 0xd8, 0x67, 0x46, 0x45, 0x94, 0x89, 0xf8, 0x81, 0xd5, 0xf6, 0xb4, 0x88, 0xb1, 0x2a, 0x44, 0x72, 0xd9, 0x87, 0x66, 0xd4, 0xf5, 0x3a, 0xa7, 0x73, 0xa9, 0xa8, 0x86, 0x62, 0xc7, 0x65, 0xc8, 0xc9, 0xa1, 0xf4, 0xd1, 0xe9, 0x5a, 0x92, 0x85, 0xa6, 0xe7, 0x93, 0xe8, 0xc1, 0xc6, 0x7a, 0x64, 0xe1, 0x4a, 0x6a, 0xe6, 0xb3, 0xf1, 0xd3, 0xa5, 0x8a, 0xb2, 0x9a, 0xba, 0x84, 0xa4, 0x63, 0xe5, 0xc5, 0xf3, 0xd2, 0xc4, 0x82, 0xaa, 0xda, 0xe4, 0xf2, 0xca, 0x83, 0xa3, 0xa2, 0xc3, 0xea, 0xc2, 0xe2, 0xe3, 0xff, 0xff}, {0, 2, 2, 1, 4, 1, 4, 1, 3, 3, 1, 0, 0, 0, 0, 140, 0x02, 0x03, 0x01, 0x04, 0x05, 0x12, 0x11, 0x06, 0x13, 0x07, 0x08, 0x14, 0x22, 0x09, 0x21, 0x00, 0x23, 0x15, 0x31, 0x32, 0x0a, 0x16, 0xf0, 0x24, 0x33, 0x41, 0x42, 0x19, 0x17, 0x25, 0x18, 0x51, 0x34, 0x43, 0x52, 0x29, 0x35, 0x61, 0x39, 0x71, 0x62, 0x36, 0x53, 0x26, 0x38, 0x1a, 0x37, 0x81, 0x27, 0x91, 0x79, 0x55, 0x45, 0x28, 0x72, 0x59, 0xa1, 0xb1, 0x44, 0x69, 0x54, 0x58, 0xd1, 0xfa, 0x57, 0xe1, 0xf1, 0xb9, 0x49, 0x47, 0x63, 0x6a, 0xf9, 0x56, 0x46, 0xa8, 0x2a, 0x4a, 0x78, 0x99, 0x3a, 0x75, 0x74, 0x86, 0x65, 0xc1, 0x76, 0xb6, 0x96, 0xd6, 0x89, 0x85, 0xc9, 0xf5, 0x95, 0xb4, 0xc7, 0xf7, 0x8a, 0x97, 0xb8, 0x73, 0xb7, 0xd8, 0xd9, 0x87, 0xa7, 0x7a, 0x48, 0x82, 0x84, 0xea, 0xf4, 0xa6, 0xc5, 0x5a, 0x94, 0xa4, 0xc6, 0x92, 0xc3, 0x68, 0xb5, 0xc8, 0xe4, 0xe5, 0xe6, 0xe9, 0xa2, 0xa3, 0xe3, 0xc2, 0x66, 0x67, 0x93, 0xaa, 0xd4, 0xd5, 0xe7, 0xf8, 0x88, 0x9a, 0xd7, 0x77, 0xc4, 0x64, 0xe2, 0x98, 0xa5, 0xca, 0xda, 0xe8, 0xf3, 0xf6, 0xa9, 0xb2, 0xb3, 0xf2, 0xd2, 0x83, 0xba, 0xd3, 0xff, 0xff}, {0, 0, 6, 2, 1, 3, 3, 2, 5, 1, 2, 2, 8, 10, 0, 117, 0x04, 0x05, 0x03, 0x06, 0x02, 0x07, 0x01, 0x08, 0x09, 0x12, 0x13, 0x14, 0x11, 0x15, 0x0a, 0x16, 0x17, 0xf0, 0x00, 0x22, 0x21, 0x18, 0x23, 0x19, 0x24, 0x32, 0x31, 0x25, 0x33, 0x38, 0x37, 0x34, 0x35, 0x36, 0x39, 0x79, 0x57, 0x58, 0x59, 0x28, 0x56, 0x78, 0x27, 0x41, 0x29, 0x77, 0x26, 0x42, 0x76, 0x99, 0x1a, 0x55, 0x98, 0x97, 0xf9, 0x48, 0x54, 0x96, 0x89, 0x47, 0xb7, 0x49, 0xfa, 0x75, 0x68, 0xb6, 0x67, 0x69, 0xb9, 0xb8, 0xd8, 0x52, 0xd7, 0x88, 0xb5, 0x74, 0x51, 0x46, 0xd9, 0xf8, 0x3a, 0xd6, 0x87, 0x45, 0x7a, 0x95, 0xd5, 0xf6, 0x86, 0xb4, 0xa9, 0x94, 0x53, 0x2a, 0xa8, 0x43, 0xf5, 0xf7, 0xd4, 0x66, 0xa7, 0x5a, 0x44, 0x8a, 0xc9, 0xe8, 0xc8, 0xe7, 0x9a, 0x6a, 0x73, 0x4a, 0x61, 0xc7, 0xf4, 0xc6, 0x65, 0xe9, 0x72, 0xe6, 0x71, 0x91, 0x93, 0xa6, 0xda, 0x92, 0x85, 0x62, 0xf3, 0xc5, 0xb2, 0xa4, 0x84, 0xba, 0x64, 0xa5, 0xb3, 0xd2, 0x81, 0xe5, 0xd3, 0xaa, 0xc4, 0xca, 0xf2, 0xb1, 0xe4, 0xd1, 0x83, 0x63, 0xea, 0xc3, 0xe2, 0x82, 0xf1, 0xa3, 0xc2, 0xa1, 0xc1, 0xe3, 0xa2, 0xe1, 0xff, 0xff}}; if (table > 2) table = 2; huff[0] = make_decoder(first_tree[table]); huff[1] = make_decoder(second_tree[table]); } /* Return 0 if the image starts with compressed data, 1 if it starts with uncompressed low-order bits. In Canon compressed data, 0xff is always followed by 0x00. */ int CLASS canon_has_lowbits() { uchar test[0x4000]; int ret = 1, i; fseek(ifp, 0, SEEK_SET); fread(test, 1, sizeof test, ifp); for (i = 540; i < sizeof test - 1; i++) if (test[i] == 0xff) { if (test[i + 1]) return 1; ret = 0; } return ret; } void CLASS canon_load_raw() { ushort *pixel, *prow, *huff[2]; int nblocks, lowbits, i, c, row, r, save, val; int block, diffbuf[64], leaf, len, diff, carry = 0, pnum = 0, base[2]; crw_init_tables(tiff_compress, huff); lowbits = canon_has_lowbits(); if (!lowbits) maximum = 0x3ff; fseek(ifp, 540 + lowbits * raw_height * raw_width / 4, SEEK_SET); zero_after_ff = 1; getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; nblocks = MIN(8, raw_height - row) * raw_width >> 6; for (block = 0; block < nblocks; block++) { memset(diffbuf, 0, sizeof diffbuf); for (i = 0; i < 64; i++) { leaf = gethuff(huff[i > 0]); if (leaf == 0 && i) break; if (leaf == 0xff) continue; i += leaf >> 4; len = leaf & 15; if (len == 0) continue; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; if (i < 64) diffbuf[i] = diff; } diffbuf[0] += carry; carry = diffbuf[0]; for (i = 0; i < 64; i++) { if (pnum++ % raw_width == 0) base[0] = base[1] = 512; if ((pixel[(block << 6) + i] = base[i & 1] += diffbuf[i]) >> 10) derror(); } } if (lowbits) { save = ftell(ifp); fseek(ifp, 26 + row * raw_width / 4, SEEK_SET); for (prow = pixel, i = 0; i < raw_width * 2; i++) { c = fgetc(ifp); for (r = 0; r < 8; r += 2, prow++) { val = (*prow << 2) + ((c >> r) & 3); if (raw_width == 2672 && val < 512) val += 2; *prow = val; } } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { FORC(2) free(huff[c]); throw; } #endif FORC(2) free(huff[c]); } int CLASS ljpeg_start(struct jhead *jh, int info_only) { ushort c, tag, len; int cnt = 0; uchar data[0x10000]; const uchar *dp; memset(jh, 0, sizeof *jh); jh->restart = INT_MAX; if ((fgetc(ifp), fgetc(ifp)) != 0xd8) return 0; do { if (feof(ifp)) return 0; if (cnt++ > 1024) return 0; // 1024 tags limit if (!fread(data, 2, 2, ifp)) return 0; tag = data[0] << 8 | data[1]; len = (data[2] << 8 | data[3]) - 2; if (tag <= 0xff00) return 0; fread(data, 1, len, ifp); switch (tag) { case 0xffc3: // start of frame; lossless, Huffman jh->sraw = ((data[7] >> 4) * (data[7] & 15) - 1) & 3; case 0xffc1: case 0xffc0: jh->algo = tag & 0xff; jh->bits = data[0]; jh->high = data[1] << 8 | data[2]; jh->wide = data[3] << 8 | data[4]; jh->clrs = data[5] + jh->sraw; if (len == 9 && !dng_version) getc(ifp); break; case 0xffc4: // define Huffman tables if (info_only) break; for (dp = data; dp < data + len && !((c = *dp++) & -20);) jh->free[c] = jh->huff[c] = make_decoder_ref(&dp); break; case 0xffda: // start of scan jh->psv = data[1 + data[0] * 2]; jh->bits -= data[3 + data[0] * 2] & 15; break; case 0xffdb: FORC(64) jh->quant[c] = data[c * 2 + 1] << 8 | data[c * 2 + 2]; break; case 0xffdd: jh->restart = data[0] << 8 | data[1]; } } while (tag != 0xffda); if (jh->bits > 16 || jh->clrs > 6 || !jh->bits || !jh->high || !jh->wide || !jh->clrs) return 0; if (info_only) return 1; if (!jh->huff[0]) return 0; FORC(19) if (!jh->huff[c + 1]) jh->huff[c + 1] = jh->huff[c]; if (jh->sraw) { FORC(4) jh->huff[2 + c] = jh->huff[1]; FORC(jh->sraw) jh->huff[1 + c] = jh->huff[0]; } jh->row = (ushort *)calloc(jh->wide * jh->clrs, 4); merror(jh->row, "ljpeg_start()"); return zero_after_ff = 1; } void CLASS ljpeg_end(struct jhead *jh) { int c; FORC4 if (jh->free[c]) free(jh->free[c]); free(jh->row); } int CLASS ljpeg_diff(ushort *huff) { int len, diff; if (!huff) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif len = gethuff(huff); if (len == 16 && (!dng_version || dng_version >= 0x1010000)) return -32768; diff = getbits(len); if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; return diff; } ushort *CLASS ljpeg_row(int jrow, struct jhead *jh) { int col, c, diff, pred, spred = 0; ushort mark = 0, *row[3]; if (jrow * jh->wide % jh->restart == 0) { FORC(6) jh->vpred[c] = 1 << (jh->bits - 1); if (jrow) { fseek(ifp, -2, SEEK_CUR); do mark = (mark << 8) + (c = fgetc(ifp)); while (c != EOF && mark >> 4 != 0xffd); } getbits(-1); } FORC3 row[c] = jh->row + jh->wide * jh->clrs * ((jrow + c) & 1); for (col = 0; col < jh->wide; col++) FORC(jh->clrs) { diff = ljpeg_diff(jh->huff[c]); if (jh->sraw && c <= jh->sraw && (col | c)) pred = spred; else if (col) pred = row[0][-jh->clrs]; else pred = (jh->vpred[c] += diff) - diff; if (jrow && col) switch (jh->psv) { case 1: break; case 2: pred = row[1][0]; break; case 3: pred = row[1][-jh->clrs]; break; case 4: pred = pred + row[1][0] - row[1][-jh->clrs]; break; case 5: pred = pred + ((row[1][0] - row[1][-jh->clrs]) >> 1); break; case 6: pred = row[1][0] + ((pred - row[1][-jh->clrs]) >> 1); break; case 7: pred = (pred + row[1][0]) >> 1; break; default: pred = 0; } if ((**row = pred + diff) >> jh->bits) derror(); if (c <= jh->sraw) spred = **row; row[0]++; row[1]++; } return row[2]; } void CLASS lossless_jpeg_load_raw() { int jwide, jhigh, jrow, jcol, val, jidx, i, j, row = 0, col = 0; struct jhead jh; ushort *rp; if (!ljpeg_start(&jh, 0)) return; if (jh.wide < 1 || jh.high < 1 || jh.clrs < 1 || jh.bits < 1) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 2); #endif jwide = jh.wide * jh.clrs; jhigh = jh.high; if (jh.clrs == 4 && jwide >= raw_width * 2) jhigh *= 2; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); if (load_flags & 1) row = jrow & 1 ? height - 1 - jrow / 2 : jrow / 2; for (jcol = 0; jcol < jwide; jcol++) { val = curve[*rp++]; if (cr2_slice[0]) { jidx = jrow * jwide + jcol; i = jidx / (cr2_slice[1] * raw_height); if ((j = i >= cr2_slice[0])) i = cr2_slice[0]; jidx -= i * (cr2_slice[1] * raw_height); row = jidx / cr2_slice[1 + j]; col = jidx % cr2_slice[1 + j] + i * cr2_slice[1]; } if (raw_width == 3984 && (col -= 2) < 0) col += (row--, raw_width); if (row > raw_height) #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_IO_CORRUPT; #else longjmp(failure, 3); #endif if ((unsigned)row < raw_height) RAW(row, col) = val; if (++col >= raw_width) col = (row++, 0); } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif ljpeg_end(&jh); } void CLASS canon_sraw_load_raw() { struct jhead jh; short *rp = 0, (*ip)[4]; int jwide, slice, scol, ecol, row, col, jrow = 0, jcol = 0, pix[3], c; int v[3] = {0, 0, 0}, ver, hue; #ifdef LIBRAW_LIBRARY_BUILD int saved_w = width, saved_h = height; #endif char *cp; if (!ljpeg_start(&jh, 0) || jh.clrs < 4) return; jwide = (jh.wide >>= 1) * jh.clrs; #ifdef LIBRAW_LIBRARY_BUILD if (load_flags & 256) { width = raw_width; height = raw_height; } try { #endif for (ecol = slice = 0; slice <= cr2_slice[0]; slice++) { scol = ecol; ecol += cr2_slice[1] * 2 / jh.clrs; if (!cr2_slice[0] || ecol > raw_width - 1) ecol = raw_width & -2; for (row = 0; row < height; row += (jh.clrs >> 1) - 1) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif ip = (short(*)[4])image + row * width; for (col = scol; col < ecol; col += 2, jcol += jh.clrs) { if ((jcol %= jwide) == 0) rp = (short *)ljpeg_row(jrow++, &jh); if (col >= width) continue; #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { FORC(jh.clrs - 2) { ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col + (c >> 1) * width + (c & 1)][1] = ip[col + (c >> 1) * width + (c & 1)][2] = 8192; } ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB) { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 8192; ip[col][2] = rp[jcol + jh.clrs - 1] - 8192; } else #endif { FORC(jh.clrs - 2) ip[col + (c >> 1) * width + (c & 1)][0] = rp[jcol + c]; ip[col][1] = rp[jcol + jh.clrs - 2] - 16384; ip[col][2] = rp[jcol + jh.clrs - 1] - 16384; } } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_INTERPOLATE) { ljpeg_end(&jh); maximum = 0x3fff; height = saved_h; width = saved_w; return; } #endif #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (cp = model2; *cp && !isdigit(*cp); cp++) ; sscanf(cp, "%d.%d.%d", v, v + 1, v + 2); ver = (v[0] * 1000 + v[1]) * 1000 + v[2]; hue = (jh.sraw + 1) << 2; if (unique_id >= 0x80000281 || (unique_id == 0x80000218 && ver > 1000006)) hue = jh.sraw << 1; ip = (short(*)[4])image; rp = ip[0]; for (row = 0; row < height; row++, ip += width) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (row & (jh.sraw >> 1)) { for (col = 0; col < width; col += 2) for (c = 1; c < 3; c++) if (row == height - 1) { ip[col][c] = ip[col - width][c]; } else { ip[col][c] = (ip[col - width][c] + ip[col + width][c] + 1) >> 1; } } for (col = 1; col < width; col += 2) for (c = 1; c < 3; c++) if (col == width - 1) ip[col][c] = ip[col - 1][c]; else ip[col][c] = (ip[col - 1][c] + ip[col + 1][c] + 1) >> 1; } #ifdef LIBRAW_LIBRARY_BUILD if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SRAW_NO_RGB)) #endif for (; rp < ip[0]; rp += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (unique_id == 0x80000218 || unique_id == 0x80000250 || unique_id == 0x80000261 || unique_id == 0x80000281 || unique_id == 0x80000287) { rp[1] = (rp[1] << 2) + hue; rp[2] = (rp[2] << 2) + hue; pix[0] = rp[0] + ((50 * rp[1] + 22929 * rp[2]) >> 14); pix[1] = rp[0] + ((-5640 * rp[1] - 11751 * rp[2]) >> 14); pix[2] = rp[0] + ((29040 * rp[1] - 101 * rp[2]) >> 14); } else { if (unique_id < 0x80000218) rp[0] -= 512; pix[0] = rp[0] + rp[2]; pix[2] = rp[0] + rp[1]; pix[1] = rp[0] + ((-778 * rp[1] - (rp[2] << 11)) >> 12); } FORC3 rp[c] = CLIP15(pix[c] * sraw_mul[c] >> 10); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } height = saved_h; width = saved_w; #endif ljpeg_end(&jh); maximum = 0x3fff; } void CLASS adobe_copy_pixel(unsigned row, unsigned col, ushort **rp) { int c; if (tiff_samples == 2 && shot_select) (*rp)++; if (raw_image) { if (row < raw_height && col < raw_width) RAW(row, col) = curve[**rp]; *rp += tiff_samples; } else { #ifdef LIBRAW_LIBRARY_BUILD if (row < raw_height && col < raw_width) FORC(tiff_samples) image[row * raw_width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #else if (row < height && col < width) FORC(tiff_samples) image[row * width + col][c] = curve[(*rp)[c]]; *rp += tiff_samples; #endif } if (tiff_samples == 2 && shot_select) (*rp)--; } void CLASS ljpeg_idct(struct jhead *jh) { int c, i, j, len, skip, coef; float work[3][8][8]; static float cs[106] = {0}; static const uchar zigzag[80] = {0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63, 63}; if (!cs[0]) FORC(106) cs[c] = cos((c & 31) * M_PI / 16) / 2; memset(work, 0, sizeof work); work[0][0][0] = jh->vpred[0] += ljpeg_diff(jh->huff[0]) * jh->quant[0]; for (i = 1; i < 64; i++) { len = gethuff(jh->huff[16]); i += skip = len >> 4; if (!(len &= 15) && skip < 15) break; coef = getbits(len); if ((coef & (1 << (len - 1))) == 0) coef -= (1 << len) - 1; ((float *)work)[zigzag[i]] = coef * jh->quant[i]; } FORC(8) work[0][0][c] *= M_SQRT1_2; FORC(8) work[0][c][0] *= M_SQRT1_2; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[1][i][j] += work[0][i][c] * cs[(j * 2 + 1) * c]; for (i = 0; i < 8; i++) for (j = 0; j < 8; j++) FORC(8) work[2][i][j] += work[1][c][j] * cs[(i * 2 + 1) * c]; FORC(64) jh->idct[c] = CLIP(((float *)work[2])[c] + 0.5); } void CLASS lossless_dng_load_raw() { unsigned save, trow = 0, tcol = 0, jwide, jrow, jcol, row, col, i, j; struct jhead jh; ushort *rp; while (trow < raw_height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif save = ftell(ifp); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); if (!ljpeg_start(&jh, 0)) break; jwide = jh.wide; if (filters) jwide *= jh.clrs; jwide /= MIN(is_raw, tiff_samples); #ifdef LIBRAW_LIBRARY_BUILD try { #endif switch (jh.algo) { case 0xc1: jh.vpred[0] = 16384; getbits(-1); for (jrow = 0; jrow + 7 < jh.high; jrow += 8) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (jcol = 0; jcol + 7 < jh.wide; jcol += 8) { ljpeg_idct(&jh); rp = jh.idct; row = trow + jcol / tile_width + jrow * 2; col = tcol + jcol % tile_width; for (i = 0; i < 16; i += 2) for (j = 0; j < 8; j++) adobe_copy_pixel(row + i, col + j, &rp); } } break; case 0xc3: for (row = col = jrow = 0; jrow < jh.high; jrow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif rp = ljpeg_row(jrow, &jh); for (jcol = 0; jcol < jwide; jcol++) { adobe_copy_pixel(trow + row, tcol + col, &rp); if (++col >= tile_width || col >= raw_width) row += 1 + (col = 0); } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { ljpeg_end(&jh); throw; } #endif fseek(ifp, save + 4, SEEK_SET); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); ljpeg_end(&jh); } } void CLASS packed_dng_load_raw() { ushort *pixel, *rp; int row, col; pixel = (ushort *)calloc(raw_width, tiff_samples * sizeof *pixel); merror(pixel, "packed_dng_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (tiff_bps == 16) read_shorts(pixel, raw_width * tiff_samples); else { getbits(-1); for (col = 0; col < raw_width * tiff_samples; col++) pixel[col] = getbits(tiff_bps); } for (rp = pixel, col = 0; col < raw_width; col++) adobe_copy_pixel(row, col, &rp); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); } void CLASS pentax_load_raw() { ushort bit[2][15], huff[4097]; int dep, row, col, diff, c, i; ushort vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; fseek(ifp, meta_offset, SEEK_SET); dep = (get2() + 12) & 15; fseek(ifp, 12, SEEK_CUR); FORC(dep) bit[0][c] = get2(); FORC(dep) bit[1][c] = fgetc(ifp); FORC(dep) for (i = bit[0][c]; i <= ((bit[0][c] + (4096 >> bit[1][c]) - 1) & 4095);) huff[++i] = bit[1][c] << 8 | c; huff[0] = 12; fseek(ifp, data_offset, SEEK_SET); getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS nikon_coolscan_load_raw() { int bufsize = width * 3 * tiff_bps / 8; if (tiff_bps <= 8) gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 255); else gamma_curve(1.0 / imgdata.params.coolscan_nef_gamma, 0., 1, 65535); fseek(ifp, data_offset, SEEK_SET); unsigned char *buf = (unsigned char *)malloc(bufsize); unsigned short *ubuf = (unsigned short *)buf; for (int row = 0; row < raw_height; row++) { int red = fread(buf, 1, bufsize, ifp); unsigned short(*ip)[4] = (unsigned short(*)[4])image + row * width; if (tiff_bps <= 8) for (int col = 0; col < width; col++) { ip[col][0] = curve[buf[col * 3]]; ip[col][1] = curve[buf[col * 3 + 1]]; ip[col][2] = curve[buf[col * 3 + 2]]; ip[col][3] = 0; } else for (int col = 0; col < width; col++) { ip[col][0] = curve[ubuf[col * 3]]; ip[col][1] = curve[ubuf[col * 3 + 1]]; ip[col][2] = curve[ubuf[col * 3 + 2]]; ip[col][3] = 0; } } free(buf); } #endif void CLASS nikon_load_raw() { static const uchar nikon_tree[][32] = { {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy */ 5, 4, 3, 6, 2, 7, 1, 0, 8, 9, 11, 10, 12}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 12-bit lossy after split */ 0x39, 0x5a, 0x38, 0x27, 0x16, 5, 4, 3, 2, 1, 0, 11, 12, 12}, {0, 1, 4, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 12-bit lossless */ 5, 4, 6, 3, 7, 2, 8, 1, 9, 0, 10, 11, 12}, {0, 1, 4, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, /* 14-bit lossy */ 5, 6, 4, 7, 8, 3, 9, 2, 1, 0, 10, 11, 12, 13, 14}, {0, 1, 5, 1, 1, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, /* 14-bit lossy after split */ 8, 0x5c, 0x4b, 0x3a, 0x29, 7, 6, 5, 4, 3, 2, 1, 0, 13, 14}, {0, 1, 4, 2, 2, 3, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, /* 14-bit lossless */ 7, 6, 8, 5, 9, 4, 10, 3, 11, 12, 2, 0, 1, 13, 14}}; ushort *huff, ver0, ver1, vpred[2][2], hpred[2], csize; int i, min, max, step = 0, tree = 0, split = 0, row, col, len, shl, diff; fseek(ifp, meta_offset, SEEK_SET); ver0 = fgetc(ifp); ver1 = fgetc(ifp); if (ver0 == 0x49 || ver1 == 0x58) fseek(ifp, 2110, SEEK_CUR); if (ver0 == 0x46) tree = 2; if (tiff_bps == 14) tree += 3; read_shorts(vpred[0], 4); max = 1 << tiff_bps & 0x7fff; if ((csize = get2()) > 1) step = max / (csize - 1); if (ver0 == 0x44 && ver1 == 0x20 && step > 0) { for (i = 0; i < csize; i++) curve[i * step] = get2(); for (i = 0; i < max; i++) curve[i] = (curve[i - i % step] * (step - i % step) + curve[i - i % step + step] * (i % step)) / step; fseek(ifp, meta_offset + 562, SEEK_SET); split = get2(); } else if (ver0 != 0x46 && csize <= 0x4001) read_shorts(curve, max = csize); while (curve[max - 2] == curve[max - 1]) max--; huff = make_decoder(nikon_tree[tree]); fseek(ifp, data_offset, SEEK_SET); getbits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (min = row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (split && row == split) { free(huff); huff = make_decoder(nikon_tree[tree + 1]); max += (min = 16) << 1; } for (col = 0; col < raw_width; col++) { i = gethuff(huff); len = i & 15; shl = i >> 4; diff = ((getbits(len - shl) << 1) + 1) << shl >> 1; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - !shl; if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; if ((ushort)(hpred[col & 1] + min) >= max) derror(); RAW(row, col) = curve[LIM((short)hpred[col & 1], 0, 0x3fff)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(huff); throw; } #endif free(huff); } void CLASS nikon_yuv_load_raw() { int row, col, yuv[4], rgb[3], b, c; UINT64 bitbuf = 0; float cmul[4]; FORC4 { cmul[c] = cam_mul[c] > 0.001f ? cam_mul[c] : 1.f; } for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if (!(b = col & 1)) { bitbuf = 0; FORC(6) bitbuf |= (UINT64)fgetc(ifp) << c * 8; FORC(4) yuv[c] = (bitbuf >> c * 12 & 0xfff) - (c >> 1 << 11); } rgb[0] = yuv[b] + 1.370705 * yuv[3]; rgb[1] = yuv[b] - 0.337633 * yuv[2] - 0.698001 * yuv[3]; rgb[2] = yuv[b] + 1.732446 * yuv[2]; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 0xfff)] / cmul[c]; } } } /* Returns 1 for a Coolpix 995, 0 for anything else. */ int CLASS nikon_e995() { int i, histo[256]; const uchar often[] = {0x00, 0x55, 0xaa, 0xff}; memset(histo, 0, sizeof histo); fseek(ifp, -2000, SEEK_END); for (i = 0; i < 2000; i++) histo[fgetc(ifp)]++; for (i = 0; i < 4; i++) if (histo[often[i]] < 200) return 0; return 1; } /* Returns 1 for a Coolpix 2100, 0 for anything else. */ int CLASS nikon_e2100() { uchar t[12]; int i; fseek(ifp, 0, SEEK_SET); for (i = 0; i < 1024; i++) { fread(t, 1, 12, ifp); if (((t[2] & t[4] & t[7] & t[9]) >> 4 & t[1] & t[6] & t[8] & t[11] & 3) != 3) return 0; } return 1; } void CLASS nikon_3700() { int bits, i; uchar dp[24]; static const struct { int bits; char t_make[12], t_model[15]; } table[] = { {0x00, "Pentax", "Optio 33WR"}, {0x03, "Nikon", "E3200"}, {0x32, "Nikon", "E3700"}, {0x33, "Olympus", "C740UZ"}}; fseek(ifp, 3072, SEEK_SET); fread(dp, 1, 24, ifp); bits = (dp[8] & 3) << 4 | (dp[20] & 3); for (i = 0; i < sizeof table / sizeof *table; i++) if (bits == table[i].bits) { strcpy(make, table[i].t_make); strcpy(model, table[i].t_model); } } /* Separates a Minolta DiMAGE Z2 from a Nikon E4300. */ int CLASS minolta_z2() { int i, nz; char tail[424]; fseek(ifp, -sizeof tail, SEEK_END); fread(tail, 1, sizeof tail, ifp); for (nz = i = 0; i < sizeof tail; i++) if (tail[i]) nz++; return nz > 20; } void CLASS ppm_thumb() { char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)malloc(thumb_length); merror(thumb, "ppm_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fread(thumb, 1, thumb_length, ifp); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS ppm16_thumb() { int i; char *thumb; thumb_length = thumb_width * thumb_height * 3; thumb = (char *)calloc(thumb_length, 2); merror(thumb, "ppm16_thumb()"); read_shorts((ushort *)thumb, thumb_length); for (i = 0; i < thumb_length; i++) thumb[i] = ((ushort *)thumb)[i] >> 8; fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); fwrite(thumb, 1, thumb_length, ofp); free(thumb); } void CLASS layer_thumb() { int i, c; char *thumb, map[][4] = {"012", "102"}; colors = thumb_misc >> 5 & 7; thumb_length = thumb_width * thumb_height; thumb = (char *)calloc(colors, thumb_length); merror(thumb, "layer_thumb()"); fprintf(ofp, "P%d\n%d %d\n255\n", 5 + (colors >> 1), thumb_width, thumb_height); fread(thumb, thumb_length, colors, ifp); for (i = 0; i < thumb_length; i++) FORCC putc(thumb[i + thumb_length * (map[thumb_misc >> 8][c] - '0')], ofp); free(thumb); } void CLASS rollei_thumb() { unsigned i; ushort *thumb; thumb_length = thumb_width * thumb_height; thumb = (ushort *)calloc(thumb_length, 2); merror(thumb, "rollei_thumb()"); fprintf(ofp, "P6\n%d %d\n255\n", thumb_width, thumb_height); read_shorts(thumb, thumb_length); for (i = 0; i < thumb_length; i++) { putc(thumb[i] << 3, ofp); putc(thumb[i] >> 5 << 2, ofp); putc(thumb[i] >> 11 << 3, ofp); } free(thumb); } void CLASS rollei_load_raw() { uchar pixel[10]; unsigned iten = 0, isix, i, buffer = 0, todo[16]; isix = raw_width * raw_height * 5 / 8; while (fread(pixel, 1, 10, ifp) == 10) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (i = 0; i < 10; i += 2) { todo[i] = iten++; todo[i + 1] = pixel[i] << 8 | pixel[i + 1]; buffer = pixel[i] >> 2 | buffer << 6; } for (; i < 16; i += 2) { todo[i] = isix++; todo[i + 1] = buffer >> (14 - i) * 5; } for (i = 0; i < 16; i += 2) raw_image[todo[i]] = (todo[i + 1] & 0x3ff); } maximum = 0x3ff; } int CLASS raw(unsigned row, unsigned col) { return (row < raw_height && col < raw_width) ? RAW(row, col) : 0; } void CLASS phase_one_flat_field(int is_float, int nc) { ushort head[8]; unsigned wide, high, y, x, c, rend, cend, row, col; float *mrow, num, mult[4]; read_shorts(head, 8); if (head[2] * head[3] * head[4] * head[5] == 0) return; wide = head[2] / head[4] + (head[2] % head[4] != 0); high = head[3] / head[5] + (head[3] % head[5] != 0); mrow = (float *)calloc(nc * wide, sizeof *mrow); merror(mrow, "phase_one_flat_field()"); for (y = 0; y < high; y++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) { num = is_float ? getreal(11) : get2() / 32768.0; if (y == 0) mrow[c * wide + x] = num; else mrow[(c + 1) * wide + x] = (num - mrow[c * wide + x]) / head[5]; } if (y == 0) continue; rend = head[1] + y * head[5]; for (row = rend - head[5]; row < raw_height && row < rend && row < head[1] + head[3] - head[5]; row++) { for (x = 1; x < wide; x++) { for (c = 0; c < nc; c += 2) { mult[c] = mrow[c * wide + x - 1]; mult[c + 1] = (mrow[c * wide + x] - mult[c]) / head[4]; } cend = head[0] + x * head[4]; for (col = cend - head[4]; col < raw_width && col < cend && col < head[0] + head[2] - head[4]; col++) { c = nc > 2 ? FC(row - top_margin, col - left_margin) : 0; if (!(c & 1)) { c = RAW(row, col) * mult[c]; RAW(row, col) = LIM(c, 0, 65535); } for (c = 0; c < nc; c += 2) mult[c] += mult[c + 1]; } } for (x = 0; x < wide; x++) for (c = 0; c < nc; c += 2) mrow[c * wide + x] += mrow[(c + 1) * wide + x]; } } free(mrow); } int CLASS phase_one_correct() { unsigned entries, tag, data, save, col, row, type; int len, i, j, k, cip, val[4], dev[4], sum, max; int head[9], diff, mindiff = INT_MAX, off_412 = 0; /* static */ const signed char dir[12][2] = {{-1, -1}, {-1, 1}, {1, -1}, {1, 1}, {-2, 0}, {0, -2}, {0, 2}, {2, 0}, {-2, -2}, {-2, 2}, {2, -2}, {2, 2}}; float poly[8], num, cfrac, frac, mult[2], *yval[2] = {NULL, NULL}; ushort *xval[2]; int qmult_applied = 0, qlin_applied = 0; #ifdef LIBRAW_LIBRARY_BUILD if (!meta_length) #else if (half_size || !meta_length) #endif return 0; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Phase One correction...\n")); #endif fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (entries--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x419) { /* Polynomial curve */ for (get4(), i = 0; i < 8; i++) poly[i] = getreal(11); poly[3] += (ph1.tag_210 - poly[7]) * poly[6] + 1; for (i = 0; i < 0x10000; i++) { num = (poly[5] * i + poly[3]) * i + poly[1]; curve[i] = LIM(num, 0, 65535); } goto apply; /* apply to right half */ } else if (tag == 0x41a) { /* Polynomial curve */ for (i = 0; i < 4; i++) poly[i] = getreal(11); for (i = 0; i < 0x10000; i++) { for (num = 0, j = 4; j--;) num = num * i + poly[j]; curve[i] = LIM(num + i, 0, 65535); } apply: /* apply to whole image */ for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (tag & 1) * ph1.split_col; col < raw_width; col++) RAW(row, col) = curve[RAW(row, col)]; } } else if (tag == 0x400) { /* Sensor defects */ while ((len -= 8) >= 0) { col = get2(); row = get2(); type = get2(); get2(); if (col >= raw_width) continue; if (type == 131 || type == 137) /* Bad column */ for (row = 0; row < raw_height; row++) if (FC(row - top_margin, col - left_margin) == 1) { for (sum = i = 0; i < 4; i++) sum += val[i] = raw(row + dir[i][0], col + dir[i][1]); for (max = i = 0; i < 4; i++) { dev[i] = abs((val[i] << 2) - sum); if (dev[max] < dev[i]) max = i; } RAW(row, col) = (sum - val[max]) / 3.0 + 0.5; } else { for (sum = 0, i = 8; i < 12; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = 0.5 + sum * 0.0732233 + (raw(row, col - 2) + raw(row, col + 2)) * 0.3535534; } else if (type == 129) { /* Bad pixel */ if (row >= raw_height) continue; j = (FC(row - top_margin, col - left_margin) != 1) * 4; for (sum = 0, i = j; i < j + 8; i++) sum += raw(row + dir[i][0], col + dir[i][1]); RAW(row, col) = (sum + 4) >> 3; } } } else if (tag == 0x401) { /* All-color flat fields */ phase_one_flat_field(1, 2); } else if (tag == 0x416 || tag == 0x410) { phase_one_flat_field(0, 2); } else if (tag == 0x40b) { /* Red+blue flat field */ phase_one_flat_field(0, 4); } else if (tag == 0x412) { fseek(ifp, 36, SEEK_CUR); diff = abs(get2() - ph1.tag_21a); if (mindiff > diff) { mindiff = diff; off_412 = ftell(ifp) - 38; } } else if (tag == 0x41f && !qlin_applied) { /* Quadrant linearization */ ushort lc[2][2][16], ref[16]; int qr, qc; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 16; i++) lc[qr][qc][i] = get4(); for (i = 0; i < 16; i++) { int v = 0; for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) v += lc[qr][qc][i]; ref[i] = (v + 2) >> 2; } for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[19], cf[19]; for (i = 0; i < 16; i++) { cx[1 + i] = lc[qr][qc][i]; cf[1 + i] = ref[i]; } cx[0] = cf[0] = 0; cx[17] = cf[17] = ((unsigned int)ref[15] * 65535) / lc[qr][qc][15]; cf[18] = cx[18] = 65535; cubic_spline(cx, cf, 19); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qlin_applied = 1; } else if (tag == 0x41e && !qmult_applied) { /* Quadrant multipliers */ float qmult[2][2] = {{1, 1}, {1, 1}}; get4(); get4(); get4(); get4(); qmult[0][0] = 1.0 + getreal(11); get4(); get4(); get4(); get4(); get4(); qmult[0][1] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][0] = 1.0 + getreal(11); get4(); get4(); get4(); qmult[1][1] = 1.0 + getreal(11); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { i = qmult[row >= ph1.split_row][col >= ph1.split_col] * RAW(row, col); RAW(row, col) = LIM(i, 0, 65535); } } qmult_applied = 1; } else if (tag == 0x431 && !qmult_applied) { /* Quadrant combined */ ushort lc[2][2][7], ref[7]; int qr, qc; for (i = 0; i < 7; i++) ref[i] = get4(); for (qr = 0; qr < 2; qr++) for (qc = 0; qc < 2; qc++) for (i = 0; i < 7; i++) lc[qr][qc][i] = get4(); for (qr = 0; qr < 2; qr++) { for (qc = 0; qc < 2; qc++) { int cx[9], cf[9]; for (i = 0; i < 7; i++) { cx[1 + i] = ref[i]; cf[1 + i] = ((unsigned)ref[i] * lc[qr][qc][i]) / 10000; } cx[0] = cf[0] = 0; cx[8] = cf[8] = 65535; cubic_spline(cx, cf, 9); for (row = (qr ? ph1.split_row : 0); row < (qr ? raw_height : ph1.split_row); row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = (qc ? ph1.split_col : 0); col < (qc ? raw_width : ph1.split_col); col++) RAW(row, col) = curve[RAW(row, col)]; } } } qmult_applied = 1; qlin_applied = 1; } fseek(ifp, save, SEEK_SET); } if (off_412) { fseek(ifp, off_412, SEEK_SET); for (i = 0; i < 9; i++) head[i] = get4() & 0x7fff; yval[0] = (float *)calloc(head[1] * head[3] + head[2] * head[4], 6); merror(yval[0], "phase_one_correct()"); yval[1] = (float *)(yval[0] + head[1] * head[3]); xval[0] = (ushort *)(yval[1] + head[2] * head[4]); xval[1] = (ushort *)(xval[0] + head[1] * head[3]); get2(); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) yval[i][j] = getreal(11); for (i = 0; i < 2; i++) for (j = 0; j < head[i + 1] * head[i + 3]; j++) xval[i][j] = get2(); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { cfrac = (float)col * head[3] / raw_width; cfrac -= cip = cfrac; num = RAW(row, col) * 0.5; for (i = cip; i < cip + 2; i++) { for (k = j = 0; j < head[1]; j++) if (num < xval[0][k = head[1] * i + j]) break; frac = (j == 0 || j == head[1]) ? 0 : (xval[0][k] - num) / (xval[0][k] - xval[0][k - 1]); mult[i - cip] = yval[0][k - 1] * frac + yval[0][k] * (1 - frac); } i = ((mult[0] * (1 - cfrac) + mult[1] * cfrac) * row + num) * 2; RAW(row, col) = LIM(i, 0, 65535); } } free(yval[0]); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (yval[0]) free(yval[0]); return LIBRAW_CANCELLED_BY_CALLBACK; } #endif return 0; } void CLASS phase_one_load_raw() { int a, b, i; ushort akey, bkey, t_mask; fseek(ifp, ph1.key_off, SEEK_SET); akey = get2(); bkey = get2(); t_mask = ph1.format == 1 ? 0x5555 : 0x1354; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw()"); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw()"); if (ph1.black_col) { fseek(ifp, ph1.black_col, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_cblack[0], raw_height * 2); } if (ph1.black_row) { fseek(ifp, ph1.black_row, SEEK_SET); read_shorts((ushort *)imgdata.rawdata.ph1_rblack[0], raw_width * 2); } } #endif fseek(ifp, data_offset, SEEK_SET); read_shorts(raw_image, raw_width * raw_height); if (ph1.format) for (i = 0; i < raw_width * raw_height; i += 2) { a = raw_image[i + 0] ^ akey; b = raw_image[i + 1] ^ bkey; raw_image[i + 0] = (a & t_mask) | (b & ~t_mask); raw_image[i + 1] = (b & t_mask) | (a & ~t_mask); } } unsigned CLASS ph1_bithuff(int nbits, ushort *huff) { #ifndef LIBRAW_NOTHREADS #define bitbuf tls->ph1_bits.bitbuf #define vbits tls->ph1_bits.vbits #else static UINT64 bitbuf = 0; static int vbits = 0; #endif unsigned c; if (nbits == -1) return bitbuf = vbits = 0; if (nbits == 0) return 0; if (vbits < nbits) { bitbuf = bitbuf << 32 | get4(); vbits += 32; } c = bitbuf << (64 - vbits) >> (64 - nbits); if (huff) { vbits -= huff[c] >> 8; return (uchar)huff[c]; } vbits -= nbits; return c; #ifndef LIBRAW_NOTHREADS #undef bitbuf #undef vbits #endif } #define ph1_bits(n) ph1_bithuff(n, 0) #define ph1_huff(h) ph1_bithuff(*h, h + 1) void CLASS phase_one_load_raw_c() { static const int length[] = {8, 7, 6, 9, 11, 10, 5, 12, 14, 13}; int *offset, len[2], pred[2], row, col, i, j; ushort *pixel; short(*c_black)[2], (*r_black)[2]; #ifdef LIBRAW_LIBRARY_BUILD if (ph1.format == 6) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif pixel = (ushort *)calloc(raw_width * 3 + raw_height * 4, 2); merror(pixel, "phase_one_load_raw_c()"); offset = (int *)(pixel + raw_width); fseek(ifp, strip_offset, SEEK_SET); for (row = 0; row < raw_height; row++) offset[row] = get4(); c_black = (short(*)[2])(offset + raw_height); fseek(ifp, ph1.black_col, SEEK_SET); if (ph1.black_col) read_shorts((ushort *)c_black[0], raw_height * 2); r_black = c_black + raw_height; fseek(ifp, ph1.black_row, SEEK_SET); if (ph1.black_row) read_shorts((ushort *)r_black[0], raw_width * 2); #ifdef LIBRAW_LIBRARY_BUILD // Copy data to internal copy (ever if not read) if (ph1.black_col || ph1.black_row) { imgdata.rawdata.ph1_cblack = (short(*)[2])calloc(raw_height * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_cblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_cblack, (ushort *)c_black[0], raw_height * 2 * sizeof(ushort)); imgdata.rawdata.ph1_rblack = (short(*)[2])calloc(raw_width * 2, sizeof(ushort)); merror(imgdata.rawdata.ph1_rblack, "phase_one_load_raw_c()"); memmove(imgdata.rawdata.ph1_rblack, (ushort *)r_black[0], raw_width * 2 * sizeof(ushort)); } #endif for (i = 0; i < 256; i++) curve[i] = i * i / 3.969 + 0.5; #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + offset[row], SEEK_SET); ph1_bits(-1); pred[0] = pred[1] = 0; for (col = 0; col < raw_width; col++) { if (col >= (raw_width & -8)) len[0] = len[1] = 14; else if ((col & 7) == 0) for (i = 0; i < 2; i++) { for (j = 0; j < 5 && !ph1_bits(1); j++) ; if (j--) len[i] = length[j * 2 + ph1_bits(1)]; } if ((i = len[col & 1]) == 14) pixel[col] = pred[col & 1] = ph1_bits(16); else pixel[col] = pred[col & 1] += ph1_bits(i) + 1 - (1 << (i - 1)); if (pred[col & 1] >> 16) derror(); if (ph1.format == 5 && pixel[col] < 256) pixel[col] = curve[pixel[col]]; } #ifndef LIBRAW_LIBRARY_BUILD for (col = 0; col < raw_width; col++) { int shift = ph1.format == 8 ? 0 : 2; i = (pixel[col] << shift) - ph1.t_black + c_black[row][col >= ph1.split_col] + r_black[col][row >= ph1.split_row]; if (i > 0) RAW(row, col) = i; } #else if (ph1.format == 8) memmove(&RAW(row, 0), &pixel[0], raw_width * 2); else for (col = 0; col < raw_width; col++) RAW(row, col) = pixel[col] << 2; #endif } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = 0xfffc - ph1.t_black; } void CLASS hasselblad_load_raw() { struct jhead jh; int shot, row, col, *back[5], len[2], diff[12], pred, sh, f, s, c; unsigned upix, urow, ucol; ushort *ip; if (!ljpeg_start(&jh, 0)) return; order = 0x4949; ph1_bits(-1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif back[4] = (int *)calloc(raw_width, 3 * sizeof **back); merror(back[4], "hasselblad_load_raw()"); FORC3 back[c] = back[4] + c * raw_width; cblack[6] >>= sh = tiff_samples > 1; shot = LIM(shot_select, 1, tiff_samples) - 1; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC4 back[(c + 3) & 3] = back[c]; for (col = 0; col < raw_width; col += 2) { for (s = 0; s < tiff_samples * 2; s += 2) { FORC(2) len[c] = ph1_huff(jh.huff[0]); FORC(2) { diff[s + c] = ph1_bits(len[c]); if ((diff[s + c] & (1 << (len[c] - 1))) == 0) diff[s + c] -= (1 << len[c]) - 1; if (diff[s + c] == 65535) diff[s + c] = -32768; } } for (s = col; s < col + 2; s++) { pred = 0x8000 + load_flags; if (col) pred = back[2][s - 2]; if (col && row > 1) switch (jh.psv) { case 11: pred += back[0][s] / 2 - back[0][s - 2] / 2; break; } f = (row & 1) * 3 ^ ((col + s) & 1); FORC(tiff_samples) { pred += diff[(s & 1) * tiff_samples + c]; upix = pred >> sh & 0xffff; if (raw_image && c == shot) RAW(row, s) = upix; if (image) { urow = row - top_margin + (c & 1); ucol = col - left_margin - ((c >> 1) & 1); ip = &image[urow * width + ucol][f]; if (urow < height && ucol < width) *ip = c < 4 ? upix : (*ip + upix) >> 1; } } back[2][s] = pred; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(back[4]); ljpeg_end(&jh); throw; } #endif free(back[4]); ljpeg_end(&jh); if (image) mix_green = 1; } void CLASS leaf_hdr_load_raw() { ushort *pixel = 0; unsigned tile = 0, r, c, row, col; if (!filters || !raw_image) { pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "leaf_hdr_load_raw()"); } #ifdef LIBRAW_LIBRARY_BUILD try { #endif FORC(tiff_samples) for (r = 0; r < raw_height; r++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (r % tile_length == 0) { fseek(ifp, data_offset + 4 * tile++, SEEK_SET); fseek(ifp, get4(), SEEK_SET); } if (filters && c != shot_select) continue; if (filters && raw_image) pixel = raw_image + r * raw_width; read_shorts(pixel, raw_width); if (!filters && image && (row = r - top_margin) < height) for (col = 0; col < width; col++) image[row * width + col][c] = pixel[col + left_margin]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { if (!filters) free(pixel); throw; } #endif if (!filters) { maximum = 0xffff; raw_color = 1; free(pixel); } } void CLASS unpacked_load_raw() { int row, col, bits = 0; while (1 << ++bits < maximum) ; read_shorts(raw_image, raw_width * raw_height); if (maximum < 0xffff || load_flags) for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS unpacked_load_raw_reversed() { int row, col, bits = 0; while (1 << ++bits < maximum) ; for (row = raw_height - 1; row >= 0; row--) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif read_shorts(&raw_image[row * raw_width], raw_width); for (col = 0; col < raw_width; col++) if ((RAW(row, col) >>= load_flags) >> bits && (unsigned)(row - top_margin) < height && (unsigned)(col - left_margin) < width) derror(); } } void CLASS sinar_4shot_load_raw() { ushort *pixel; unsigned shot, row, col, r, c; if (raw_image) { shot = LIM(shot_select, 1, 4) - 1; fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); unpacked_load_raw(); return; } pixel = (ushort *)calloc(raw_width, sizeof *pixel); merror(pixel, "sinar_4shot_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (shot = 0; shot < 4; shot++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, data_offset + shot * 4, SEEK_SET); fseek(ifp, get4(), SEEK_SET); for (row = 0; row < raw_height; row++) { read_shorts(pixel, raw_width); if ((r = row - top_margin - (shot >> 1 & 1)) >= height) continue; for (col = 0; col < raw_width; col++) { if ((c = col - left_margin - (shot & 1)) >= width) continue; image[r * width + c][(row & 1) * 3 ^ (~col & 1)] = pixel[col]; } } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); mix_green = 1; } void CLASS imacon_full_load_raw() { int row, col; if (!image) return; #ifdef LIBRAW_LIBRARY_BUILD unsigned short *buf = (unsigned short *)malloc(width * 3 * sizeof(unsigned short)); merror(buf, "imacon_full_load_raw"); #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); read_shorts(buf, width * 3); unsigned short(*rowp)[4] = &image[row * width]; for (col = 0; col < width; col++) { rowp[col][0] = buf[col * 3]; rowp[col][1] = buf[col * 3 + 1]; rowp[col][2] = buf[col * 3 + 2]; rowp[col][3] = 0; } #else for (col = 0; col < width; col++) read_shorts(image[row * width + col], 3); #endif } #ifdef LIBRAW_LIBRARY_BUILD free(buf); #endif } void CLASS packed_load_raw() { int vbits = 0, bwide, rbits, bite, half, irow, row, col, val, i; UINT64 bitbuf = 0; bwide = raw_width * tiff_bps / 8; bwide += bwide & load_flags >> 7; rbits = bwide * 8 - raw_width * tiff_bps; if (load_flags & 1) bwide = bwide * 16 / 15; bite = 8 + (load_flags & 24); half = (raw_height + 1) >> 1; for (irow = 0; irow < raw_height; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif row = irow; if (load_flags & 2 && (row = irow % half * 2 + irow / half) == 1 && load_flags & 4) { if (vbits = 0, tiff_compress) fseek(ifp, data_offset - (-half * bwide & -2048), SEEK_SET); else { fseek(ifp, 0, SEEK_END); fseek(ifp, ftell(ifp) >> 3 << 2, SEEK_SET); } } for (col = 0; col < raw_width; col++) { for (vbits -= tiff_bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } val = bitbuf << (64 - tiff_bps - vbits) >> (64 - tiff_bps); RAW(row, col ^ (load_flags >> 6 & 1)) = val; if (load_flags & 1 && (col % 10) == 9 && fgetc(ifp) && row < height + top_margin && col < width + left_margin) derror(); } vbits -= rbits; } } #ifdef LIBRAW_LIBRARY_BUILD ushort raw_stride; void CLASS parse_broadcom() { /* This structure is at offset 0xb0 from the 'BRCM' ident. */ struct { uint8_t umode[32]; uint16_t uwidth; uint16_t uheight; uint16_t padding_right; uint16_t padding_down; uint32_t unknown_block[6]; uint16_t transform; uint16_t format; uint8_t bayer_order; uint8_t bayer_format; } header; header.bayer_order = 0; fseek(ifp, 0xb0 - 0x20, SEEK_CUR); fread(&header, 1, sizeof(header), ifp); raw_stride = ((((((header.uwidth + header.padding_right) * 5) + 3) >> 2) + 0x1f) & (~0x1f)); raw_width = width = header.uwidth; raw_height = height = header.uheight; filters = 0x16161616; /* default Bayer order is 2, BGGR */ switch (header.bayer_order) { case 0: /* RGGB */ filters = 0x94949494; break; case 1: /* GBRG */ filters = 0x49494949; break; case 3: /* GRBG */ filters = 0x61616161; break; } } void CLASS broadcom_load_raw() { uchar *data, *dp; int rev, row, col, c; rev = 3 * (order == 0x4949); data = (uchar *)malloc(raw_stride * 2); merror(data, "broadcom_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data + raw_stride, 1, raw_stride, ifp) < raw_stride) derror(); FORC(raw_stride) data[c] = data[raw_stride + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } #endif void CLASS nokia_load_raw() { uchar *data, *dp; int rev, dwide, row, col, c; double sum[] = {0, 0}; rev = 3 * (order == 0x4949); dwide = (raw_width * 5 + 1) / 4; data = (uchar *)malloc(dwide * 2); merror(data, "nokia_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(data + dwide, 1, dwide, ifp) < dwide) derror(); FORC(dwide) data[c] = data[dwide + (c ^ rev)]; for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } #endif free(data); maximum = 0x3ff; if (strncmp(make, "OmniVision", 10)) return; row = raw_height / 2; FORC(width - 1) { sum[c & 1] += SQR(RAW(row, c) - RAW(row + 1, c + 1)); sum[~c & 1] += SQR(RAW(row + 1, c) - RAW(row, c + 1)); } if (sum[1] > sum[0]) filters = 0x4b4b4b4b; } void CLASS android_tight_load_raw() { uchar *data, *dp; int bwide, row, col, c; bwide = -(-5 * raw_width >> 5) << 3; data = (uchar *)malloc(bwide); merror(data, "android_tight_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 5, col += 4) FORC4 RAW(row, col + c) = (dp[c] << 2) | (dp[4] >> (c << 1) & 3); } free(data); } void CLASS android_loose_load_raw() { uchar *data, *dp; int bwide, row, col, c; UINT64 bitbuf = 0; bwide = (raw_width + 5) / 6 << 3; data = (uchar *)malloc(bwide); merror(data, "android_loose_load_raw()"); for (row = 0; row < raw_height; row++) { if (fread(data, 1, bwide, ifp) < bwide) derror(); for (dp = data, col = 0; col < raw_width; dp += 8, col += 6) { FORC(8) bitbuf = (bitbuf << 8) | dp[c ^ 7]; FORC(6) RAW(row, col + c) = (bitbuf >> c * 10) & 0x3ff; } } free(data); } void CLASS canon_rmf_load_raw() { int row, col, bits, orow, ocol, c; #ifdef LIBRAW_LIBRARY_BUILD int *words = (int *)malloc(sizeof(int) * (raw_width / 3 + 1)); merror(words, "canon_rmf_load_raw"); #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); fread(words, sizeof(int), raw_width / 3, ifp); for (col = 0; col < raw_width - 2; col += 3) { bits = words[col / 3]; FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #else for (col = 0; col < raw_width - 2; col += 3) { bits = get4(); FORC3 { orow = row; if ((ocol = col + c - 4) < 0) { ocol += raw_width; if ((orow -= 2) < 0) orow += raw_height; } RAW(orow, ocol) = curve[bits >> (10 * c + 2) & 0x3ff]; } } #endif } #ifdef LIBRAW_LIBRARY_BUILD free(words); #endif maximum = curve[0x3ff]; } unsigned CLASS pana_bits(int nbits) { #ifndef LIBRAW_NOTHREADS #define buf tls->pana_bits.buf #define vbits tls->pana_bits.vbits #else static uchar buf[0x4000]; static int vbits; #endif int byte; if (!nbits) return vbits = 0; if (!vbits) { fread(buf + load_flags, 1, 0x4000 - load_flags, ifp); fread(buf, 1, load_flags, ifp); } vbits = (vbits - nbits) & 0x1ffff; byte = vbits >> 3 ^ 0x3ff0; return (buf[byte] | buf[byte + 1] << 8) >> (vbits & 7) & ~((~0u) << nbits); #ifndef LIBRAW_NOTHREADS #undef buf #undef vbits #endif } void CLASS panasonic_load_raw() { int row, col, i, j, sh = 0, pred[2], nonz[2]; pana_bits(0); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { if ((i = col % 14) == 0) pred[0] = pred[1] = nonz[0] = nonz[1] = 0; if (i % 3 == 2) sh = 4 >> (3 - pana_bits(2)); if (nonz[i & 1]) { if ((j = pana_bits(8))) { if ((pred[i & 1] -= 0x80 << sh) < 0 || sh == 4) pred[i & 1] &= ~((~0u) << sh); pred[i & 1] += j << sh; } } else if ((nonz[i & 1] = pana_bits(8)) || i > 11) pred[i & 1] = nonz[i & 1] << 4 | pana_bits(4); if ((RAW(row, col) = pred[col & 1]) > 4098 && col < width && row < height) derror(); } } } void CLASS panasonic_16x10_load_raw() { #ifdef LIBRAW_LIBRARY_BUILD throw LIBRAW_EXCEPTION_DECODE_RAW; #endif } void CLASS olympus_load_raw() { ushort huff[4096]; int row, col, nbits, sign, low, high, i, c, w, n, nw; int acarry[2][3], *carry, pred, diff; huff[n = 0] = 0xc0c; for (i = 12; i--;) FORC(2048 >> i) huff[++n] = (i + 1) << 8 | i; fseek(ifp, 7, SEEK_CUR); getbits(-1); for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif memset(acarry, 0, sizeof acarry); for (col = 0; col < raw_width; col++) { carry = acarry[col & 1]; i = 2 * (carry[2] < 3); for (nbits = 2 + i; (ushort)carry[0] >> (nbits + i); nbits++) ; low = (sign = getbits(3)) & 3; sign = sign << 29 >> 31; if ((high = getbithuff(12, huff)) == 12) high = getbits(16 - nbits) >> 1; carry[0] = (high << nbits) | getbits(nbits); diff = (carry[0] ^ sign) + carry[1]; carry[1] = (diff * 3 + carry[1]) >> 5; carry[2] = carry[0] > 16 ? 0 : carry[2] + 1; if (col >= width) continue; if (row < 2 && col < 2) pred = 0; else if (row < 2) pred = RAW(row, col - 2); else if (col < 2) pred = RAW(row - 2, col); else { w = RAW(row, col - 2); n = RAW(row - 2, col); nw = RAW(row - 2, col - 2); if ((w < nw && nw < n) || (n < nw && nw < w)) { if (ABS(w - nw) > 32 || ABS(n - nw) > 32) pred = w + n - nw; else pred = (w + n) >> 1; } else pred = ABS(w - nw) > ABS(n - nw) ? w : n; } if ((RAW(row, col) = pred + ((diff << 2) | low)) >> 12) derror(); } } } void CLASS minolta_rd175_load_raw() { uchar pixel[768]; unsigned irow, box, row, col; for (irow = 0; irow < 1481; irow++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 768, ifp) < 768) derror(); box = irow / 82; row = irow % 82 * 12 + ((box < 12) ? box | 1 : (box - 12) * 2); switch (irow) { case 1477: case 1479: continue; case 1476: row = 984; break; case 1480: row = 985; break; case 1478: row = 985; box = 1; } if ((box < 12) && (box & 1)) { for (col = 0; col < 1533; col++, row ^= 1) if (col != 1) RAW(row, col) = (col + 1) & 2 ? pixel[col / 2 - 1] + pixel[col / 2 + 1] : pixel[col / 2] << 1; RAW(row, 1) = pixel[1] << 1; RAW(row, 1533) = pixel[765] << 1; } else for (col = row & 1; col < 1534; col += 2) RAW(row, col) = pixel[col / 2] << 1; } maximum = 0xff << 1; } void CLASS quicktake_100_load_raw() { uchar pixel[484][644]; static const short gstep[16] = {-89, -60, -44, -32, -22, -15, -8, -2, 2, 8, 15, 22, 32, 44, 60, 89}; static const short rstep[6][4] = {{-3, -1, 1, 3}, {-5, -1, 1, 5}, {-8, -2, 2, 8}, {-13, -3, 3, 13}, {-19, -4, 4, 19}, {-28, -6, 6, 28}}; static const short t_curve[256] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 88, 90, 92, 94, 97, 99, 101, 103, 105, 107, 110, 112, 114, 116, 118, 120, 123, 125, 127, 129, 131, 134, 136, 138, 140, 142, 144, 147, 149, 151, 153, 155, 158, 160, 162, 164, 166, 168, 171, 173, 175, 177, 179, 181, 184, 186, 188, 190, 192, 195, 197, 199, 201, 203, 205, 208, 210, 212, 214, 216, 218, 221, 223, 226, 230, 235, 239, 244, 248, 252, 257, 261, 265, 270, 274, 278, 283, 287, 291, 296, 300, 305, 309, 313, 318, 322, 326, 331, 335, 339, 344, 348, 352, 357, 361, 365, 370, 374, 379, 383, 387, 392, 396, 400, 405, 409, 413, 418, 422, 426, 431, 435, 440, 444, 448, 453, 457, 461, 466, 470, 474, 479, 483, 487, 492, 496, 500, 508, 519, 531, 542, 553, 564, 575, 587, 598, 609, 620, 631, 643, 654, 665, 676, 687, 698, 710, 721, 732, 743, 754, 766, 777, 788, 799, 810, 822, 833, 844, 855, 866, 878, 889, 900, 911, 922, 933, 945, 956, 967, 978, 989, 1001, 1012, 1023}; int rb, row, col, sharp, val = 0; getbits(-1); memset(pixel, 0x80, sizeof pixel); for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 2 + (row & 1); col < width + 2; col += 2) { val = ((pixel[row - 1][col - 1] + 2 * pixel[row - 1][col + 1] + pixel[row][col - 2]) >> 2) + gstep[getbits(4)]; pixel[row][col] = val = LIM(val, 0, 255); if (col < 4) pixel[row][col - 2] = pixel[row + 1][~row & 1] = val; if (row == 2) pixel[row - 1][col + 1] = pixel[row - 1][col + 3] = val; } pixel[row][col] = val; } for (rb = 0; rb < 2; rb++) for (row = 2 + rb; row < height + 2; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { if (row < 4 || col < 4) sharp = 2; else { val = ABS(pixel[row - 2][col] - pixel[row][col - 2]) + ABS(pixel[row - 2][col] - pixel[row - 2][col - 2]) + ABS(pixel[row][col - 2] - pixel[row - 2][col - 2]); sharp = val < 4 ? 0 : val < 8 ? 1 : val < 16 ? 2 : val < 32 ? 3 : val < 48 ? 4 : 5; } val = ((pixel[row - 2][col] + pixel[row][col - 2]) >> 1) + rstep[sharp][getbits(2)]; pixel[row][col] = val = LIM(val, 0, 255); if (row < 4) pixel[row - 2][col + 2] = val; if (col < 4) pixel[row + 2][col - 2] = val; } } for (row = 2; row < height + 2; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 3 - (row & 1); col < width + 2; col += 2) { val = ((pixel[row][col - 1] + (pixel[row][col] << 2) + pixel[row][col + 1]) >> 1) - 0x100; pixel[row][col] = LIM(val, 0, 255); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = t_curve[pixel[row + 2][col + 2]]; } maximum = 0x3ff; } #define radc_token(tree) ((signed char)getbithuff(8, huff[tree])) #define FORYX \ for (y = 1; y < 3; y++) \ for (x = col + 1; x >= col; x--) #define PREDICTOR \ (c ? (buf[c][y - 1][x] + buf[c][y][x + 1]) / 2 : (buf[c][y - 1][x + 1] + 2 * buf[c][y - 1][x] + buf[c][y][x + 1]) / 4) #ifdef __GNUC__ #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8) #pragma GCC optimize("no-aggressive-loop-optimizations") #endif #endif void CLASS kodak_radc_load_raw() { static const signed char src[] = { 1, 1, 2, 3, 3, 4, 4, 2, 5, 7, 6, 5, 7, 6, 7, 8, 1, 0, 2, 1, 3, 3, 4, 4, 5, 2, 6, 7, 7, 6, 8, 5, 8, 8, 2, 1, 2, 3, 3, 0, 3, 2, 3, 4, 4, 6, 5, 5, 6, 7, 6, 8, 2, 0, 2, 1, 2, 3, 3, 2, 4, 4, 5, 6, 6, 7, 7, 5, 7, 8, 2, 1, 2, 4, 3, 0, 3, 2, 3, 3, 4, 7, 5, 5, 6, 6, 6, 8, 2, 3, 3, 1, 3, 2, 3, 4, 3, 5, 3, 6, 4, 7, 5, 0, 5, 8, 2, 3, 2, 6, 3, 0, 3, 1, 4, 4, 4, 5, 4, 7, 5, 2, 5, 8, 2, 4, 2, 7, 3, 3, 3, 6, 4, 1, 4, 2, 4, 5, 5, 0, 5, 8, 2, 6, 3, 1, 3, 3, 3, 5, 3, 7, 3, 8, 4, 0, 5, 2, 5, 4, 2, 0, 2, 1, 3, 2, 3, 3, 4, 4, 4, 5, 5, 6, 5, 7, 4, 8, 1, 0, 2, 2, 2, -2, 1, -3, 1, 3, 2, -17, 2, -5, 2, 5, 2, 17, 2, -7, 2, 2, 2, 9, 2, 18, 2, -18, 2, -9, 2, -2, 2, 7, 2, -28, 2, 28, 3, -49, 3, -9, 3, 9, 4, 49, 5, -79, 5, 79, 2, -1, 2, 13, 2, 26, 3, 39, 4, -16, 5, 55, 6, -37, 6, 76, 2, -26, 2, -13, 2, 1, 3, -39, 4, 16, 5, -55, 6, -76, 6, 37}; ushort huff[19][256]; int row, col, tree, nreps, rep, step, i, c, s, r, x, y, val; short last[3] = {16, 16, 16}, mul[3], buf[3][3][386]; static const ushort pt[] = {0, 0, 1280, 1344, 2320, 3616, 3328, 8000, 4095, 16383, 65535, 16383}; for (i = 2; i < 12; i += 2) for (c = pt[i - 2]; c <= pt[i]; c++) curve[c] = (float)(c - pt[i - 2]) / (pt[i] - pt[i - 2]) * (pt[i + 1] - pt[i - 1]) + pt[i - 1] + 0.5; for (s = i = 0; i < sizeof src; i += 2) FORC(256 >> src[i]) ((ushort *)huff)[s++] = src[i] << 8 | (uchar)src[i + 1]; s = kodak_cbpp == 243 ? 2 : 3; FORC(256) huff[18][c] = (8 - s) << 8 | c >> s << s | 1 << (s - 1); getbits(-1); for (i = 0; i < sizeof(buf) / sizeof(short); i++) ((short *)buf)[i] = 2048; for (row = 0; row < height; row += 4) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif FORC3 mul[c] = getbits(6); #ifdef LIBRAW_LIBRARY_BUILD if(!mul[0] || !mul[1] || !mul[2]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif FORC3 { val = ((0x1000000 / last[c] + 0x7ff) >> 12) * mul[c]; s = val > 65564 ? 10 : 12; x = ~((~0u) << (s - 1)); val <<= 12 - s; for (i = 0; i < sizeof(buf[0]) / sizeof(short); i++) ((short *)buf[c])[i] = (((short *)buf[c])[i] * val + x) >> s; last[c] = mul[c]; for (r = 0; r <= !c; r++) { buf[c][1][width / 2] = buf[c][2][width / 2] = mul[c] << 7; for (tree = 1, col = width / 2; col > 0;) { if ((tree = radc_token(tree))) { col -= 2; if (tree == 8) FORYX buf[c][y][x] = (uchar)radc_token(18) * mul[c]; else FORYX buf[c][y][x] = radc_token(tree + 10) * 16 + PREDICTOR; } else do { nreps = (col > 2) ? radc_token(9) + 1 : 1; for (rep = 0; rep < 8 && rep < nreps && col > 0; rep++) { col -= 2; FORYX buf[c][y][x] = PREDICTOR; if (rep & 1) { step = radc_token(10) << 4; FORYX buf[c][y][x] += step; } } } while (nreps == 9); } for (y = 0; y < 2; y++) for (x = 0; x < width / 2; x++) { val = (buf[c][y + 1][x] << 4) / mul[c]; if (val < 0) val = 0; if (c) RAW(row + y * 2 + c - 1, x * 2 + 2 - c) = val; else RAW(row + r * 2 + y, x * 2 + y) = val; } memcpy(buf[c][0] + !c, buf[c][2], sizeof buf[c][0] - 2 * !c); } } for (y = row; y < row + 4; y++) for (x = 0; x < width; x++) if ((x + y) & 1) { r = x ? x - 1 : x + 1; s = x + 1 < width ? x + 1 : x - 1; val = (RAW(y, x) - 2048) * 2 + (RAW(y, r) + RAW(y, s)) / 2; if (val < 0) val = 0; RAW(y, x) = val; } } for (i = 0; i < height * width; i++) raw_image[i] = curve[raw_image[i]]; maximum = 0x3fff; } #undef FORYX #undef PREDICTOR #ifdef NO_JPEG void CLASS kodak_jpeg_load_raw() {} void CLASS lossy_dng_load_raw() {} #else #ifndef LIBRAW_LIBRARY_BUILD METHODDEF(boolean) fill_input_buffer(j_decompress_ptr cinfo) { static uchar jpeg_buffer[4096]; size_t nbytes; nbytes = fread(jpeg_buffer, 1, 4096, ifp); swab(jpeg_buffer, jpeg_buffer, nbytes); cinfo->src->next_input_byte = jpeg_buffer; cinfo->src->bytes_in_buffer = nbytes; return TRUE; } void CLASS kodak_jpeg_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; int row, col; cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, ifp); cinfo.src->fill_input_buffer = fill_input_buffer; jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { fprintf(stderr, _("%s: incorrect JPEG dimensions\n"), ifname); jpeg_destroy_decompress(&cinfo); longjmp(failure, 3); } buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, width * 3, 1); while (cinfo.output_scanline < cinfo.output_height) { row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); maximum = 0xff << 1; } #else struct jpegErrorManager { struct jpeg_error_mgr pub; }; static void jpegErrorExit(j_common_ptr cinfo) { jpegErrorManager *myerr = (jpegErrorManager *)cinfo->err; throw LIBRAW_EXCEPTION_DECODE_JPEG; } // LibRaw's Kodak_jpeg_load_raw void CLASS kodak_jpeg_load_raw() { if (data_size < 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; int row, col; jpegErrorManager jerr; struct jpeg_decompress_struct cinfo; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; unsigned char *jpg_buf = (unsigned char *)malloc(data_size); merror(jpg_buf, "kodak_jpeg_load_raw"); unsigned char *pixel_buf = (unsigned char *)malloc(width * 3); jpeg_create_decompress(&cinfo); merror(pixel_buf, "kodak_jpeg_load_raw"); fread(jpg_buf, data_size, 1, ifp); swab((char *)jpg_buf, (char *)jpg_buf, data_size); try { jpeg_mem_src(&cinfo, jpg_buf, data_size); int rc = jpeg_read_header(&cinfo, TRUE); if (rc != 1) throw LIBRAW_EXCEPTION_DECODE_JPEG; jpeg_start_decompress(&cinfo); if ((cinfo.output_width != width) || (cinfo.output_height * 2 != height) || (cinfo.output_components != 3)) { throw LIBRAW_EXCEPTION_DECODE_JPEG; } unsigned char *buf[1]; buf[0] = pixel_buf; while (cinfo.output_scanline < cinfo.output_height) { checkCancel(); row = cinfo.output_scanline * 2; jpeg_read_scanlines(&cinfo, buf, 1); unsigned char(*pixel)[3] = (unsigned char(*)[3])buf[0]; for (col = 0; col < width; col += 2) { RAW(row + 0, col + 0) = pixel[col + 0][1] << 1; RAW(row + 1, col + 1) = pixel[col + 1][1] << 1; RAW(row + 0, col + 1) = pixel[col][0] + pixel[col + 1][0]; RAW(row + 1, col + 0) = pixel[col][2] + pixel[col + 1][2]; } } } catch (...) { jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); throw; } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); free(jpg_buf); free(pixel_buf); maximum = 0xff << 1; } #endif #ifndef LIBRAW_LIBRARY_BUILD void CLASS gamma_curve(double pwr, double ts, int mode, int imax); #endif void CLASS lossy_dng_load_raw() { struct jpeg_decompress_struct cinfo; struct jpeg_error_mgr jerr; JSAMPARRAY buf; JSAMPLE(*pixel)[3]; unsigned sorder = order, ntags, opcode, deg, i, j, c; unsigned save = data_offset - 4, trow = 0, tcol = 0, row, col; ushort cur[3][256]; double coeff[9], tot; if (meta_offset) { fseek(ifp, meta_offset, SEEK_SET); order = 0x4d4d; ntags = get4(); while (ntags--) { opcode = get4(); get4(); get4(); if (opcode != 8) { fseek(ifp, get4(), SEEK_CUR); continue; } fseek(ifp, 20, SEEK_CUR); if ((c = get4()) > 2) break; fseek(ifp, 12, SEEK_CUR); if ((deg = get4()) > 8) break; for (i = 0; i <= deg && i < 9; i++) coeff[i] = getreal(12); for (i = 0; i < 256; i++) { for (tot = j = 0; j <= deg; j++) tot += coeff[j] * pow(i / 255.0, (int)j); cur[c][i] = tot * 0xffff; } } order = sorder; } else { gamma_curve(1 / 2.4, 12.92, 1, 255); FORC3 memcpy(cur[c], curve, sizeof cur[0]); } cinfo.err = jpeg_std_error(&jerr); jpeg_create_decompress(&cinfo); while (trow < raw_height) { fseek(ifp, save += 4, SEEK_SET); if (tile_length < INT_MAX) fseek(ifp, get4(), SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD if (libraw_internal_data.internal_data.input->jpeg_src(&cinfo) == -1) { jpeg_destroy_decompress(&cinfo); throw LIBRAW_EXCEPTION_DECODE_JPEG; } #else jpeg_stdio_src(&cinfo, ifp); #endif jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); buf = (*cinfo.mem->alloc_sarray)((j_common_ptr)&cinfo, JPOOL_IMAGE, cinfo.output_width * 3, 1); #ifdef LIBRAW_LIBRARY_BUILD try { #endif while (cinfo.output_scanline < cinfo.output_height && (row = trow + cinfo.output_scanline) < height) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jpeg_read_scanlines(&cinfo, buf, 1); pixel = (JSAMPLE(*)[3])buf[0]; for (col = 0; col < cinfo.output_width && tcol + col < width; col++) { FORC3 image[row * width + tcol + col][c] = cur[c][pixel[col][c]]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { jpeg_destroy_decompress(&cinfo); throw; } #endif jpeg_abort_decompress(&cinfo); if ((tcol += tile_width) >= raw_width) trow += tile_length + (tcol = 0); } jpeg_destroy_decompress(&cinfo); maximum = 0xffff; } #endif void CLASS kodak_dc120_load_raw() { static const int mul[4] = {162, 192, 187, 92}; static const int add[4] = {0, 636, 424, 212}; uchar pixel[848]; int row, shift, col; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, 848, ifp) < 848) derror(); shift = row * mul[row & 3] + add[row & 3]; for (col = 0; col < width; col++) RAW(row, col) = (ushort)pixel[(col + shift) % 848]; } maximum = 0xff; } void CLASS eight_bit_load_raw() { uchar *pixel; unsigned row, col; pixel = (uchar *)calloc(raw_width, sizeof *pixel); merror(pixel, "eight_bit_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, 1, raw_width, ifp) < raw_width) derror(); for (col = 0; col < raw_width; col++) RAW(row, col) = curve[pixel[col]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c330_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 2 * sizeof *pixel); merror(pixel, "kodak_c330_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (fread(pixel, raw_width, 2, ifp) < 2) derror(); if (load_flags && (row & 31) == 31) fseek(ifp, raw_width * 32, SEEK_CUR); for (col = 0; col < width; col++) { y = pixel[col * 2]; cb = pixel[(col * 2 & -4) | 1] - 128; cr = pixel[(col * 2 & -4) | 3] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_c603_load_raw() { uchar *pixel; int row, col, y, cb, cr, rgb[3], c; pixel = (uchar *)calloc(raw_width, 3 * sizeof *pixel); merror(pixel, "kodak_c603_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if (~row & 1) if (fread(pixel, raw_width, 3, ifp) < 3) derror(); for (col = 0; col < width; col++) { y = pixel[width * 2 * (row & 1) + col]; cb = pixel[width + (col & -2)] - 128; cr = pixel[width + (col & -2) + 1] - 128; rgb[1] = y - ((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; FORC3 image[row * width + col][c] = curve[LIM(rgb[c], 0, 255)]; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); maximum = curve[0xff]; } void CLASS kodak_262_load_raw() { static const uchar kodak_tree[2][26] = { {0, 1, 5, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 3, 1, 1, 1, 1, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}}; ushort *huff[2]; uchar *pixel; int *strip, ns, c, row, col, chess, pi = 0, pi1, pi2, pred, val; FORC(2) huff[c] = make_decoder(kodak_tree[c]); ns = (raw_height + 63) >> 5; pixel = (uchar *)malloc(raw_width * 32 + ns * 4); merror(pixel, "kodak_262_load_raw()"); strip = (int *)(pixel + raw_width * 32); order = 0x4d4d; FORC(ns) strip[c] = get4(); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif if ((row & 31) == 0) { fseek(ifp, strip[row >> 5], SEEK_SET); getbits(-1); pi = 0; } for (col = 0; col < raw_width; col++) { chess = (row + col) & 1; pi1 = chess ? pi - 2 : pi - raw_width - 1; pi2 = chess ? pi - 2 * raw_width : pi - raw_width + 1; if (col <= chess) pi1 = -1; if (pi1 < 0) pi1 = pi2; if (pi2 < 0) pi2 = pi1; if (pi1 < 0 && col > 1) pi1 = pi2 = pi - 2; pred = (pi1 < 0) ? 0 : (pixel[pi1] + pixel[pi2]) >> 1; pixel[pi] = val = pred + ljpeg_diff(huff[chess]); if (val >> 8) derror(); val = curve[pixel[pi++]]; RAW(row, col) = val; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(pixel); throw; } #endif free(pixel); FORC(2) free(huff[c]); } int CLASS kodak_65000_decode(short *out, int bsize) { uchar c, blen[768]; ushort raw[6]; INT64 bitbuf = 0; int save, bits = 0, i, j, len, diff; save = ftell(ifp); bsize = (bsize + 3) & -4; for (i = 0; i < bsize; i += 2) { c = fgetc(ifp); if ((blen[i] = c & 15) > 12 || (blen[i + 1] = c >> 4) > 12) { fseek(ifp, save, SEEK_SET); for (i = 0; i < bsize; i += 8) { read_shorts(raw, 6); out[i] = raw[0] >> 12 << 8 | raw[2] >> 12 << 4 | raw[4] >> 12; out[i + 1] = raw[1] >> 12 << 8 | raw[3] >> 12 << 4 | raw[5] >> 12; for (j = 0; j < 6; j++) out[i + 2 + j] = raw[j] & 0xfff; } return 1; } } if ((bsize & 7) == 4) { bitbuf = fgetc(ifp) << 8; bitbuf += fgetc(ifp); bits = 16; } for (i = 0; i < bsize; i++) { len = blen[i]; if (bits < len) { for (j = 0; j < 32; j += 8) bitbuf += (INT64)fgetc(ifp) << (bits + (j ^ 8)); bits += 32; } diff = bitbuf & (0xffff >> (16 - len)); bitbuf >>= len; bits -= len; if ((diff & (1 << (len - 1))) == 0) diff -= (1 << len) - 1; out[i] = diff; } return 0; } void CLASS kodak_65000_load_raw() { short buf[272]; /* 264 looks enough */ int row, col, len, pred[2], ret, i; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { pred[0] = pred[1] = 0; len = MIN(256, width - col); ret = kodak_65000_decode(buf, len); for (i = 0; i < len; i++) { int idx = ret ? buf[i] : (pred[i & 1] += buf[i]); if(idx >=0 && idx < 0xffff) { if ((RAW(row, col + i) = curve[idx]) >> 12) derror(); } else derror(); } } } } void CLASS kodak_ycbcr_load_raw() { short buf[384], *bp; int row, col, len, c, i, j, k, y[2][2], cb, cr, rgb[3]; ushort *ip; if (!image) return; unsigned int bits = (load_flags && load_flags > 9 && load_flags < 17) ? load_flags : 10; for (row = 0; row < height; row += 2) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 128) { len = MIN(128, width - col); kodak_65000_decode(buf, len * 3); y[0][1] = y[1][1] = cb = cr = 0; for (bp = buf, i = 0; i < len; i += 2, bp += 2) { cb += bp[4]; cr += bp[5]; rgb[1] = -((cb + cr + 2) >> 2); rgb[2] = rgb[1] + cb; rgb[0] = rgb[1] + cr; for (j = 0; j < 2; j++) for (k = 0; k < 2; k++) { if ((y[j][k] = y[j][k ^ 1] + *bp++) >> bits) derror(); ip = image[(row + j) * width + col + i + k]; FORC3 ip[c] = curve[LIM(y[j][k] + rgb[c], 0, 0xfff)]; } } } } } void CLASS kodak_rgb_load_raw() { short buf[768], *bp; int row, col, len, c, i, rgb[3], ret; ushort *ip = image[0]; for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col += 256) { len = MIN(256, width - col); ret = kodak_65000_decode(buf, len * 3); memset(rgb, 0, sizeof rgb); for (bp = buf, i = 0; i < len; i++, ip += 4) #ifdef LIBRAW_LIBRARY_BUILD if (load_flags == 12) { FORC3 ip[c] = ret ? (*bp++) : (rgb[c] += *bp++); } else #endif FORC3 if ((ip[c] = ret ? (*bp++) : (rgb[c] += *bp++)) >> 12) derror(); } } } void CLASS kodak_thumb_load_raw() { int row, col; colors = thumb_misc >> 5; for (row = 0; row < height; row++) for (col = 0; col < width; col++) read_shorts(image[row * width + col], colors); maximum = (1 << (thumb_misc & 31)) - 1; } void CLASS sony_decrypt(unsigned *data, int len, int start, int key) { #ifndef LIBRAW_NOTHREADS #define pad tls->sony_decrypt.pad #define p tls->sony_decrypt.p #else static unsigned pad[128], p; #endif if (start) { for (p = 0; p < 4; p++) pad[p] = key = key * 48828125 + 1; pad[3] = pad[3] << 1 | (pad[0] ^ pad[2]) >> 31; for (p = 4; p < 127; p++) pad[p] = (pad[p - 4] ^ pad[p - 2]) << 1 | (pad[p - 3] ^ pad[p - 1]) >> 31; for (p = 0; p < 127; p++) pad[p] = htonl(pad[p]); } while (len--) { *data++ ^= pad[p & 127] = pad[(p + 1) & 127] ^ pad[(p + 65) & 127]; p++; } #ifndef LIBRAW_NOTHREADS #undef pad #undef p #endif } void CLASS sony_load_raw() { uchar head[40]; ushort *pixel; unsigned i, key, row, col; fseek(ifp, 200896, SEEK_SET); fseek(ifp, (unsigned)fgetc(ifp) * 4 - 1, SEEK_CUR); order = 0x4d4d; key = get4(); fseek(ifp, 164600, SEEK_SET); fread(head, 1, 40, ifp); sony_decrypt((unsigned *)head, 10, 1, key); for (i = 26; i-- > 22;) key = key << 8 | head[i]; fseek(ifp, data_offset, SEEK_SET); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pixel = raw_image + row * raw_width; if (fread(pixel, 2, raw_width, ifp) < raw_width) derror(); sony_decrypt((unsigned *)pixel, raw_width / 2, !row, key); for (col = 0; col < raw_width; col++) if ((pixel[col] = ntohs(pixel[col])) >> 14) derror(); } maximum = 0x3ff0; } void CLASS sony_arw_load_raw() { ushort huff[32770]; static const ushort tab[18] = {0xf11, 0xf10, 0xe0f, 0xd0e, 0xc0d, 0xb0c, 0xa0b, 0x90a, 0x809, 0x708, 0x607, 0x506, 0x405, 0x304, 0x303, 0x300, 0x202, 0x201}; int i, c, n, col, row, sum = 0; huff[0] = 15; for (n = i = 0; i < 18; i++) FORC(32768 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (col = raw_width; col--;) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (row = 0; row < raw_height + 1; row += 2) { if (row == raw_height) row = 1; if ((sum += ljpeg_diff(huff)) >> 12) derror(); if (row < height) RAW(row, col) = sum; } } } void CLASS sony_arw2_load_raw() { uchar *data, *dp; ushort pix[16]; int row, col, val, max, min, imax, imin, sh, bit, i; data = (uchar *)malloc(raw_width + 1); merror(data, "sony_arw2_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD try { #endif for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fread(data, 1, raw_width, ifp); for (dp = data, col = 0; col < raw_width - 30; dp += 16) { max = 0x7ff & (val = sget4(dp)); min = 0x7ff & val >> 11; imax = 0x0f & val >> 22; imin = 0x0f & val >> 26; for (sh = 0; sh < 4 && 0x80 << sh <= max - min; sh++) ; #ifdef LIBRAW_LIBRARY_BUILD /* flag checks if outside of loop */ if (!(imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_ALLFLAGS) // no flag set || (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE)) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_BASEONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else pix[i] = 0; } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAONLY) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } else if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTAZEROBASE) { for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = 0; else if (i == imin) pix[i] = 0; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh); if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } } #else /* unaltered dcraw processing */ for (bit = 30, i = 0; i < 16; i++) if (i == imax) pix[i] = max; else if (i == imin) pix[i] = min; else { pix[i] = ((sget2(dp + (bit >> 3)) >> (bit & 7) & 0x7f) << sh) + min; if (pix[i] > 0x7ff) pix[i] = 0x7ff; bit += 7; } #endif #ifdef LIBRAW_LIBRARY_BUILD if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) { for (i = 0; i < 16; i++, col += 2) { unsigned slope = pix[i] < 1001 ? 2 : curve[pix[i] << 1] - curve[(pix[i] << 1) - 2]; unsigned step = 1 << sh; RAW(row, col) = curve[pix[i] << 1] > black + imgdata.params.sony_arw2_posterization_thr ? LIM(((slope * step * 1000) / (curve[pix[i] << 1] - black)), 0, 10000) : 0; } } else { for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1]; } #else for (i = 0; i < 16; i++, col += 2) RAW(row, col) = curve[pix[i] << 1] >> 2; #endif col -= col & 1 ? 1 : 31; } } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { free(data); throw; } if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_SONYARW2_DELTATOVALUE) maximum = 10000; #endif free(data); } void CLASS samsung_load_raw() { int row, col, c, i, dir, op[4], len[4]; order = 0x4949; for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, strip_offset + row * 4, SEEK_SET); fseek(ifp, data_offset + get4(), SEEK_SET); ph1_bits(-1); FORC4 len[c] = row < 2 ? 7 : 4; for (col = 0; col < raw_width; col += 16) { dir = ph1_bits(1); FORC4 op[c] = ph1_bits(2); FORC4 switch (op[c]) { case 3: len[c] = ph1_bits(4); break; case 2: len[c]--; break; case 1: len[c]++; } for (c = 0; c < 16; c += 2) { i = len[((c & 1) << 1) | (c >> 3)]; RAW(row, col + c) = ((signed)ph1_bits(i) << (32 - i) >> (32 - i)) + (dir ? RAW(row + (~c | -2), col + c) : col ? RAW(row, col + (c | -2)) : 128); if (c == 14) c = -1; } } } for (row = 0; row < raw_height - 1; row += 2) for (col = 0; col < raw_width - 1; col += 2) SWAP(RAW(row, col + 1), RAW(row + 1, col)); } void CLASS samsung2_load_raw() { static const ushort tab[14] = {0x304, 0x307, 0x206, 0x205, 0x403, 0x600, 0x709, 0x80a, 0x90b, 0xa0c, 0xa0d, 0x501, 0x408, 0x402}; ushort huff[1026], vpred[2][2] = {{0, 0}, {0, 0}}, hpred[2]; int i, c, n, row, col, diff; huff[0] = 10; for (n = i = 0; i < 14; i++) FORC(1024 >> (tab[i] >> 8)) huff[++n] = tab[i]; getbits(-1); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < raw_width; col++) { diff = ljpeg_diff(huff); if (col < 2) hpred[col] = vpred[row & 1][col] += diff; else hpred[col & 1] += diff; RAW(row, col) = hpred[col & 1]; if (hpred[col & 1] >> tiff_bps) derror(); } } } void CLASS samsung3_load_raw() { int opt, init, mag, pmode, row, tab, col, pred, diff, i, c; ushort lent[3][2], len[4], *prow[2]; order = 0x4949; fseek(ifp, 9, SEEK_CUR); opt = fgetc(ifp); init = (get2(), get2()); for (row = 0; row < raw_height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif fseek(ifp, (data_offset - ftell(ifp)) & 15, SEEK_CUR); ph1_bits(-1); mag = 0; pmode = 7; FORC(6)((ushort *)lent)[c] = row < 2 ? 7 : 4; prow[row & 1] = &RAW(row - 1, 1 - ((row & 1) << 1)); // green prow[~row & 1] = &RAW(row - 2, 0); // red and blue for (tab = 0; tab + 15 < raw_width; tab += 16) { if (~opt & 4 && !(tab & 63)) { i = ph1_bits(2); mag = i < 3 ? mag - '2' + "204"[i] : ph1_bits(12); } if (opt & 2) pmode = 7 - 4 * ph1_bits(1); else if (!ph1_bits(1)) pmode = ph1_bits(3); if (opt & 1 || !ph1_bits(1)) { FORC4 len[c] = ph1_bits(2); FORC4 { i = ((row & 1) << 1 | (c & 1)) % 3; len[c] = len[c] < 3 ? lent[i][0] - '1' + "120"[len[c]] : ph1_bits(4); lent[i][0] = lent[i][1]; lent[i][1] = len[c]; } } FORC(16) { col = tab + (((c & 7) << 1) ^ (c >> 3) ^ (row & 1)); pred = (pmode == 7 || row < 2) ? (tab ? RAW(row, tab - 2 + (col & 1)) : init) : (prow[col & 1][col - '4' + "0224468"[pmode]] + prow[col & 1][col - '4' + "0244668"[pmode]] + 1) >> 1; diff = ph1_bits(i = len[c >> 2]); if (diff >> (i - 1)) diff -= 1 << i; diff = diff * (mag * 2 + 1) + mag; RAW(row, col) = pred + diff; } } } } #define HOLE(row) ((holes >> (((row)-raw_height) & 7)) & 1) /* Kudos to Rich Taylor for figuring out SMaL's compression algorithm. */ void CLASS smal_decode_segment(unsigned seg[2][2], int holes) { uchar hist[3][13] = {{7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {7, 7, 0, 0, 63, 55, 47, 39, 31, 23, 15, 7, 0}, {3, 3, 0, 0, 63, 47, 31, 15, 0}}; int low, high = 0xff, carry = 0, nbits = 8; int pix, s, count, bin, next, i, sym[3]; uchar diff, pred[] = {0, 0}; ushort data = 0, range = 0; fseek(ifp, seg[0][1] + 1, SEEK_SET); getbits(-1); if (seg[1][0] > raw_width * raw_height) seg[1][0] = raw_width * raw_height; for (pix = seg[0][0]; pix < seg[1][0]; pix++) { for (s = 0; s < 3; s++) { data = data << nbits | getbits(nbits); if (carry < 0) carry = (nbits += carry + 1) < 1 ? nbits - 1 : 0; while (--nbits >= 0) if ((data >> nbits & 0xff) == 0xff) break; if (nbits > 0) data = ((data & ((1 << (nbits - 1)) - 1)) << 1) | ((data + (((data & (1 << (nbits - 1)))) << 1)) & ((~0u) << nbits)); if (nbits >= 0) { data += getbits(1); carry = nbits - 8; } count = ((((data - range + 1) & 0xffff) << 2) - 1) / (high >> 4); for (bin = 0; hist[s][bin + 5] > count; bin++) ; low = hist[s][bin + 5] * (high >> 4) >> 2; if (bin) high = hist[s][bin + 4] * (high >> 4) >> 2; high -= low; for (nbits = 0; high << nbits < 128; nbits++) ; range = (range + low) << nbits; high <<= nbits; next = hist[s][1]; if (++hist[s][2] > hist[s][3]) { next = (next + 1) & hist[s][0]; hist[s][3] = (hist[s][next + 4] - hist[s][next + 5]) >> 2; hist[s][2] = 1; } if (hist[s][hist[s][1] + 4] - hist[s][hist[s][1] + 5] > 1) { if (bin < hist[s][1]) for (i = bin; i < hist[s][1]; i++) hist[s][i + 5]--; else if (next <= bin) for (i = hist[s][1]; i < bin; i++) hist[s][i + 5]++; } hist[s][1] = next; sym[s] = bin; } diff = sym[2] << 5 | sym[1] << 2 | (sym[0] & 3); if (sym[0] & 4) diff = diff ? -diff : 0x80; if (ftell(ifp) + 12 >= seg[1][1]) diff = 0; #ifdef LIBRAW_LIBRARY_BUILD if (pix >= raw_width * raw_height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif raw_image[pix] = pred[pix & 1] += diff; if (!(pix & 1) && HOLE(pix / raw_width)) pix += 2; } maximum = 0xff; } void CLASS smal_v6_load_raw() { unsigned seg[2][2]; fseek(ifp, 16, SEEK_SET); seg[0][0] = 0; seg[0][1] = get2(); seg[1][0] = raw_width * raw_height; seg[1][1] = INT_MAX; smal_decode_segment(seg, 0); } int CLASS median4(int *p) { int min, max, sum, i; min = max = sum = p[0]; for (i = 1; i < 4; i++) { sum += p[i]; if (min > p[i]) min = p[i]; if (max < p[i]) max = p[i]; } return (sum - min - max) >> 1; } void CLASS fill_holes(int holes) { int row, col, val[4]; for (row = 2; row < height - 2; row++) { if (!HOLE(row)) continue; for (col = 1; col < width - 1; col += 4) { val[0] = RAW(row - 1, col - 1); val[1] = RAW(row - 1, col + 1); val[2] = RAW(row + 1, col - 1); val[3] = RAW(row + 1, col + 1); RAW(row, col) = median4(val); } for (col = 2; col < width - 2; col += 4) if (HOLE(row - 2) || HOLE(row + 2)) RAW(row, col) = (RAW(row, col - 2) + RAW(row, col + 2)) >> 1; else { val[0] = RAW(row, col - 2); val[1] = RAW(row, col + 2); val[2] = RAW(row - 2, col); val[3] = RAW(row + 2, col); RAW(row, col) = median4(val); } } } void CLASS smal_v9_load_raw() { unsigned seg[256][2], offset, nseg, holes, i; fseek(ifp, 67, SEEK_SET); offset = get4(); nseg = (uchar)fgetc(ifp); fseek(ifp, offset, SEEK_SET); for (i = 0; i < nseg * 2; i++) ((unsigned *)seg)[i] = get4() + data_offset * (i & 1); fseek(ifp, 78, SEEK_SET); holes = fgetc(ifp); fseek(ifp, 88, SEEK_SET); seg[nseg][0] = raw_height * raw_width; seg[nseg][1] = get4() + data_offset; for (i = 0; i < nseg; i++) smal_decode_segment(seg + i, holes); if (holes) fill_holes(holes); } void CLASS redcine_load_raw() { #ifndef NO_JASPER int c, row, col; jas_stream_t *in; jas_image_t *jimg; jas_matrix_t *jmat; jas_seqent_t *data; ushort *img, *pix; jas_init(); #ifndef LIBRAW_LIBRARY_BUILD in = jas_stream_fopen(ifname, "rb"); #else in = (jas_stream_t *)ifp->make_jas_stream(); if (!in) throw LIBRAW_EXCEPTION_DECODE_JPEG2000; #endif jas_stream_seek(in, data_offset + 20, SEEK_SET); jimg = jas_image_decode(in, -1, 0); #ifndef LIBRAW_LIBRARY_BUILD if (!jimg) longjmp(failure, 3); #else if (!jimg) { jas_stream_close(in); throw LIBRAW_EXCEPTION_DECODE_JPEG2000; } #endif jmat = jas_matrix_create(height / 2, width / 2); merror(jmat, "redcine_load_raw()"); img = (ushort *)calloc((height + 2), (width + 2) * 2); merror(img, "redcine_load_raw()"); #ifdef LIBRAW_LIBRARY_BUILD bool fastexitflag = false; try { #endif FORC4 { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif jas_image_readcmpt(jimg, c, 0, 0, width / 2, height / 2, jmat); data = jas_matrix_getref(jmat, 0, 0); for (row = c >> 1; row < height; row += 2) for (col = c & 1; col < width; col += 2) img[(row + 1) * (width + 2) + col + 1] = data[(row / 2) * (width / 2) + col / 2]; } for (col = 1; col <= width; col++) { img[col] = img[2 * (width + 2) + col]; img[(height + 1) * (width + 2) + col] = img[(height - 1) * (width + 2) + col]; } for (row = 0; row < height + 2; row++) { img[row * (width + 2)] = img[row * (width + 2) + 2]; img[(row + 1) * (width + 2) - 1] = img[(row + 1) * (width + 2) - 3]; } for (row = 1; row <= height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif pix = img + row * (width + 2) + (col = 1 + (FC(row, 1) & 1)); for (; col <= width; col += 2, pix += 2) { c = (((pix[0] - 0x800) << 3) + pix[-(width + 2)] + pix[width + 2] + pix[-1] + pix[1]) >> 2; pix[0] = LIM(c, 0, 4095); } } for (row = 0; row < height; row++) { #ifdef LIBRAW_LIBRARY_BUILD checkCancel(); #endif for (col = 0; col < width; col++) RAW(row, col) = curve[img[(row + 1) * (width + 2) + col + 1]]; } #ifdef LIBRAW_LIBRARY_BUILD } catch (...) { fastexitflag = true; } #endif free(img); jas_matrix_destroy(jmat); jas_image_destroy(jimg); jas_stream_close(in); #ifdef LIBRAW_LIBRARY_BUILD if (fastexitflag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif #endif } void CLASS crop_masked_pixels() { int row, col; unsigned #ifndef LIBRAW_LIBRARY_BUILD r, raw_pitch = raw_width * 2, c, m, mblack[8], zero, val; #else c, m, zero, val; #define mblack imgdata.color.black_stat #endif #ifndef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS phase_one_load_raw || load_raw == &CLASS phase_one_load_raw_c) phase_one_correct(); if (fuji_width) { for (row = 0; row < raw_height - top_margin * 2; row++) { for (col = 0; col < fuji_width << !fuji_layout; col++) { if (fuji_layout) { r = fuji_width - 1 - col + (row >> 1); c = col + ((row + 1) >> 1); } else { r = fuji_width - 1 + row - (col >> 1); c = row + ((col + 1) >> 1); } if (r < height && c < width) BAYER(r, c) = RAW(row + top_margin, col + left_margin); } } } else { for (row = 0; row < height; row++) for (col = 0; col < width; col++) BAYER2(row, col) = RAW(row + top_margin, col + left_margin); } #endif if (mask[0][3] > 0) goto mask_set; if (load_raw == &CLASS canon_load_raw || load_raw == &CLASS lossless_jpeg_load_raw) { mask[0][1] = mask[1][1] += 2; mask[0][3] -= 2; goto sides; } if (load_raw == &CLASS canon_600_load_raw || load_raw == &CLASS sony_load_raw || (load_raw == &CLASS eight_bit_load_raw && strncmp(model, "DC2", 3)) || load_raw == &CLASS kodak_262_load_raw || (load_raw == &CLASS packed_load_raw && (load_flags & 32))) { sides: mask[0][0] = mask[1][0] = top_margin; mask[0][2] = mask[1][2] = top_margin + height; mask[0][3] += left_margin; mask[1][1] += left_margin + width; mask[1][3] += raw_width; } if (load_raw == &CLASS nokia_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &CLASS broadcom_load_raw) { mask[0][2] = top_margin; mask[0][3] = width; } #endif mask_set: memset(mblack, 0, sizeof mblack); for (zero = m = 0; m < 8; m++) for (row = MAX(mask[m][0], 0); row < MIN(mask[m][2], raw_height); row++) for (col = MAX(mask[m][1], 0); col < MIN(mask[m][3], raw_width); col++) { c = FC(row - top_margin, col - left_margin); mblack[c] += val = raw_image[(row)*raw_pitch / 2 + (col)]; mblack[4 + c]++; zero += !val; } if (load_raw == &CLASS canon_600_load_raw && width < raw_width) { black = (mblack[0] + mblack[1] + mblack[2] + mblack[3]) / (mblack[4] + mblack[5] + mblack[6] + mblack[7]) - 4; #ifndef LIBRAW_LIBRARY_BUILD canon_600_correct(); #endif } else if (zero < mblack[4] && mblack[5] && mblack[6] && mblack[7]) { FORC4 cblack[c] = mblack[c] / mblack[4 + c]; black = cblack[4] = cblack[5] = cblack[6] = 0; } } #ifdef LIBRAW_LIBRARY_BUILD #undef mblack #endif void CLASS remove_zeroes() { unsigned row, col, tot, n, r, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 0, 2); #endif for (row = 0; row < height; row++) for (col = 0; col < width; col++) if (BAYER(row, col) == 0) { tot = n = 0; for (r = row - 2; r <= row + 2; r++) for (c = col - 2; c <= col + 2; c++) if (r < height && c < width && FC(r, c) == FC(row, col) && BAYER(r, c)) tot += (n++, BAYER(r, c)); if (n) BAYER(row, col) = tot / n; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_REMOVE_ZEROES, 1, 2); #endif } static const uchar xlat[2][256] = { {0xc1, 0xbf, 0x6d, 0x0d, 0x59, 0xc5, 0x13, 0x9d, 0x83, 0x61, 0x6b, 0x4f, 0xc7, 0x7f, 0x3d, 0x3d, 0x53, 0x59, 0xe3, 0xc7, 0xe9, 0x2f, 0x95, 0xa7, 0x95, 0x1f, 0xdf, 0x7f, 0x2b, 0x29, 0xc7, 0x0d, 0xdf, 0x07, 0xef, 0x71, 0x89, 0x3d, 0x13, 0x3d, 0x3b, 0x13, 0xfb, 0x0d, 0x89, 0xc1, 0x65, 0x1f, 0xb3, 0x0d, 0x6b, 0x29, 0xe3, 0xfb, 0xef, 0xa3, 0x6b, 0x47, 0x7f, 0x95, 0x35, 0xa7, 0x47, 0x4f, 0xc7, 0xf1, 0x59, 0x95, 0x35, 0x11, 0x29, 0x61, 0xf1, 0x3d, 0xb3, 0x2b, 0x0d, 0x43, 0x89, 0xc1, 0x9d, 0x9d, 0x89, 0x65, 0xf1, 0xe9, 0xdf, 0xbf, 0x3d, 0x7f, 0x53, 0x97, 0xe5, 0xe9, 0x95, 0x17, 0x1d, 0x3d, 0x8b, 0xfb, 0xc7, 0xe3, 0x67, 0xa7, 0x07, 0xf1, 0x71, 0xa7, 0x53, 0xb5, 0x29, 0x89, 0xe5, 0x2b, 0xa7, 0x17, 0x29, 0xe9, 0x4f, 0xc5, 0x65, 0x6d, 0x6b, 0xef, 0x0d, 0x89, 0x49, 0x2f, 0xb3, 0x43, 0x53, 0x65, 0x1d, 0x49, 0xa3, 0x13, 0x89, 0x59, 0xef, 0x6b, 0xef, 0x65, 0x1d, 0x0b, 0x59, 0x13, 0xe3, 0x4f, 0x9d, 0xb3, 0x29, 0x43, 0x2b, 0x07, 0x1d, 0x95, 0x59, 0x59, 0x47, 0xfb, 0xe5, 0xe9, 0x61, 0x47, 0x2f, 0x35, 0x7f, 0x17, 0x7f, 0xef, 0x7f, 0x95, 0x95, 0x71, 0xd3, 0xa3, 0x0b, 0x71, 0xa3, 0xad, 0x0b, 0x3b, 0xb5, 0xfb, 0xa3, 0xbf, 0x4f, 0x83, 0x1d, 0xad, 0xe9, 0x2f, 0x71, 0x65, 0xa3, 0xe5, 0x07, 0x35, 0x3d, 0x0d, 0xb5, 0xe9, 0xe5, 0x47, 0x3b, 0x9d, 0xef, 0x35, 0xa3, 0xbf, 0xb3, 0xdf, 0x53, 0xd3, 0x97, 0x53, 0x49, 0x71, 0x07, 0x35, 0x61, 0x71, 0x2f, 0x43, 0x2f, 0x11, 0xdf, 0x17, 0x97, 0xfb, 0x95, 0x3b, 0x7f, 0x6b, 0xd3, 0x25, 0xbf, 0xad, 0xc7, 0xc5, 0xc5, 0xb5, 0x8b, 0xef, 0x2f, 0xd3, 0x07, 0x6b, 0x25, 0x49, 0x95, 0x25, 0x49, 0x6d, 0x71, 0xc7}, {0xa7, 0xbc, 0xc9, 0xad, 0x91, 0xdf, 0x85, 0xe5, 0xd4, 0x78, 0xd5, 0x17, 0x46, 0x7c, 0x29, 0x4c, 0x4d, 0x03, 0xe9, 0x25, 0x68, 0x11, 0x86, 0xb3, 0xbd, 0xf7, 0x6f, 0x61, 0x22, 0xa2, 0x26, 0x34, 0x2a, 0xbe, 0x1e, 0x46, 0x14, 0x68, 0x9d, 0x44, 0x18, 0xc2, 0x40, 0xf4, 0x7e, 0x5f, 0x1b, 0xad, 0x0b, 0x94, 0xb6, 0x67, 0xb4, 0x0b, 0xe1, 0xea, 0x95, 0x9c, 0x66, 0xdc, 0xe7, 0x5d, 0x6c, 0x05, 0xda, 0xd5, 0xdf, 0x7a, 0xef, 0xf6, 0xdb, 0x1f, 0x82, 0x4c, 0xc0, 0x68, 0x47, 0xa1, 0xbd, 0xee, 0x39, 0x50, 0x56, 0x4a, 0xdd, 0xdf, 0xa5, 0xf8, 0xc6, 0xda, 0xca, 0x90, 0xca, 0x01, 0x42, 0x9d, 0x8b, 0x0c, 0x73, 0x43, 0x75, 0x05, 0x94, 0xde, 0x24, 0xb3, 0x80, 0x34, 0xe5, 0x2c, 0xdc, 0x9b, 0x3f, 0xca, 0x33, 0x45, 0xd0, 0xdb, 0x5f, 0xf5, 0x52, 0xc3, 0x21, 0xda, 0xe2, 0x22, 0x72, 0x6b, 0x3e, 0xd0, 0x5b, 0xa8, 0x87, 0x8c, 0x06, 0x5d, 0x0f, 0xdd, 0x09, 0x19, 0x93, 0xd0, 0xb9, 0xfc, 0x8b, 0x0f, 0x84, 0x60, 0x33, 0x1c, 0x9b, 0x45, 0xf1, 0xf0, 0xa3, 0x94, 0x3a, 0x12, 0x77, 0x33, 0x4d, 0x44, 0x78, 0x28, 0x3c, 0x9e, 0xfd, 0x65, 0x57, 0x16, 0x94, 0x6b, 0xfb, 0x59, 0xd0, 0xc8, 0x22, 0x36, 0xdb, 0xd2, 0x63, 0x98, 0x43, 0xa1, 0x04, 0x87, 0x86, 0xf7, 0xa6, 0x26, 0xbb, 0xd6, 0x59, 0x4d, 0xbf, 0x6a, 0x2e, 0xaa, 0x2b, 0xef, 0xe6, 0x78, 0xb6, 0x4e, 0xe0, 0x2f, 0xdc, 0x7c, 0xbe, 0x57, 0x19, 0x32, 0x7e, 0x2a, 0xd0, 0xb8, 0xba, 0x29, 0x00, 0x3c, 0x52, 0x7d, 0xa8, 0x49, 0x3b, 0x2d, 0xeb, 0x25, 0x49, 0xfa, 0xa3, 0xaa, 0x39, 0xa7, 0xc5, 0xa7, 0x50, 0x11, 0x36, 0xfb, 0xc6, 0x67, 0x4a, 0xf5, 0xa5, 0x12, 0x65, 0x7e, 0xb0, 0xdf, 0xaf, 0x4e, 0xb3, 0x61, 0x7f, 0x2f}}; void CLASS gamma_curve(double pwr, double ts, int mode, int imax) { int i; double g[6], bnd[2] = {0, 0}, r; g[0] = pwr; g[1] = ts; g[2] = g[3] = g[4] = 0; bnd[g[1] >= 1] = 1; if (g[1] && (g[1] - 1) * (g[0] - 1) <= 0) { for (i = 0; i < 48; i++) { g[2] = (bnd[0] + bnd[1]) / 2; if (g[0]) bnd[(pow(g[2] / g[1], -g[0]) - 1) / g[0] - 1 / g[2] > -1] = g[2]; else bnd[g[2] / exp(1 - 1 / g[2]) < g[1]] = g[2]; } g[3] = g[2] / g[1]; if (g[0]) g[4] = g[2] * (1 / g[0] - 1); } if (g[0]) g[5] = 1 / (g[1] * SQR(g[3]) / 2 - g[4] * (1 - g[3]) + (1 - pow(g[3], 1 + g[0])) * (1 + g[4]) / (1 + g[0])) - 1; else g[5] = 1 / (g[1] * SQR(g[3]) / 2 + 1 - g[2] - g[3] - g[2] * g[3] * (log(g[3]) - 1)) - 1; if (!mode--) { memcpy(gamm, g, sizeof gamm); return; } for (i = 0; i < 0x10000; i++) { curve[i] = 0xffff; if ((r = (double)i / imax) < 1) curve[i] = 0x10000 * (mode ? (r < g[3] ? r * g[1] : (g[0] ? pow(r, g[0]) * (1 + g[4]) - g[4] : log(r) * g[2] + 1)) : (r < g[2] ? r / g[1] : (g[0] ? pow((r + g[4]) / (1 + g[4]), 1 / g[0]) : exp((r - 1) / g[2])))); } } void CLASS pseudoinverse(double (*in)[3], double (*out)[3], int size) { double work[3][6], num; int i, j, k; for (i = 0; i < 3; i++) { for (j = 0; j < 6; j++) work[i][j] = j == i + 3; for (j = 0; j < 3; j++) for (k = 0; k < size; k++) work[i][j] += in[k][i] * in[k][j]; } for (i = 0; i < 3; i++) { num = work[i][i]; for (j = 0; j < 6; j++) work[i][j] /= num; for (k = 0; k < 3; k++) { if (k == i) continue; num = work[k][i]; for (j = 0; j < 6; j++) work[k][j] -= work[i][j] * num; } } for (i = 0; i < size; i++) for (j = 0; j < 3; j++) for (out[i][j] = k = 0; k < 3; k++) out[i][j] += work[j][k + 3] * in[i][k]; } void CLASS cam_xyz_coeff(float _rgb_cam[3][4], double cam_xyz[4][3]) { double cam_rgb[4][3], inverse[4][3], num; int i, j, k; for (i = 0; i < colors; i++) /* Multiply out XYZ colorspace */ for (j = 0; j < 3; j++) for (cam_rgb[i][j] = k = 0; k < 3; k++) cam_rgb[i][j] += cam_xyz[i][k] * xyz_rgb[k][j]; for (i = 0; i < colors; i++) { /* Normalize cam_rgb so that */ for (num = j = 0; j < 3; j++) /* cam_rgb * (1,1,1) is (1,1,1,1) */ num += cam_rgb[i][j]; if (num > 0.00001) { for (j = 0; j < 3; j++) cam_rgb[i][j] /= num; pre_mul[i] = 1 / num; } else { for (j = 0; j < 3; j++) cam_rgb[i][j] = 0.0; pre_mul[i] = 1.0; } } pseudoinverse(cam_rgb, inverse, colors); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) _rgb_cam[i][j] = inverse[j][i]; } #ifdef COLORCHECK void CLASS colorcheck() { #define NSQ 24 // Coordinates of the GretagMacbeth ColorChecker squares // width, height, 1st_column, 1st_row int cut[NSQ][4]; // you must set these // ColorChecker Chart under 6500-kelvin illumination static const double gmb_xyY[NSQ][3] = {{0.400, 0.350, 10.1}, // Dark Skin {0.377, 0.345, 35.8}, // Light Skin {0.247, 0.251, 19.3}, // Blue Sky {0.337, 0.422, 13.3}, // Foliage {0.265, 0.240, 24.3}, // Blue Flower {0.261, 0.343, 43.1}, // Bluish Green {0.506, 0.407, 30.1}, // Orange {0.211, 0.175, 12.0}, // Purplish Blue {0.453, 0.306, 19.8}, // Moderate Red {0.285, 0.202, 6.6}, // Purple {0.380, 0.489, 44.3}, // Yellow Green {0.473, 0.438, 43.1}, // Orange Yellow {0.187, 0.129, 6.1}, // Blue {0.305, 0.478, 23.4}, // Green {0.539, 0.313, 12.0}, // Red {0.448, 0.470, 59.1}, // Yellow {0.364, 0.233, 19.8}, // Magenta {0.196, 0.252, 19.8}, // Cyan {0.310, 0.316, 90.0}, // White {0.310, 0.316, 59.1}, // Neutral 8 {0.310, 0.316, 36.2}, // Neutral 6.5 {0.310, 0.316, 19.8}, // Neutral 5 {0.310, 0.316, 9.0}, // Neutral 3.5 {0.310, 0.316, 3.1}}; // Black double gmb_cam[NSQ][4], gmb_xyz[NSQ][3]; double inverse[NSQ][3], cam_xyz[4][3], balance[4], num; int c, i, j, k, sq, row, col, pass, count[4]; memset(gmb_cam, 0, sizeof gmb_cam); for (sq = 0; sq < NSQ; sq++) { FORCC count[c] = 0; for (row = cut[sq][3]; row < cut[sq][3] + cut[sq][1]; row++) for (col = cut[sq][2]; col < cut[sq][2] + cut[sq][0]; col++) { c = FC(row, col); if (c >= colors) c -= 2; gmb_cam[sq][c] += BAYER2(row, col); BAYER2(row, col) = black + (BAYER2(row, col) - black) / 2; count[c]++; } FORCC gmb_cam[sq][c] = gmb_cam[sq][c] / count[c] - black; gmb_xyz[sq][0] = gmb_xyY[sq][2] * gmb_xyY[sq][0] / gmb_xyY[sq][1]; gmb_xyz[sq][1] = gmb_xyY[sq][2]; gmb_xyz[sq][2] = gmb_xyY[sq][2] * (1 - gmb_xyY[sq][0] - gmb_xyY[sq][1]) / gmb_xyY[sq][1]; } pseudoinverse(gmb_xyz, inverse, NSQ); for (pass = 0; pass < 2; pass++) { for (raw_color = i = 0; i < colors; i++) for (j = 0; j < 3; j++) for (cam_xyz[i][j] = k = 0; k < NSQ; k++) cam_xyz[i][j] += gmb_cam[k][i] * inverse[k][j]; cam_xyz_coeff(rgb_cam, cam_xyz); FORCC balance[c] = pre_mul[c] * gmb_cam[20][c]; for (sq = 0; sq < NSQ; sq++) FORCC gmb_cam[sq][c] *= balance[c]; } if (verbose) { printf(" { \"%s %s\", %d,\n\t{", make, model, black); num = 10000 / (cam_xyz[1][0] + cam_xyz[1][1] + cam_xyz[1][2]); FORCC for (j = 0; j < 3; j++) printf("%c%d", (c | j) ? ',' : ' ', (int)(cam_xyz[c][j] * num + 0.5)); puts(" } },"); } #undef NSQ } #endif void CLASS hat_transform(float *temp, float *base, int st, int size, int sc) { int i; for (i = 0; i < sc; i++) temp[i] = 2 * base[st * i] + base[st * (sc - i)] + base[st * (i + sc)]; for (; i + sc < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (i + sc)]; for (; i < size; i++) temp[i] = 2 * base[st * i] + base[st * (i - sc)] + base[st * (2 * size - 2 - (i + sc))]; } #if !defined(LIBRAW_USE_OPENMP) void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; FORC(nc) { /* denoise R,G1,B,G3 individually */ for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #else /* LIBRAW_USE_OPENMP */ void CLASS wavelet_denoise() { float *fimg = 0, *temp, thold, mul[2], avg, diff; int scale = 1, size, lev, hpass, lpass, row, col, nc, c, i, wlast, blk[2]; ushort *window[4]; static const float noise[] = {0.8002, 0.2735, 0.1202, 0.0585, 0.0291, 0.0152, 0.0080, 0.0044}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Wavelet denoising...\n")); #endif while (maximum << scale < 0x10000) scale++; maximum <<= --scale; black <<= scale; FORC4 cblack[c] <<= scale; if ((size = iheight * iwidth) < 0x15550000) fimg = (float *)malloc((size * 3 + iheight + iwidth) * sizeof *fimg); merror(fimg, "wavelet_denoise()"); temp = fimg + size * 3; if ((nc = colors) == 3 && filters) nc++; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp parallel default(shared) private(i, col, row, thold, lev, lpass, hpass, temp, c) firstprivate(scale, size) #endif { temp = (float *)malloc((iheight + iwidth) * sizeof *fimg); FORC(nc) { /* denoise R,G1,B,G3 individually */ #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) fimg[i] = 256 * sqrt((double)(image[i][c] << scale)); for (hpass = lev = 0; lev < 5; lev++) { lpass = size * ((lev & 1) + 1); #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (row = 0; row < iheight; row++) { hat_transform(temp, fimg + hpass + row * iwidth, 1, iwidth, 1 << lev); for (col = 0; col < iwidth; col++) fimg[lpass + row * iwidth + col] = temp[col] * 0.25; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (col = 0; col < iwidth; col++) { hat_transform(temp, fimg + lpass + col, iwidth, iheight, 1 << lev); for (row = 0; row < iheight; row++) fimg[lpass + row * iwidth + col] = temp[row] * 0.25; } thold = threshold * noise[lev]; #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) { fimg[hpass + i] -= fimg[lpass + i]; if (fimg[hpass + i] < -thold) fimg[hpass + i] += thold; else if (fimg[hpass + i] > thold) fimg[hpass + i] -= thold; else fimg[hpass + i] = 0; if (hpass) fimg[i] += fimg[hpass + i]; } hpass = lpass; } #ifdef LIBRAW_LIBRARY_BUILD #pragma omp for #endif for (i = 0; i < size; i++) image[i][c] = CLIP(SQR(fimg[i] + fimg[lpass + i]) / 0x10000); } free(temp); } /* end omp parallel */ /* the following loops are hard to parallize, no idea yes, * problem is wlast which is carrying dependency * second part should be easyer, but did not yet get it right. */ if (filters && colors == 3) { /* pull G1 and G3 closer together */ for (row = 0; row < 2; row++) { mul[row] = 0.125 * pre_mul[FC(row + 1, 0) | 1] / pre_mul[FC(row, 0) | 1]; blk[row] = cblack[FC(row, 0) | 1]; } for (i = 0; i < 4; i++) window[i] = (ushort *)fimg + width * i; for (wlast = -1, row = 1; row < height - 1; row++) { while (wlast < row + 1) { for (wlast++, i = 0; i < 4; i++) window[(i + 3) & 3] = window[i]; for (col = FC(wlast, 1) & 1; col < width; col += 2) window[2][col] = BAYER(wlast, col); } thold = threshold / 512; for (col = (FC(row, 0) & 1) + 1; col < width - 1; col += 2) { avg = (window[0][col - 1] + window[0][col + 1] + window[2][col - 1] + window[2][col + 1] - blk[~row & 1] * 4) * mul[row & 1] + (window[1][col] + blk[row & 1]) * 0.5; avg = avg < 0 ? 0 : sqrt(avg); diff = sqrt((double)BAYER(row, col)) - avg; if (diff < -thold) diff += thold; else if (diff > thold) diff -= thold; else diff = 0; BAYER(row, col) = CLIP(SQR(avg + diff) + 0.5); } } } free(fimg); } #endif // green equilibration void CLASS green_matching() { int i, j; double m1, m2, c1, c2; int o1_1, o1_2, o1_3, o1_4; int o2_1, o2_2, o2_3, o2_4; ushort(*img)[4]; const int margin = 3; int oj = 2, oi = 2; float f; const float thr = 0.01f; if (half_size || shrink) return; if (FC(oj, oi) != 3) oj++; if (FC(oj, oi) != 3) oi++; if (FC(oj, oi) != 3) oj--; img = (ushort(*)[4])calloc(height * width, sizeof *image); merror(img, "green_matching()"); memcpy(img, image, height * width * sizeof *image); for (j = oj; j < height - margin; j += 2) for (i = oi; i < width - margin; i += 2) { o1_1 = img[(j - 1) * width + i - 1][1]; o1_2 = img[(j - 1) * width + i + 1][1]; o1_3 = img[(j + 1) * width + i - 1][1]; o1_4 = img[(j + 1) * width + i + 1][1]; o2_1 = img[(j - 2) * width + i][3]; o2_2 = img[(j + 2) * width + i][3]; o2_3 = img[j * width + i - 2][3]; o2_4 = img[j * width + i + 2][3]; m1 = (o1_1 + o1_2 + o1_3 + o1_4) / 4.0; m2 = (o2_1 + o2_2 + o2_3 + o2_4) / 4.0; c1 = (abs(o1_1 - o1_2) + abs(o1_1 - o1_3) + abs(o1_1 - o1_4) + abs(o1_2 - o1_3) + abs(o1_3 - o1_4) + abs(o1_2 - o1_4)) / 6.0; c2 = (abs(o2_1 - o2_2) + abs(o2_1 - o2_3) + abs(o2_1 - o2_4) + abs(o2_2 - o2_3) + abs(o2_3 - o2_4) + abs(o2_2 - o2_4)) / 6.0; if ((img[j * width + i][3] < maximum * 0.95) && (c1 < maximum * thr) && (c2 < maximum * thr)) { f = image[j * width + i][3] * m1 / m2; image[j * width + i][3] = f > 0xffff ? 0xffff : f; } } free(img); } void CLASS scale_colors() { unsigned bottom, right, size, row, col, ur, uc, i, x, y, c, sum[8]; int val, dark, sat; double dsum[8], dmin, dmax; float scale_mul[4], fr, fc; ushort *img = 0, *pix; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 0, 2); #endif if (user_mul[0]) memcpy(pre_mul, user_mul, sizeof pre_mul); if (use_auto_wb || (use_camera_wb && cam_mul[0] == -1)) { memset(dsum, 0, sizeof dsum); bottom = MIN(greybox[1] + greybox[3], height); right = MIN(greybox[0] + greybox[2], width); for (row = greybox[1]; row < bottom; row += 8) for (col = greybox[0]; col < right; col += 8) { memset(sum, 0, sizeof sum); for (y = row; y < row + 8 && y < bottom; y++) for (x = col; x < col + 8 && x < right; x++) FORC4 { if (filters) { c = fcol(y, x); val = BAYER2(y, x); } else val = image[y * width + x][c]; if (val > maximum - 25) goto skip_block; if ((val -= cblack[c]) < 0) val = 0; sum[c] += val; sum[c + 4]++; if (filters) break; } FORC(8) dsum[c] += sum[c]; skip_block:; } FORC4 if (dsum[c]) pre_mul[c] = dsum[c + 4] / dsum[c]; } if (use_camera_wb && cam_mul[0] != -1) { memset(sum, 0, sizeof sum); for (row = 0; row < 8; row++) for (col = 0; col < 8; col++) { c = FC(row, col); if ((val = white[row][col] - cblack[c]) > 0) sum[c] += val; sum[c + 4]++; } #ifdef LIBRAW_LIBRARY_BUILD if (load_raw == &LibRaw::nikon_load_sraw) { // Nikon sRAW: camera WB already applied: pre_mul[0] = pre_mul[1] = pre_mul[2] = pre_mul[3] = 1.0; } else #endif if (sum[0] && sum[1] && sum[2] && sum[3]) FORC4 pre_mul[c] = (float)sum[c + 4] / sum[c]; else if (cam_mul[0] && cam_mul[2]) memcpy(pre_mul, cam_mul, sizeof pre_mul); else { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_BAD_CAMERA_WB; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Cannot use camera white balance.\n"), ifname); #endif } } #ifdef LIBRAW_LIBRARY_BUILD // Nikon sRAW, daylight if (load_raw == &LibRaw::nikon_load_sraw && !use_camera_wb && !use_auto_wb && cam_mul[0] > 0.001f && cam_mul[1] > 0.001f && cam_mul[2] > 0.001f) { for (c = 0; c < 3; c++) pre_mul[c] /= cam_mul[c]; } #endif if (pre_mul[1] == 0) pre_mul[1] = 1; if (pre_mul[3] == 0) pre_mul[3] = colors < 4 ? pre_mul[1] : 1; dark = black; sat = maximum; if (threshold) wavelet_denoise(); maximum -= black; for (dmin = DBL_MAX, dmax = c = 0; c < 4; c++) { if (dmin > pre_mul[c]) dmin = pre_mul[c]; if (dmax < pre_mul[c]) dmax = pre_mul[c]; } if (!highlight) dmax = dmin; FORC4 scale_mul[c] = (pre_mul[c] /= dmax) * 65535.0 / maximum; #ifdef DCRAW_VERBOSE if (verbose) { fprintf(stderr, _("Scaling with darkness %d, saturation %d, and\nmultipliers"), dark, sat); FORC4 fprintf(stderr, " %f", pre_mul[c]); fputc('\n', stderr); } #endif if (filters > 1000 && (cblack[4] + 1) / 2 == 1 && (cblack[5] + 1) / 2 == 1) { FORC4 cblack[FC(c / 2, c % 2)] += cblack[6 + c / 2 % cblack[4] * cblack[5] + c % 2 % cblack[5]]; cblack[4] = cblack[5] = 0; } size = iheight * iwidth; #ifdef LIBRAW_LIBRARY_BUILD scale_colors_loop(scale_mul); #else for (i = 0; i < size * 4; i++) { if (!(val = ((ushort *)image)[i])) continue; if (cblack[4] && cblack[5]) val -= cblack[6 + i / 4 / iwidth % cblack[4] * cblack[5] + i / 4 % iwidth % cblack[5]]; val -= cblack[i & 3]; val *= scale_mul[i & 3]; ((ushort *)image)[i] = CLIP(val); } #endif if ((aber[0] != 1 || aber[2] != 1) && colors == 3) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Correcting chromatic aberration...\n")); #endif for (c = 0; c < 4; c += 2) { if (aber[c] == 1) continue; img = (ushort *)malloc(size * sizeof *img); merror(img, "scale_colors()"); for (i = 0; i < size; i++) img[i] = image[i][c]; for (row = 0; row < iheight; row++) { ur = fr = (row - iheight * 0.5) * aber[c] + iheight * 0.5; if (ur > iheight - 2) continue; fr -= ur; for (col = 0; col < iwidth; col++) { uc = fc = (col - iwidth * 0.5) * aber[c] + iwidth * 0.5; if (uc > iwidth - 2) continue; fc -= uc; pix = img + ur * iwidth + uc; image[row * iwidth + col][c] = (pix[0] * (1 - fc) + pix[1] * fc) * (1 - fr) + (pix[iwidth] * (1 - fc) + pix[iwidth + 1] * fc) * fr; } } free(img); } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_SCALE_COLORS, 1, 2); #endif } void CLASS pre_interpolate() { ushort(*img)[4]; int row, col, c; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 0, 2); #endif if (shrink) { if (half_size) { height = iheight; width = iwidth; if (filters == 9) { for (row = 0; row < 3; row++) for (col = 1; col < 4; col++) if (!(image[row * width + col][0] | image[row * width + col][2])) goto break2; break2: for (; row < height; row += 3) for (col = (col - 1) % 3 + 1; col < width - 1; col += 3) { img = image + row * width + col; for (c = 0; c < 3; c += 2) img[0][c] = (img[-1][c] + img[1][c]) >> 1; } } } else { img = (ushort(*)[4])calloc(height, width * sizeof *img); merror(img, "pre_interpolate()"); for (row = 0; row < height; row++) for (col = 0; col < width; col++) { c = fcol(row, col); img[row * width + col][c] = image[(row >> 1) * iwidth + (col >> 1)][c]; } free(image); image = img; shrink = 0; } } if (filters > 1000 && colors == 3) { mix_green = four_color_rgb ^ half_size; if (four_color_rgb | half_size) colors++; else { for (row = FC(1, 0) >> 1; row < height; row += 2) for (col = FC(row, 1) & 1; col < width; col += 2) image[row * width + col][1] = image[row * width + col][3]; filters &= ~((filters & 0x55555555) << 1); } } if (half_size) filters = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_PRE_INTERPOLATE, 1, 2); #endif } void CLASS border_interpolate(int border) { unsigned row, col, y, x, f, c, sum[8]; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { if (col == border && row >= border && row < height - border) col = width - border; memset(sum, 0, sizeof sum); for (y = row - 1; y != row + 2; y++) for (x = col - 1; x != col + 2; x++) if (y < height && x < width) { f = fcol(y, x); sum[f] += image[y * width + x][f]; sum[f + 4]++; } f = fcol(row, col); FORCC if (c != f && sum[c + 4]) image[row * width + col][c] = sum[c] / sum[c + 4]; } } void CLASS lin_interpolate_loop(int code[16][16][32], int size) { int row; for (row = 1; row < height - 1; row++) { int col, *ip; ushort *pix; for (col = 1; col < width - 1; col++) { int i; int sum[4]; pix = image[row * width + col]; ip = code[row % size][col % size]; memset(sum, 0, sizeof sum); for (i = *ip++; i--; ip += 3) sum[ip[2]] += pix[ip[0]] << ip[1]; for (i = colors; --i; ip += 2) pix[ip[0]] = sum[ip[0]] * ip[1] >> 8; } } } void CLASS lin_interpolate() { int code[16][16][32], size = 16, *ip, sum[4]; int f, c, x, y, row, col, shift, color; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Bilinear interpolation...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #endif if (filters == 9) size = 6; border_interpolate(1); for (row = 0; row < size; row++) for (col = 0; col < size; col++) { ip = code[row][col] + 1; f = fcol(row, col); memset(sum, 0, sizeof sum); for (y = -1; y <= 1; y++) for (x = -1; x <= 1; x++) { shift = (y == 0) + (x == 0); color = fcol(row + y, col + x); if (color == f) continue; *ip++ = (width * y + x) * 4 + color; *ip++ = shift; *ip++ = color; sum[color] += 1 << shift; } code[row][col][0] = (ip - code[row][col]) / 3; FORCC if (c != f) { *ip++ = c; *ip++ = sum[c] > 0 ? 256 / sum[c] : 0; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #endif lin_interpolate_loop(code, size); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #endif } /* This algorithm is officially called: "Interpolation using a Threshold-based variable number of gradients" described in http://scien.stanford.edu/pages/labsite/1999/psych221/projects/99/tingchen/algodep/vargra.html I've extended the basic idea to work with non-Bayer filter arrays. Gradients are numbered clockwise from NW=0 to W=7. */ void CLASS vng_interpolate() { static const signed char *cp, terms[] = {-2, -2, +0, -1, 0, 0x01, -2, -2, +0, +0, 1, 0x01, -2, -1, -1, +0, 0, 0x01, -2, -1, +0, -1, 0, 0x02, -2, -1, +0, +0, 0, 0x03, -2, -1, +0, +1, 1, 0x01, -2, +0, +0, -1, 0, 0x06, -2, +0, +0, +0, 1, 0x02, -2, +0, +0, +1, 0, 0x03, -2, +1, -1, +0, 0, 0x04, -2, +1, +0, -1, 1, 0x04, -2, +1, +0, +0, 0, 0x06, -2, +1, +0, +1, 0, 0x02, -2, +2, +0, +0, 1, 0x04, -2, +2, +0, +1, 0, 0x04, -1, -2, -1, +0, 0, -128, -1, -2, +0, -1, 0, 0x01, -1, -2, +1, -1, 0, 0x01, -1, -2, +1, +0, 1, 0x01, -1, -1, -1, +1, 0, -120, -1, -1, +1, -2, 0, 0x40, -1, -1, +1, -1, 0, 0x22, -1, -1, +1, +0, 0, 0x33, -1, -1, +1, +1, 1, 0x11, -1, +0, -1, +2, 0, 0x08, -1, +0, +0, -1, 0, 0x44, -1, +0, +0, +1, 0, 0x11, -1, +0, +1, -2, 1, 0x40, -1, +0, +1, -1, 0, 0x66, -1, +0, +1, +0, 1, 0x22, -1, +0, +1, +1, 0, 0x33, -1, +0, +1, +2, 1, 0x10, -1, +1, +1, -1, 1, 0x44, -1, +1, +1, +0, 0, 0x66, -1, +1, +1, +1, 0, 0x22, -1, +1, +1, +2, 0, 0x10, -1, +2, +0, +1, 0, 0x04, -1, +2, +1, +0, 1, 0x04, -1, +2, +1, +1, 0, 0x04, +0, -2, +0, +0, 1, -128, +0, -1, +0, +1, 1, -120, +0, -1, +1, -2, 0, 0x40, +0, -1, +1, +0, 0, 0x11, +0, -1, +2, -2, 0, 0x40, +0, -1, +2, -1, 0, 0x20, +0, -1, +2, +0, 0, 0x30, +0, -1, +2, +1, 1, 0x10, +0, +0, +0, +2, 1, 0x08, +0, +0, +2, -2, 1, 0x40, +0, +0, +2, -1, 0, 0x60, +0, +0, +2, +0, 1, 0x20, +0, +0, +2, +1, 0, 0x30, +0, +0, +2, +2, 1, 0x10, +0, +1, +1, +0, 0, 0x44, +0, +1, +1, +2, 0, 0x10, +0, +1, +2, -1, 1, 0x40, +0, +1, +2, +0, 0, 0x60, +0, +1, +2, +1, 0, 0x20, +0, +1, +2, +2, 0, 0x10, +1, -2, +1, +0, 0, -128, +1, -1, +1, +1, 0, -120, +1, +0, +1, +2, 0, 0x08, +1, +0, +2, -1, 0, 0x40, +1, +0, +2, +1, 0, 0x10}, chood[] = {-1, -1, -1, 0, -1, +1, 0, +1, +1, +1, +1, 0, +1, -1, 0, -1}; ushort(*brow[5])[4], *pix; int prow = 8, pcol = 2, *ip, *code[16][16], gval[8], gmin, gmax, sum[4]; int row, col, x, y, x1, x2, y1, y2, t, weight, grads, color, diag; int g, diff, thold, num, c; lin_interpolate(); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("VNG interpolation...\n")); #endif if (filters == 1) prow = pcol = 16; if (filters == 9) prow = pcol = 6; ip = (int *)calloc(prow * pcol, 1280); merror(ip, "vng_interpolate()"); for (row = 0; row < prow; row++) /* Precalculate for VNG */ for (col = 0; col < pcol; col++) { code[row][col] = ip; for (cp = terms, t = 0; t < 64; t++) { y1 = *cp++; x1 = *cp++; y2 = *cp++; x2 = *cp++; weight = *cp++; grads = *cp++; color = fcol(row + y1, col + x1); if (fcol(row + y2, col + x2) != color) continue; diag = (fcol(row, col + 1) == color && fcol(row + 1, col) == color) ? 2 : 1; if (abs(y1 - y2) == diag && abs(x1 - x2) == diag) continue; *ip++ = (y1 * width + x1) * 4 + color; *ip++ = (y2 * width + x2) * 4 + color; *ip++ = weight; for (g = 0; g < 8; g++) if (grads & 1 << g) *ip++ = g; *ip++ = -1; } *ip++ = INT_MAX; for (cp = chood, g = 0; g < 8; g++) { y = *cp++; x = *cp++; *ip++ = (y * width + x) * 4; color = fcol(row, col); if (fcol(row + y, col + x) != color && fcol(row + y * 2, col + x * 2) == color) *ip++ = (y * width + x) * 8 + color; else *ip++ = 0; } } brow[4] = (ushort(*)[4])calloc(width * 3, sizeof **brow); merror(brow[4], "vng_interpolate()"); for (row = 0; row < 3; row++) brow[row] = brow[4] + row * width; for (row = 2; row < height - 2; row++) { /* Do VNG interpolation */ #ifdef LIBRAW_LIBRARY_BUILD if (!((row - 2) % 256)) RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, (row - 2) / 256 + 1, ((height - 3) / 256) + 1); #endif for (col = 2; col < width - 2; col++) { pix = image[row * width + col]; ip = code[row % prow][col % pcol]; memset(gval, 0, sizeof gval); while ((g = ip[0]) != INT_MAX) { /* Calculate gradients */ diff = ABS(pix[g] - pix[ip[1]]) << ip[2]; gval[ip[3]] += diff; ip += 5; if ((g = ip[-1]) == -1) continue; gval[g] += diff; while ((g = *ip++) != -1) gval[g] += diff; } ip++; gmin = gmax = gval[0]; /* Choose a threshold */ for (g = 1; g < 8; g++) { if (gmin > gval[g]) gmin = gval[g]; if (gmax < gval[g]) gmax = gval[g]; } if (gmax == 0) { memcpy(brow[2][col], pix, sizeof *image); continue; } thold = gmin + (gmax >> 1); memset(sum, 0, sizeof sum); color = fcol(row, col); for (num = g = 0; g < 8; g++, ip += 2) { /* Average the neighbors */ if (gval[g] <= thold) { FORCC if (c == color && ip[1]) sum[c] += (pix[c] + pix[ip[1]]) >> 1; else sum[c] += pix[ip[0] + c]; num++; } } FORCC { /* Save to buffer */ t = pix[color]; if (c != color) t += (sum[c] - sum[color]) / num; brow[2][col][c] = CLIP(t); } } if (row > 3) /* Write buffer to image */ memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); for (g = 0; g < 4; g++) brow[(g - 1) & 3] = brow[g]; } memcpy(image[(row - 2) * width + 2], brow[0] + 2, (width - 4) * sizeof *image); memcpy(image[(row - 1) * width + 2], brow[1] + 2, (width - 4) * sizeof *image); free(brow[4]); free(code[0][0]); } /* Patterned Pixel Grouping Interpolation by Alain Desbiolles */ void CLASS ppg_interpolate() { int dir[5] = {1, width, -1, -width, 1}; int row, col, diff[2], guess[2], c, d, i; ushort(*pix)[4]; border_interpolate(3); #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("PPG interpolation...\n")); #endif /* Fill in the green layer with gradients and pattern recognition: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 0, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 3; row < height - 3; row++) for (col = 3 + (FC(row, 3) & 1), c = FC(row, col); col < width - 3; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; i++) { guess[i] = (pix[-d][1] + pix[0][c] + pix[d][1]) * 2 - pix[-2 * d][c] - pix[2 * d][c]; diff[i] = (ABS(pix[-2 * d][c] - pix[0][c]) + ABS(pix[2 * d][c] - pix[0][c]) + ABS(pix[-d][1] - pix[d][1])) * 3 + (ABS(pix[3 * d][1] - pix[d][1]) + ABS(pix[-3 * d][1] - pix[-d][1])) * 2; } d = dir[i = diff[0] > diff[1]]; pix[0][1] = ULIM(guess[i] >> 2, pix[d][1], pix[-d][1]); } /* Calculate red and blue for each green pixel: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 1, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 2) & 1), c = FC(row, col + 1); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i]) > 0; c = 2 - c, i++) pix[0][c] = CLIP((pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]) >> 1); } /* Calculate blue for red pixels and vice versa: */ #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_INTERPOLATE, 2, 3); #ifdef LIBRAW_USE_OPENMP #pragma omp parallel for default(shared) private(guess, diff, row, col, d, c, i, pix) schedule(static) #endif #endif for (row = 1; row < height - 1; row++) for (col = 1 + (FC(row, 1) & 1), c = 2 - FC(row, col); col < width - 1; col += 2) { pix = image + row * width + col; for (i = 0; (d = dir[i] + dir[i + 1]) > 0; i++) { diff[i] = ABS(pix[-d][c] - pix[d][c]) + ABS(pix[-d][1] - pix[0][1]) + ABS(pix[d][1] - pix[0][1]); guess[i] = pix[-d][c] + pix[d][c] + 2 * pix[0][1] - pix[-d][1] - pix[d][1]; } if (diff[0] != diff[1]) pix[0][c] = CLIP(guess[diff[0] > diff[1]] >> 1); else pix[0][c] = CLIP((guess[0] + guess[1]) >> 2); } } void CLASS cielab(ushort rgb[3], short lab[3]) { int c, i, j, k; float r, xyz[3]; #ifdef LIBRAW_NOTHREADS static float cbrt[0x10000], xyz_cam[3][4]; #else #define cbrt tls->ahd_data.cbrt #define xyz_cam tls->ahd_data.xyz_cam #endif if (!rgb) { #ifndef LIBRAW_NOTHREADS if (cbrt[0] < -1.0f) #endif for (i = 0; i < 0x10000; i++) { r = i / 65535.0; cbrt[i] = r > 0.008856 ? pow(r, 1.f / 3.0f) : 7.787f * r + 16.f / 116.0f; } for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (xyz_cam[i][j] = k = 0; k < 3; k++) xyz_cam[i][j] += xyz_rgb[i][k] * rgb_cam[k][j] / d65_white[i]; return; } xyz[0] = xyz[1] = xyz[2] = 0.5; FORCC { xyz[0] += xyz_cam[0][c] * rgb[c]; xyz[1] += xyz_cam[1][c] * rgb[c]; xyz[2] += xyz_cam[2][c] * rgb[c]; } xyz[0] = cbrt[CLIP((int)xyz[0])]; xyz[1] = cbrt[CLIP((int)xyz[1])]; xyz[2] = cbrt[CLIP((int)xyz[2])]; lab[0] = 64 * (116 * xyz[1] - 16); lab[1] = 64 * 500 * (xyz[0] - xyz[1]); lab[2] = 64 * 200 * (xyz[1] - xyz[2]); #ifndef LIBRAW_NOTHREADS #undef cbrt #undef xyz_cam #endif } #define TS 512 /* Tile Size */ #define fcol(row, col) xtrans[(row + 6) % 6][(col + 6) % 6] /* Frank Markesteijn's algorithm for Fuji X-Trans sensors */ void CLASS xtrans_interpolate(int passes) { int c, d, f, g, h, i, v, ng, row, col, top, left, mrow, mcol; #ifdef LIBRAW_LIBRARY_BUILD int cstat[4]={0,0,0,0}; #endif int val, ndir, pass, hm[8], avg[4], color[3][8]; static const short orth[12] = {1, 0, 0, 1, -1, 0, 0, -1, 1, 0, 0, 1}, patt[2][16] = {{0, 1, 0, -1, 2, 0, -1, 0, 1, 1, 1, -1, 0, 0, 0, 0}, {0, 1, 0, -2, 1, 0, -2, 0, 1, 1, -2, -2, 1, -1, -1, 1}}, dir[4] = {1, TS, TS + 1, TS - 1}; short allhex[3][3][2][8], *hex; ushort min, max, sgrow, sgcol; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][3], (*lix)[3]; float(*drv)[TS][TS], diff[6], tr; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("%d-pass X-Trans interpolation...\n"), passes); #endif #ifdef LIBRAW_LIBRARY_BUILD if(width < TS || height < TS) throw LIBRAW_EXCEPTION_IO_CORRUPT; // too small image /* Check against right pattern */ for (row = 0; row < 6; row++) for (col = 0; col < 6; col++) cstat[fcol(row,col)]++; if(cstat[0] < 6 || cstat[0]>10 || cstat[1]< 16 || cstat[1]>24 || cstat[2]< 6 || cstat[2]>10 || cstat[3]) throw LIBRAW_EXCEPTION_IO_CORRUPT; // Init allhex table to unreasonable values for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) allhex[i][j][k][l]=32700; #endif cielab(0, 0); ndir = 4 << (passes > 1); buffer = (char *)malloc(TS * TS * (ndir * 11 + 6)); merror(buffer, "xtrans_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][3])(buffer + TS * TS * (ndir * 6)); drv = (float(*)[TS][TS])(buffer + TS * TS * (ndir * 6 + 6)); homo = (char(*)[TS][TS])(buffer + TS * TS * (ndir * 10 + 6)); int minv=0,maxv=0,minh=0,maxh=0; /* Map a green hexagon around each non-green pixel and vice versa: */ for (row = 0; row < 3; row++) for (col = 0; col < 3; col++) for (ng = d = 0; d < 10; d += 2) { g = fcol(row, col) == 1; if (fcol(row + orth[d], col + orth[d + 2]) == 1) ng = 0; else ng++; if (ng == 4) { sgrow = row; sgcol = col; } if (ng == g + 1) FORC(8) { v = orth[d] * patt[g][c * 2] + orth[d + 1] * patt[g][c * 2 + 1]; h = orth[d + 2] * patt[g][c * 2] + orth[d + 3] * patt[g][c * 2 + 1]; minv=MIN(v,minv); maxv=MAX(v,maxv); minh=MIN(v,minh); maxh=MAX(v,maxh); allhex[row][col][0][c ^ (g * 2 & d)] = h + v * width; allhex[row][col][1][c ^ (g * 2 & d)] = h + v * TS; } } #ifdef LIBRAW_LIBRARY_BUILD // Check allhex table initialization for(int i = 0; i < 3; i++) for(int j = 0; j < 3; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 8; l++) if(allhex[i][j][k][l]>maxh+maxv*width+1 || allhex[i][j][k][l]<minh+minv*width-1) throw LIBRAW_EXCEPTION_IO_CORRUPT; int retrycount = 0; #endif /* Set green1 and green3 to the minimum and maximum allowed values: */ for (row = 2; row < height - 2; row++) for (min = ~(max = 0), col = 2; col < width - 2; col++) { if (fcol(row, col) == 1 && (min = ~(max = 0))) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; if (!max) FORC(6) { val = pix[hex[c]][1]; if (min > val) min = val; if (max < val) max = val; } pix[0][1] = min; pix[0][3] = max; switch ((row - sgrow) % 3) { case 1: if (row < height - 3) { row++; col--; } break; case 2: if ((min = ~(max = 0)) && (col += 2) < width - 3 && row > 2) { row--; #ifdef LIBRAW_LIBRARY_BUILD if(retrycount++ > width*height) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif } } } for (top = 3; top < height - 19; top += TS - 16) for (left = 3; left < width - 19; left += TS - 16) { mrow = MIN(top + TS, height - 3); mcol = MIN(left + TS, width - 3); for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) memcpy(rgb[0][row - top][col - left], image[row * width + col], 6); FORC3 memcpy(rgb[c + 1], rgb[0], sizeof *rgb); /* Interpolate green horizontally, vertically, and along both diagonals: */ for (row = top; row < mrow; row++) for (col = left; col < mcol; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][0]; color[1][0] = 174 * (pix[hex[1]][1] + pix[hex[0]][1]) - 46 * (pix[2 * hex[1]][1] + pix[2 * hex[0]][1]); color[1][1] = 223 * pix[hex[3]][1] + pix[hex[2]][1] * 33 + 92 * (pix[0][f] - pix[-hex[2]][f]); FORC(2) color[1][2 + c] = 164 * pix[hex[4 + c]][1] + 92 * pix[-2 * hex[4 + c]][1] + 33 * (2 * pix[0][f] - pix[3 * hex[4 + c]][f] - pix[-3 * hex[4 + c]][f]); FORC4 rgb[c ^ !((row - sgrow) % 3)][row - top][col - left][1] = LIM(color[1][c] >> 8, pix[0][1], pix[0][3]); } for (pass = 0; pass < passes; pass++) { if (pass == 1) memcpy(rgb += 4, buffer, 4 * sizeof *rgb); /* Recalculate green from interpolated values of closer pixels: */ if (pass) { for (row = top + 2; row < mrow - 2; row++) for (col = left + 2; col < mcol - 2; col++) { if ((f = fcol(row, col)) == 1) continue; pix = image + row * width + col; hex = allhex[row % 3][col % 3][1]; for (d = 3; d < 6; d++) { rix = &rgb[(d - 2) ^ !((row - sgrow) % 3)][row - top][col - left]; val = rix[-2 * hex[d]][1] + 2 * rix[hex[d]][1] - rix[-2 * hex[d]][f] - 2 * rix[hex[d]][f] + 3 * rix[0][f]; rix[0][1] = LIM(val / 3, pix[0][1], pix[0][3]); } } } /* Interpolate red and blue values for solitary green pixels: */ for (row = (top - sgrow + 4) / 3 * 3 + sgrow; row < mrow - 2; row += 3) for (col = (left - sgcol + 4) / 3 * 3 + sgcol; col < mcol - 2; col += 3) { rix = &rgb[0][row - top][col - left]; h = fcol(row, col + 1); memset(diff, 0, sizeof diff); for (i = 1, d = 0; d < 6; d++, i ^= TS ^ 1, h ^= 2) { for (c = 0; c < 2; c++, h ^= 2) { g = 2 * rix[0][1] - rix[i << c][1] - rix[-i << c][1]; color[h][d] = g + rix[i << c][h] + rix[-i << c][h]; if (d > 1) diff[d] += SQR(rix[i << c][1] - rix[-i << c][1] - rix[i << c][h] + rix[-i << c][h]) + SQR(g); } if (d > 1 && (d & 1)) if (diff[d - 1] < diff[d]) FORC(2) color[c * 2][d] = color[c * 2][d - 1]; if (d < 2 || (d & 1)) { FORC(2) rix[0][c * 2] = CLIP(color[c * 2][d] / 2); rix += TS * TS; } } } /* Interpolate red for blue pixels and vice versa: */ for (row = top + 3; row < mrow - 3; row++) for (col = left + 3; col < mcol - 3; col++) { if ((f = 2 - fcol(row, col)) == 1) continue; rix = &rgb[0][row - top][col - left]; c = (row - sgrow) % 3 ? TS : 1; h = 3 * (c ^ TS ^ 1); for (d = 0; d < 4; d++, rix += TS * TS) { i = d > 1 || ((d ^ c) & 1) || ((ABS(rix[0][1] - rix[c][1]) + ABS(rix[0][1] - rix[-c][1])) < 2 * (ABS(rix[0][1] - rix[h][1]) + ABS(rix[0][1] - rix[-h][1]))) ? c : h; rix[0][f] = CLIP((rix[i][f] + rix[-i][f] + 2 * rix[0][1] - rix[i][1] - rix[-i][1]) / 2); } } /* Fill in red and blue for 2x2 blocks of green: */ for (row = top + 2; row < mrow - 2; row++) if ((row - sgrow) % 3) for (col = left + 2; col < mcol - 2; col++) if ((col - sgcol) % 3) { rix = &rgb[0][row - top][col - left]; hex = allhex[row % 3][col % 3][1]; for (d = 0; d < ndir; d += 2, rix += TS * TS) if (hex[d] + hex[d + 1]) { g = 3 * rix[0][1] - 2 * rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + 2 * rix[hex[d]][c] + rix[hex[d + 1]][c]) / 3); } else { g = 2 * rix[0][1] - rix[hex[d]][1] - rix[hex[d + 1]][1]; for (c = 0; c < 4; c += 2) rix[0][c] = CLIP((g + rix[hex[d]][c] + rix[hex[d + 1]][c]) / 2); } } } rgb = (ushort(*)[TS][TS][3])buffer; mrow -= top; mcol -= left; /* Convert to CIELab and differentiate in all directions: */ for (d = 0; d < ndir; d++) { for (row = 2; row < mrow - 2; row++) for (col = 2; col < mcol - 2; col++) cielab(rgb[d][row][col], lab[row][col]); for (f = dir[d & 3], row = 3; row < mrow - 3; row++) for (col = 3; col < mcol - 3; col++) { lix = &lab[row][col]; g = 2 * lix[0][0] - lix[f][0] - lix[-f][0]; drv[d][row][col] = SQR(g) + SQR((2 * lix[0][1] - lix[f][1] - lix[-f][1] + g * 500 / 232)) + SQR((2 * lix[0][2] - lix[f][2] - lix[-f][2] - g * 500 / 580)); } } /* Build homogeneity maps from the derivatives: */ memset(homo, 0, ndir * TS * TS); for (row = 4; row < mrow - 4; row++) for (col = 4; col < mcol - 4; col++) { for (tr = FLT_MAX, d = 0; d < ndir; d++) if (tr > drv[d][row][col]) tr = drv[d][row][col]; tr *= 8; for (d = 0; d < ndir; d++) for (v = -1; v <= 1; v++) for (h = -1; h <= 1; h++) if (drv[d][row + v][col + h] <= tr) homo[d][row][col]++; } /* Average the most homogenous pixels for the final result: */ if (height - top < TS + 4) mrow = height - top + 2; if (width - left < TS + 4) mcol = width - left + 2; for (row = MIN(top, 8); row < mrow - 8; row++) for (col = MIN(left, 8); col < mcol - 8; col++) { for (d = 0; d < ndir; d++) for (hm[d] = 0, v = -2; v <= 2; v++) for (h = -2; h <= 2; h++) hm[d] += homo[d][row + v][col + h]; for (d = 0; d < ndir - 4; d++) if (hm[d] < hm[d + 4]) hm[d] = 0; else if (hm[d] > hm[d + 4]) hm[d + 4] = 0; for (max = hm[0], d = 1; d < ndir; d++) if (max < hm[d]) max = hm[d]; max -= max >> 3; memset(avg, 0, sizeof avg); for (d = 0; d < ndir; d++) if (hm[d] >= max) { FORC3 avg[c] += rgb[d][row][col][c]; avg[3]++; } FORC3 image[(row + top) * width + col + left][c] = avg[c] / avg[3]; } } free(buffer); border_interpolate(8); } #undef fcol /* Adaptive Homogeneity-Directed interpolation is based on the work of Keigo Hirakawa, Thomas Parks, and Paul Lee. */ #ifdef LIBRAW_LIBRARY_BUILD void CLASS ahd_interpolate_green_h_and_v(int top, int left, ushort (*out_rgb)[TS][TS][3]) { int row, col; int c, val; ushort(*pix)[4]; const int rowlimit = MIN(top + TS, height - 2); const int collimit = MIN(left + TS, width - 2); for (row = top; row < rowlimit; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < collimit; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; out_rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; out_rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } } void CLASS ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][3], short (*out_lab)[TS][3]) { unsigned row, col; int c, val; ushort(*pix)[4]; ushort(*rix)[3]; short(*lix)[3]; float xyz[3]; const unsigned num_pix_per_row = 4 * width; const unsigned rowlimit = MIN(top + TS - 1, height - 3); const unsigned collimit = MIN(left + TS - 1, width - 3); ushort *pix_above; ushort *pix_below; int t1, t2; for (row = top + 1; row < rowlimit; row++) { pix = image + row * width + left; rix = &inout_rgb[row - top][0]; lix = &out_lab[row - top][0]; for (col = left + 1; col < collimit; col++) { pix++; pix_above = &pix[0][0] - num_pix_per_row; pix_below = &pix[0][0] + num_pix_per_row; rix++; lix++; c = 2 - FC(row, col); if (c == 1) { c = FC(row + 1, col); t1 = 2 - c; val = pix[0][1] + ((pix[-1][t1] + pix[1][t1] - rix[-1][1] - rix[1][1]) >> 1); rix[0][t1] = CLIP(val); val = pix[0][1] + ((pix_above[c] + pix_below[c] - rix[-TS][1] - rix[TS][1]) >> 1); } else { t1 = -4 + c; /* -4+c: pixel of color c to the left */ t2 = 4 + c; /* 4+c: pixel of color c to the right */ val = rix[0][1] + ((pix_above[t1] + pix_above[t2] + pix_below[t1] + pix_below[t2] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); } rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } } } void CLASS ahd_interpolate_r_and_b_and_convert_to_cielab(int top, int left, ushort (*inout_rgb)[TS][TS][3], short (*out_lab)[TS][TS][3]) { int direction; for (direction = 0; direction < 2; direction++) { ahd_interpolate_r_and_b_in_rgb_and_convert_to_cielab(top, left, inout_rgb[direction], out_lab[direction]); } } void CLASS ahd_interpolate_build_homogeneity_map(int top, int left, short (*lab)[TS][TS][3], char (*out_homogeneity_map)[TS][2]) { int row, col; int tr, tc; int direction; int i; short(*lix)[3]; short(*lixs[2])[3]; short *adjacent_lix; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; static const int dir[4] = {-1, 1, -TS, TS}; const int rowlimit = MIN(top + TS - 2, height - 4); const int collimit = MIN(left + TS - 2, width - 4); int homogeneity; char(*homogeneity_map_p)[2]; memset(out_homogeneity_map, 0, 2 * TS * TS); for (row = top + 2; row < rowlimit; row++) { tr = row - top; homogeneity_map_p = &out_homogeneity_map[tr][1]; for (direction = 0; direction < 2; direction++) { lixs[direction] = &lab[direction][tr][1]; } for (col = left + 2; col < collimit; col++) { tc = col - left; homogeneity_map_p++; for (direction = 0; direction < 2; direction++) { lix = ++lixs[direction]; for (i = 0; i < 4; i++) { adjacent_lix = lix[dir[i]]; ldiff[direction][i] = ABS(lix[0][0] - adjacent_lix[0]); abdiff[direction][i] = SQR(lix[0][1] - adjacent_lix[1]) + SQR(lix[0][2] - adjacent_lix[2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (direction = 0; direction < 2; direction++) { homogeneity = 0; for (i = 0; i < 4; i++) { if (ldiff[direction][i] <= leps && abdiff[direction][i] <= abeps) { homogeneity++; } } homogeneity_map_p[0][direction] = homogeneity; } } } } void CLASS ahd_interpolate_combine_homogeneous_pixels(int top, int left, ushort (*rgb)[TS][TS][3], char (*homogeneity_map)[TS][2]) { int row, col; int tr, tc; int i, j; int direction; int hm[2]; int c; const int rowlimit = MIN(top + TS - 3, height - 5); const int collimit = MIN(left + TS - 3, width - 5); ushort(*pix)[4]; ushort(*rix[2])[3]; for (row = top + 3; row < rowlimit; row++) { tr = row - top; pix = &image[row * width + left + 2]; for (direction = 0; direction < 2; direction++) { rix[direction] = &rgb[direction][tr][2]; } for (col = left + 3; col < collimit; col++) { tc = col - left; pix++; for (direction = 0; direction < 2; direction++) { rix[direction]++; } for (direction = 0; direction < 2; direction++) { hm[direction] = 0; for (i = tr - 1; i <= tr + 1; i++) { for (j = tc - 1; j <= tc + 1; j++) { hm[direction] += homogeneity_map[i][j][direction]; } } } if (hm[0] != hm[1]) { memcpy(pix[0], rix[hm[1] > hm[0]][0], 3 * sizeof(ushort)); } else { FORC3 { pix[0][c] = (rix[0][0][c] + rix[1][0][c]) >> 1; } } } } } void CLASS ahd_interpolate() { int i, j, k, top, left; float xyz_cam[3][4], r; char *buffer; ushort(*rgb)[TS][TS][3]; short(*lab)[TS][TS][3]; char(*homo)[TS][2]; int terminate_flag = 0; cielab(0, 0); border_interpolate(5); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp parallel private(buffer, rgb, lab, homo, top, left, i, j, k) shared(xyz_cam, terminate_flag) #endif #endif { buffer = (char *)malloc(26 * TS * TS); /* 1664 kB */ merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][2])(buffer + 24 * TS * TS); #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP #pragma omp for schedule(dynamic) #endif #endif for (top = 2; top < height - 5; top += TS - 6) { #ifdef LIBRAW_LIBRARY_BUILD #ifdef LIBRAW_USE_OPENMP if (0 == omp_get_thread_num()) #endif if (callbacks.progress_cb) { int rr = (*callbacks.progress_cb)(callbacks.progresscb_data, LIBRAW_PROGRESS_INTERPOLATE, top - 2, height - 7); if (rr) terminate_flag = 1; } #endif for (left = 2; !terminate_flag && (left < width - 5); left += TS - 6) { ahd_interpolate_green_h_and_v(top, left, rgb); ahd_interpolate_r_and_b_and_convert_to_cielab(top, left, rgb, lab); ahd_interpolate_build_homogeneity_map(top, left, lab, homo); ahd_interpolate_combine_homogeneous_pixels(top, left, rgb, homo); } } free(buffer); } #ifdef LIBRAW_LIBRARY_BUILD if (terminate_flag) throw LIBRAW_EXCEPTION_CANCELLED_BY_CALLBACK; #endif } #else void CLASS ahd_interpolate() { int i, j, top, left, row, col, tr, tc, c, d, val, hm[2]; static const int dir[4] = {-1, 1, -TS, TS}; unsigned ldiff[2][4], abdiff[2][4], leps, abeps; ushort(*rgb)[TS][TS][3], (*rix)[3], (*pix)[4]; short(*lab)[TS][TS][3], (*lix)[3]; char(*homo)[TS][TS], *buffer; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("AHD interpolation...\n")); #endif cielab(0, 0); border_interpolate(5); buffer = (char *)malloc(26 * TS * TS); merror(buffer, "ahd_interpolate()"); rgb = (ushort(*)[TS][TS][3])buffer; lab = (short(*)[TS][TS][3])(buffer + 12 * TS * TS); homo = (char(*)[TS][TS])(buffer + 24 * TS * TS); for (top = 2; top < height - 5; top += TS - 6) for (left = 2; left < width - 5; left += TS - 6) { /* Interpolate green horizontally and vertically: */ for (row = top; row < top + TS && row < height - 2; row++) { col = left + (FC(row, left) & 1); for (c = FC(row, col); col < left + TS && col < width - 2; col += 2) { pix = image + row * width + col; val = ((pix[-1][1] + pix[0][c] + pix[1][1]) * 2 - pix[-2][c] - pix[2][c]) >> 2; rgb[0][row - top][col - left][1] = ULIM(val, pix[-1][1], pix[1][1]); val = ((pix[-width][1] + pix[0][c] + pix[width][1]) * 2 - pix[-2 * width][c] - pix[2 * width][c]) >> 2; rgb[1][row - top][col - left][1] = ULIM(val, pix[-width][1], pix[width][1]); } } /* Interpolate red and blue, and convert to CIELab: */ for (d = 0; d < 2; d++) for (row = top + 1; row < top + TS - 1 && row < height - 3; row++) for (col = left + 1; col < left + TS - 1 && col < width - 3; col++) { pix = image + row * width + col; rix = &rgb[d][row - top][col - left]; lix = &lab[d][row - top][col - left]; if ((c = 2 - FC(row, col)) == 1) { c = FC(row + 1, col); val = pix[0][1] + ((pix[-1][2 - c] + pix[1][2 - c] - rix[-1][1] - rix[1][1]) >> 1); rix[0][2 - c] = CLIP(val); val = pix[0][1] + ((pix[-width][c] + pix[width][c] - rix[-TS][1] - rix[TS][1]) >> 1); } else val = rix[0][1] + ((pix[-width - 1][c] + pix[-width + 1][c] + pix[+width - 1][c] + pix[+width + 1][c] - rix[-TS - 1][1] - rix[-TS + 1][1] - rix[+TS - 1][1] - rix[+TS + 1][1] + 1) >> 2); rix[0][c] = CLIP(val); c = FC(row, col); rix[0][c] = pix[0][c]; cielab(rix[0], lix[0]); } /* Build homogeneity maps from the CIELab images: */ memset(homo, 0, 2 * TS * TS); for (row = top + 2; row < top + TS - 2 && row < height - 4; row++) { tr = row - top; for (col = left + 2; col < left + TS - 2 && col < width - 4; col++) { tc = col - left; for (d = 0; d < 2; d++) { lix = &lab[d][tr][tc]; for (i = 0; i < 4; i++) { ldiff[d][i] = ABS(lix[0][0] - lix[dir[i]][0]); abdiff[d][i] = SQR(lix[0][1] - lix[dir[i]][1]) + SQR(lix[0][2] - lix[dir[i]][2]); } } leps = MIN(MAX(ldiff[0][0], ldiff[0][1]), MAX(ldiff[1][2], ldiff[1][3])); abeps = MIN(MAX(abdiff[0][0], abdiff[0][1]), MAX(abdiff[1][2], abdiff[1][3])); for (d = 0; d < 2; d++) for (i = 0; i < 4; i++) if (ldiff[d][i] <= leps && abdiff[d][i] <= abeps) homo[d][tr][tc]++; } } /* Combine the most homogenous pixels for the final result: */ for (row = top + 3; row < top + TS - 3 && row < height - 5; row++) { tr = row - top; for (col = left + 3; col < left + TS - 3 && col < width - 5; col++) { tc = col - left; for (d = 0; d < 2; d++) for (hm[d] = 0, i = tr - 1; i <= tr + 1; i++) for (j = tc - 1; j <= tc + 1; j++) hm[d] += homo[d][i][j]; if (hm[0] != hm[1]) FORC3 image[row * width + col][c] = rgb[hm[1] > hm[0]][tr][tc][c]; else FORC3 image[row * width + col][c] = (rgb[0][tr][tc][c] + rgb[1][tr][tc][c]) >> 1; } } } free(buffer); } #endif #undef TS void CLASS median_filter() { ushort(*pix)[4]; int pass, c, i, j, k, med[9]; static const uchar opt[] = /* Optimal 9-element median search */ {1, 2, 4, 5, 7, 8, 0, 1, 3, 4, 6, 7, 1, 2, 4, 5, 7, 8, 0, 3, 5, 8, 4, 7, 3, 6, 1, 4, 2, 5, 4, 7, 4, 2, 6, 4, 4, 2}; for (pass = 1; pass <= med_passes; pass++) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_MEDIAN_FILTER, pass - 1, med_passes); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Median filter pass %d...\n"), pass); #endif for (c = 0; c < 3; c += 2) { for (pix = image; pix < image + width * height; pix++) pix[0][3] = pix[0][c]; for (pix = image + width; pix < image + width * (height - 1); pix++) { if ((pix - image + 1) % width < 2) continue; for (k = 0, i = -width; i <= width; i += width) for (j = i - 1; j <= i + 1; j++) med[k++] = pix[j][3] - pix[j][1]; for (i = 0; i < sizeof opt; i += 2) if (med[opt[i]] > med[opt[i + 1]]) SWAP(med[opt[i]], med[opt[i + 1]]); pix[0][c] = CLIP(med[4] + pix[0][1]); } } } } void CLASS blend_highlights() { int clip = INT_MAX, row, col, c, i, j; static const float trans[2][4][4] = {{{1, 1, 1}, {1.7320508, -1.7320508, 0}, {-1, -1, 2}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; static const float itrans[2][4][4] = {{{1, 0.8660254, -0.5}, {1, -0.8660254, -0.5}, {1, 0, 1}}, {{1, 1, 1, 1}, {1, -1, 1, -1}, {1, 1, -1, -1}, {1, -1, -1, 1}}}; float cam[2][4], lab[2][4], sum[2], chratio; if ((unsigned)(colors - 3) > 1) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Blending highlights...\n")); #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 0, 2); #endif FORCC if (clip > (i = 65535 * pre_mul[c])) clip = i; for (row = 0; row < height; row++) for (col = 0; col < width; col++) { FORCC if (image[row * width + col][c] > clip) break; if (c == colors) continue; FORCC { cam[0][c] = image[row * width + col][c]; cam[1][c] = MIN(cam[0][c], clip); } for (i = 0; i < 2; i++) { FORCC for (lab[i][c] = j = 0; j < colors; j++) lab[i][c] += trans[colors - 3][c][j] * cam[i][j]; for (sum[i] = 0, c = 1; c < colors; c++) sum[i] += SQR(lab[i][c]); } chratio = sqrt(sum[1] / sum[0]); for (c = 1; c < colors; c++) lab[0][c] *= chratio; FORCC for (cam[0][c] = j = 0; j < colors; j++) cam[0][c] += itrans[colors - 3][c][j] * lab[0][j]; FORCC image[row * width + col][c] = cam[0][c] / colors; } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, 1, 2); #endif } #define SCALE (4 >> shrink) void CLASS recover_highlights() { float *map, sum, wgt, grow; int hsat[4], count, spread, change, val, i; unsigned high, wide, mrow, mcol, row, col, kc, c, d, y, x; ushort *pixel; static const signed char dir[8][2] = {{-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}}; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rebuilding highlights...\n")); #endif grow = pow(2.0, 4 - highlight); FORCC hsat[c] = 32000 * pre_mul[c]; for (kc = 0, c = 1; c < colors; c++) if (pre_mul[kc] < pre_mul[c]) kc = c; high = height / SCALE; wide = width / SCALE; map = (float *)calloc(high, wide * sizeof *map); merror(map, "recover_highlights()"); FORCC if (c != kc) { #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_HIGHLIGHTS, c - 1, colors - 1); #endif memset(map, 0, high * wide * sizeof *map); for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { sum = wgt = count = 0; for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] == 1 && pixel[kc] > 24000) { sum += pixel[c]; wgt += pixel[kc]; count++; } } if (count == SCALE * SCALE) map[mrow * wide + mcol] = sum / wgt; } for (spread = 32 / grow; spread--;) { for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { if (map[mrow * wide + mcol]) continue; sum = count = 0; for (d = 0; d < 8; d++) { y = mrow + dir[d][0]; x = mcol + dir[d][1]; if (y < high && x < wide && map[y * wide + x] > 0) { sum += (1 + (d & 1)) * map[y * wide + x]; count += 1 + (d & 1); } } if (count > 3) map[mrow * wide + mcol] = -(sum + grow) / (count + grow); } for (change = i = 0; i < high * wide; i++) if (map[i] < 0) { map[i] = -map[i]; change = 1; } if (!change) break; } for (i = 0; i < high * wide; i++) if (map[i] == 0) map[i] = 1; for (mrow = 0; mrow < high; mrow++) for (mcol = 0; mcol < wide; mcol++) { for (row = mrow * SCALE; row < (mrow + 1) * SCALE; row++) for (col = mcol * SCALE; col < (mcol + 1) * SCALE; col++) { pixel = image[row * width + col]; if (pixel[c] / hsat[c] > 1) { val = pixel[kc] * map[mrow * wide + mcol]; if (pixel[c] < val) pixel[c] = CLIP(val); } } } } free(map); } #undef SCALE void CLASS tiff_get(unsigned base, unsigned *tag, unsigned *type, unsigned *len, unsigned *save) { *tag = get2(); *type = get2(); *len = get4(); *save = ftell(ifp) + 4; if (*len * ("11124811248484"[*type < 14 ? *type : 0] - '0') > 4) fseek(ifp, get4() + base, SEEK_SET); } void CLASS parse_thumb_note(int base, unsigned toff, unsigned tlen) { unsigned entries, tag, type, len, save; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == toff) thumb_offset = get4() + base; if (tag == tlen) thumb_length = get4(); fseek(ifp, save, SEEK_SET); } } static float powf_lim(float a, float b, float limup) { return (b > limup || b < -limup) ? 0.f : powf(a, b); } static float powf64(float a, float b) { return powf_lim(a, b, 64.f); } #ifdef LIBRAW_LIBRARY_BUILD static float my_roundf(float x) { float t; if (x >= 0.0) { t = ceilf(x); if (t - x > 0.5) t -= 1.0; return t; } else { t = ceilf(-x); if (t + x > 0.5) t -= 1.0; return -t; } } static float _CanonConvertAperture(ushort in) { if ((in == (ushort)0xffe0) || (in == (ushort)0x7fff)) return 0.0f; return powf64(2.0, in / 64.0); } static float _CanonConvertEV(short in) { short EV, Sign, Frac; float Frac_f; EV = in; if (EV < 0) { EV = -EV; Sign = -1; } else { Sign = 1; } Frac = EV & 0x1f; EV -= Frac; // remove fraction if (Frac == 0x0c) { // convert 1/3 and 2/3 codes Frac_f = 32.0f / 3.0f; } else if (Frac == 0x14) { Frac_f = 64.0f / 3.0f; } else Frac_f = (float)Frac; return ((float)Sign * ((float)EV + Frac_f)) / 32.0f; } unsigned CLASS setCanonBodyFeatures(unsigned id) { if (id == 0x03740000) // EOS M3 id = 0x80000374; else if (id == 0x03840000) // EOS M10 id = 0x80000384; else if (id == 0x03940000) // EOS M5 id = 0x80000394; else if (id == 0x04070000) // EOS M6 id = 0x80000407; else if (id == 0x03980000) // EOS M100 id = 0x80000398; imgdata.lens.makernotes.CamID = id; if ((id == 0x80000001) || // 1D (id == 0x80000174) || // 1D2 (id == 0x80000232) || // 1D2N (id == 0x80000169) || // 1D3 (id == 0x80000281) // 1D4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSH; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000167) || // 1Ds (id == 0x80000188) || // 1Ds2 (id == 0x80000215) || // 1Ds3 (id == 0x80000269) || // 1DX (id == 0x80000328) || // 1DX2 (id == 0x80000324) || // 1DC (id == 0x80000213) || // 5D (id == 0x80000218) || // 5D2 (id == 0x80000285) || // 5D3 (id == 0x80000349) || // 5D4 (id == 0x80000382) || // 5DS (id == 0x80000401) || // 5DS R (id == 0x80000302) // 6D ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; } else if ((id == 0x80000331) || // M (id == 0x80000355) || // M2 (id == 0x80000374) || // M3 (id == 0x80000384) || // M10 (id == 0x80000394) || // M5 (id == 0x80000407) || // M6 (id == 0x80000398) // M100 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF_M; } else if ((id == 0x01140000) || // D30 (id == 0x01668000) || // D60 (id > 0x80000000)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Unknown; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } return id; } void CLASS processCanonCameraInfo(unsigned id, uchar *CameraInfo, unsigned maxlen, unsigned type) { ushort iCanonLensID = 0, iCanonMaxFocal = 0, iCanonMinFocal = 0, iCanonLens = 0, iCanonCurFocal = 0, iCanonFocalType = 0; if(maxlen<16) return; // too short CameraInfo[0] = 0; CameraInfo[1] = 0; if (type == 4) { if ((maxlen == 94) || (maxlen == 138) || (maxlen == 148) || (maxlen == 156) || (maxlen == 162) || (maxlen == 167) || (maxlen == 171) || (maxlen == 264) || (maxlen > 400)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-3)<<2)); else if (maxlen == 72) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-1)<<2)); else if ((maxlen == 85) || (maxlen == 93)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-2)<<2)); else if ((maxlen == 96) || (maxlen == 104)) imgdata.other.CameraTemperature = sget4(CameraInfo + ((maxlen-4)<<2)); } switch (id) { case 0x80000001: // 1D case 0x80000167: // 1DS iCanonCurFocal = 10; iCanonLensID = 13; iCanonMinFocal = 14; iCanonMaxFocal = 16; if (!imgdata.lens.makernotes.CurFocal) imgdata.lens.makernotes.CurFocal = sget2(CameraInfo + iCanonCurFocal); if (!imgdata.lens.makernotes.MinFocal) imgdata.lens.makernotes.MinFocal = sget2(CameraInfo + iCanonMinFocal); if (!imgdata.lens.makernotes.MaxFocal) imgdata.lens.makernotes.MaxFocal = sget2(CameraInfo + iCanonMaxFocal); imgdata.other.CameraTemperature = 0.0f; break; case 0x80000174: // 1DMkII case 0x80000188: // 1DsMkII iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; iCanonFocalType = 45; break; case 0x80000232: // 1DMkII N iCanonCurFocal = 9; iCanonLensID = 12; iCanonMinFocal = 17; iCanonMaxFocal = 19; break; case 0x80000169: // 1DMkIII case 0x80000215: // 1DsMkIII iCanonCurFocal = 29; iCanonLensID = 273; iCanonMinFocal = 275; iCanonMaxFocal = 277; break; case 0x80000281: // 1DMkIV iCanonCurFocal = 30; iCanonLensID = 335; iCanonMinFocal = 337; iCanonMaxFocal = 339; break; case 0x80000269: // 1D X iCanonCurFocal = 35; iCanonLensID = 423; iCanonMinFocal = 425; iCanonMaxFocal = 427; break; case 0x80000213: // 5D iCanonCurFocal = 40; if (!sget2Rev(CameraInfo + 12)) iCanonLensID = 151; else iCanonLensID = 12; iCanonMinFocal = 147; iCanonMaxFocal = 149; break; case 0x80000218: // 5DMkII iCanonCurFocal = 30; iCanonLensID = 230; iCanonMinFocal = 232; iCanonMaxFocal = 234; break; case 0x80000285: // 5DMkIII iCanonCurFocal = 35; iCanonLensID = 339; iCanonMinFocal = 341; iCanonMaxFocal = 343; break; case 0x80000302: // 6D iCanonCurFocal = 35; iCanonLensID = 353; iCanonMinFocal = 355; iCanonMaxFocal = 357; break; case 0x80000250: // 7D iCanonCurFocal = 30; iCanonLensID = 274; iCanonMinFocal = 276; iCanonMaxFocal = 278; break; case 0x80000190: // 40D iCanonCurFocal = 29; iCanonLensID = 214; iCanonMinFocal = 216; iCanonMaxFocal = 218; iCanonLens = 2347; break; case 0x80000261: // 50D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000287: // 60D iCanonCurFocal = 30; iCanonLensID = 232; iCanonMinFocal = 234; iCanonMaxFocal = 236; break; case 0x80000325: // 70D iCanonCurFocal = 35; iCanonLensID = 358; iCanonMinFocal = 360; iCanonMaxFocal = 362; break; case 0x80000176: // 450D iCanonCurFocal = 29; iCanonLensID = 222; iCanonLens = 2355; break; case 0x80000252: // 500D iCanonCurFocal = 30; iCanonLensID = 246; iCanonMinFocal = 248; iCanonMaxFocal = 250; break; case 0x80000270: // 550D iCanonCurFocal = 30; iCanonLensID = 255; iCanonMinFocal = 257; iCanonMaxFocal = 259; break; case 0x80000286: // 600D case 0x80000288: // 1100D iCanonCurFocal = 30; iCanonLensID = 234; iCanonMinFocal = 236; iCanonMaxFocal = 238; break; case 0x80000301: // 650D case 0x80000326: // 700D iCanonCurFocal = 35; iCanonLensID = 295; iCanonMinFocal = 297; iCanonMaxFocal = 299; break; case 0x80000254: // 1000D iCanonCurFocal = 29; iCanonLensID = 226; iCanonMinFocal = 228; iCanonMaxFocal = 230; iCanonLens = 2359; break; } if (iCanonFocalType) { if (iCanonFocalType >= maxlen) return; // broken; imgdata.lens.makernotes.FocalType = CameraInfo[iCanonFocalType]; if (!imgdata.lens.makernotes.FocalType) // zero means 'fixed' here, replacing with standard '1' imgdata.lens.makernotes.FocalType = 1; } if (!imgdata.lens.makernotes.CurFocal) { if (iCanonCurFocal >= maxlen) return; // broken; imgdata.lens.makernotes.CurFocal = sget2Rev(CameraInfo + iCanonCurFocal); } if (!imgdata.lens.makernotes.LensID) { if (iCanonLensID >= maxlen) return; // broken; imgdata.lens.makernotes.LensID = sget2Rev(CameraInfo + iCanonLensID); } if (!imgdata.lens.makernotes.MinFocal) { if (iCanonMinFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MinFocal = sget2Rev(CameraInfo + iCanonMinFocal); } if (!imgdata.lens.makernotes.MaxFocal) { if (iCanonMaxFocal >= maxlen) return; // broken; imgdata.lens.makernotes.MaxFocal = sget2Rev(CameraInfo + iCanonMaxFocal); } if (!imgdata.lens.makernotes.Lens[0] && iCanonLens) { if (iCanonLens + 64 >= maxlen) return; // broken; if (CameraInfo[iCanonLens] < 65) // non-Canon lens { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 64); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-S", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-S ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "TS-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "TS-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "TS-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "MP-E", 4)) { memcpy(imgdata.lens.makernotes.Lens, "MP-E ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "MP-E", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else if (!strncmp((char *)CameraInfo + iCanonLens, "EF-M", 4)) { memcpy(imgdata.lens.makernotes.Lens, "EF-M ", 5); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF-M", 4); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; memcpy(imgdata.lens.makernotes.Lens + 5, CameraInfo + iCanonLens + 4, 60); } else { memcpy(imgdata.lens.makernotes.Lens, CameraInfo + iCanonLens, 2); memcpy(imgdata.lens.makernotes.LensFeatures_pre, "EF", 2); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; imgdata.lens.makernotes.Lens[2] = 32; memcpy(imgdata.lens.makernotes.Lens + 3, CameraInfo + iCanonLens + 2, 62); } } return; } void CLASS Canon_CameraSettings() { fseek(ifp, 10, SEEK_CUR); imgdata.shootinginfo.DriveMode = get2(); get2(); imgdata.shootinginfo.FocusMode = get2(); fseek(ifp, 18, SEEK_CUR); imgdata.shootinginfo.MeteringMode = get2(); get2(); imgdata.shootinginfo.AFPoint = get2(); imgdata.shootinginfo.ExposureMode = get2(); get2(); imgdata.lens.makernotes.LensID = get2(); imgdata.lens.makernotes.MaxFocal = get2(); imgdata.lens.makernotes.MinFocal = get2(); imgdata.lens.makernotes.CanonFocalUnits = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.MaxFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; imgdata.lens.makernotes.MinFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } imgdata.lens.makernotes.MaxAp = _CanonConvertAperture(get2()); imgdata.lens.makernotes.MinAp = _CanonConvertAperture(get2()); fseek(ifp, 12, SEEK_CUR); imgdata.shootinginfo.ImageStabilization = get2(); } void CLASS Canon_WBpresets(int skip1, int skip2) { int c; FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ (c >> 1)] = get2(); if (skip1) fseek(ifp, skip1, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c ^ (c >> 1)] = get2(); if (skip2) fseek(ifp, skip2, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ (c >> 1)] = get2(); return; } void CLASS Canon_WBCTpresets(short WBCTversion) { if (WBCTversion == 0) for (int i = 0; i < 15; i++) // tint, as shot R, as shot B, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if (WBCTversion == 1) for (int i = 0; i < 15; i++) // as shot R, as shot B, tint, CСT { imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(get2(), 1.f); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(get2(), 1.f); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x80000374) || // M3 (unique_id == 0x80000384) || // M10 (unique_id == 0x80000394) || // M5 (unique_id == 0x80000407) || // M6 (unique_id == 0x80000398) || // M100 (unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000))) // G1 X Mark III for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][3] = 1024.0f / fMAX(1.f, get2()); imgdata.color.WBCT_Coeffs[i][0] = get2(); } else if ((WBCTversion == 2) && ((unique_id == 0x03950000) || (unique_id == 0x03930000))) // G5 X, G9 X for (int i = 0; i < 15; i++) // tint, offset, as shot R, as shot B, CСT { fseek(ifp, 2, SEEK_CUR); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 1.0f; imgdata.color.WBCT_Coeffs[i][1] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][3] = (float)get2() / 512.0f; imgdata.color.WBCT_Coeffs[i][0] = get2(); } return; } void CLASS processNikonLensData(uchar *LensData, unsigned len) { ushort i; if (!(imgdata.lens.nikon.NikonLensType & 0x01)) { imgdata.lens.makernotes.LensFeatures_pre[0] = 'A'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } else { imgdata.lens.makernotes.LensFeatures_pre[0] = 'M'; imgdata.lens.makernotes.LensFeatures_pre[1] = 'F'; } if (imgdata.lens.nikon.NikonLensType & 0x02) { if (imgdata.lens.nikon.NikonLensType & 0x04) imgdata.lens.makernotes.LensFeatures_suf[0] = 'G'; else imgdata.lens.makernotes.LensFeatures_suf[0] = 'D'; imgdata.lens.makernotes.LensFeatures_suf[1] = ' '; } if (imgdata.lens.nikon.NikonLensType & 0x08) { imgdata.lens.makernotes.LensFeatures_suf[2] = 'V'; imgdata.lens.makernotes.LensFeatures_suf[3] = 'R'; } if (imgdata.lens.nikon.NikonLensType & 0x10) { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_1INCH; } else imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_F; if (imgdata.lens.nikon.NikonLensType & 0x20) { strcpy(imgdata.lens.makernotes.Adapter, "FT-1"); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Nikon_F; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Nikon_CX; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } imgdata.lens.nikon.NikonLensType = imgdata.lens.nikon.NikonLensType & 0xdf; if (len < 20) { switch (len) { case 9: i = 2; break; case 15: i = 7; break; case 16: i = 8; break; } imgdata.lens.nikon.NikonLensIDNumber = LensData[i]; imgdata.lens.nikon.NikonLensFStops = LensData[i + 1]; imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; if (fabsf(imgdata.lens.makernotes.MinFocal) < 1.1f) { if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 2]) imgdata.lens.makernotes.MinFocal = 5.0f * powf64(2.0f, (float)LensData[i + 2] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 3]) imgdata.lens.makernotes.MaxFocal = 5.0f * powf64(2.0f, (float)LensData[i + 3] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 4]) imgdata.lens.makernotes.MaxAp4MinFocal = powf64(2.0f, (float)LensData[i + 4] / 24.0f); if ((imgdata.lens.nikon.NikonLensType ^ (uchar)0x01) || LensData[i + 5]) imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(2.0f, (float)LensData[i + 5] / 24.0f); } imgdata.lens.nikon.NikonMCUVersion = LensData[i + 6]; if (i != 2) { if ((LensData[i - 1]) && (fabsf(imgdata.lens.makernotes.CurFocal) < 1.1f)) imgdata.lens.makernotes.CurFocal = 5.0f * powf64(2.0f, (float)LensData[i - 1] / 24.0f); if (LensData[i + 7]) imgdata.lens.nikon.NikonEffectiveMaxAp = powf64(2.0f, (float)LensData[i + 7] / 24.0f); } imgdata.lens.makernotes.LensID = (unsigned long long)LensData[i] << 56 | (unsigned long long)LensData[i + 1] << 48 | (unsigned long long)LensData[i + 2] << 40 | (unsigned long long)LensData[i + 3] << 32 | (unsigned long long)LensData[i + 4] << 24 | (unsigned long long)LensData[i + 5] << 16 | (unsigned long long)LensData[i + 6] << 8 | (unsigned long long)imgdata.lens.nikon.NikonLensType; } else if ((len == 459) || (len == 590)) { memcpy(imgdata.lens.makernotes.Lens, LensData + 390, 64); } else if (len == 509) { memcpy(imgdata.lens.makernotes.Lens, LensData + 391, 64); } else if (len == 879) { memcpy(imgdata.lens.makernotes.Lens, LensData + 680, 64); } return; } void CLASS setOlympusBodyFeatures(unsigned long long id) { imgdata.lens.makernotes.CamID = id; if (id == 0x5330303638ULL) { strcpy (model, "E-M10MarkIII"); } if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-300 ((id & 0x00ffff0000ULL) == 0x0030300000ULL)) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FT; if ((id == 0x4434303430ULL) || // E-1 (id == 0x4434303431ULL) || // E-330 ((id >= 0x5330303033ULL) && (id <= 0x5330303138ULL)) || // E-330 to E-520 (id == 0x5330303233ULL) || // E-620 (id == 0x5330303239ULL) || // E-450 (id == 0x5330303330ULL) || // E-600 (id == 0x5330303333ULL)) // E-5 { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FT; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_mFT; } } else { imgdata.lens.makernotes.LensMount = imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS parseCanonMakernotes(unsigned tag, unsigned type, unsigned len) { if (tag == 0x0001) Canon_CameraSettings(); else if (tag == 0x0002) // focal length { imgdata.lens.makernotes.FocalType = get2(); imgdata.lens.makernotes.CurFocal = get2(); if (imgdata.lens.makernotes.CanonFocalUnits > 1) { imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } } else if (tag == 0x0004) // shot info { short tempAp; fseek(ifp, 24, SEEK_CUR); tempAp = get2(); if (tempAp != 0) imgdata.other.CameraTemperature = (float)(tempAp-128); tempAp = get2(); if (tempAp != -1) imgdata.other.FlashGN = ((float)tempAp) / 32; get2(); // fseek(ifp, 30, SEEK_CUR); imgdata.other.FlashEC = _CanonConvertEV((signed short)get2()); fseek(ifp, 8 - 32, SEEK_CUR); if ((tempAp = get2()) != 0x7fff) imgdata.lens.makernotes.CurAp = _CanonConvertAperture(tempAp); if (imgdata.lens.makernotes.CurAp < 0.7f) { fseek(ifp, 32, SEEK_CUR); imgdata.lens.makernotes.CurAp = _CanonConvertAperture(get2()); } if (!aperture) aperture = imgdata.lens.makernotes.CurAp; } else if (tag == 0x0095 && // lens model tag !imgdata.lens.makernotes.Lens[0]) { fread(imgdata.lens.makernotes.Lens, 2, 1, ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; if (imgdata.lens.makernotes.Lens[0] < 65) // non-Canon lens fread(imgdata.lens.makernotes.Lens + 2, 62, 1, ifp); else { char efs[2]; imgdata.lens.makernotes.LensFeatures_pre[0] = imgdata.lens.makernotes.Lens[0]; imgdata.lens.makernotes.LensFeatures_pre[1] = imgdata.lens.makernotes.Lens[1]; fread(efs, 2, 1, ifp); if (efs[0] == 45 && (efs[1] == 83 || efs[1] == 69 || efs[1] == 77)) { // "EF-S, TS-E, MP-E, EF-M" lenses imgdata.lens.makernotes.Lens[2] = imgdata.lens.makernotes.LensFeatures_pre[2] = efs[0]; imgdata.lens.makernotes.Lens[3] = imgdata.lens.makernotes.LensFeatures_pre[3] = efs[1]; imgdata.lens.makernotes.Lens[4] = 32; if (efs[1] == 83) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_S; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } else if (efs[1] == 77) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF_M; } } else { // "EF" lenses imgdata.lens.makernotes.Lens[2] = 32; imgdata.lens.makernotes.Lens[3] = efs[0]; imgdata.lens.makernotes.Lens[4] = efs[1]; } fread(imgdata.lens.makernotes.Lens + 5, 58, 1, ifp); } } else if (tag == 0x00a9) { long int save1 = ftell(ifp); int c; fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, save1, SEEK_SET); } else if (tag == 0x00e0) // sensor info { imgdata.makernotes.canon.SensorWidth = (get2(), get2()); imgdata.makernotes.canon.SensorHeight = get2(); imgdata.makernotes.canon.SensorLeftBorder = (get2(), get2(), get2()); imgdata.makernotes.canon.SensorTopBorder = get2(); imgdata.makernotes.canon.SensorRightBorder = get2(); imgdata.makernotes.canon.SensorBottomBorder = get2(); imgdata.makernotes.canon.BlackMaskLeftBorder = get2(); imgdata.makernotes.canon.BlackMaskTopBorder = get2(); imgdata.makernotes.canon.BlackMaskRightBorder = get2(); imgdata.makernotes.canon.BlackMaskBottomBorder = get2(); } else if (tag == 0x4001 && len > 500) { int c; long int save1 = ftell(ifp); switch (len) { case 582: imgdata.makernotes.canon.CanonColorDataVer = 1; // 20D / 350D { fseek(ifp, save1 + (0x1e << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x41 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x46 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x23 << 1), SEEK_SET); Canon_WBpresets(2, 2); fseek(ifp, save1 + (0x4b << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 653: imgdata.makernotes.canon.CanonColorDataVer = 2; // 1Dmk2 / 1DsMK2 { fseek(ifp, save1 + (0x18 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x90 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x95 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x9a << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x27 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa4 << 1), SEEK_SET); Canon_WBCTpresets(1); // ABCT } break; case 796: imgdata.makernotes.canon.CanonColorDataVer = 3; // 1DmkIIN / 5D / 30D / 400D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x71 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x76 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom2][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x7b << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom3][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x4e << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0c4 << 1), SEEK_SET); // offset 196 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; // 1DmkIII / 1DSmkIII / 1DmkIV / 5DmkII // 7D / 40D / 50D / 60D / 450D / 500D // 550D / 1000D / 1100D case 674: case 692: case 702: case 1227: case 1250: case 1251: case 1337: case 1338: case 1346: imgdata.makernotes.canon.CanonColorDataVer = 4; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x53 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xa8 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0e7 << 1), SEEK_SET); // offset 231 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if ((imgdata.makernotes.canon.CanonColorDataSubVer == 4) || (imgdata.makernotes.canon.CanonColorDataSubVer == 5)) { fseek(ifp, save1 + (0x2b9 << 1), SEEK_SET); // offset 697 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if ((imgdata.makernotes.canon.CanonColorDataSubVer == 6) || (imgdata.makernotes.canon.CanonColorDataSubVer == 7)) { fseek(ifp, save1 + (0x2d0 << 1), SEEK_SET); // offset 720 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 9) { fseek(ifp, save1 + (0x2d4 << 1), SEEK_SET); // offset 724 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; case 5120: imgdata.makernotes.canon.CanonColorDataVer = 5; // PowerSot G10, G12, G5 X, G7 X, G9 X, EOS M3, EOS M5, EOS M6 { if ((unique_id == 0x03970000) || // G7 X Mark II (unique_id == 0x04100000) || // G9 X Mark II (unique_id == 0x04180000) || // G1 X Mark III (unique_id == 0x80000394) || // EOS M5 (unique_id == 0x80000398) || // EOS M100 (unique_id == 0x80000407)) // EOS M6 { fseek(ifp, save1 + (0x4f << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); fseek(ifp, 8, SEEK_CUR); Canon_WBpresets(8, 24); fseek(ifp, 168, SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ (c >> 1)] = get2(); fseek(ifp, 24, SEEK_CUR); Canon_WBCTpresets(2); // BCADT fseek(ifp, 6, SEEK_CUR); } else { fseek(ifp, save1 + (0x4c << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); get2(); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Other][c ^ (c >> 1)] = get2(); get2(); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xba << 1), SEEK_SET); Canon_WBCTpresets(2); // BCADT fseek(ifp, save1 + (0x108 << 1), SEEK_SET); // offset 264 short } int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } break; case 1273: case 1275: imgdata.makernotes.canon.CanonColorDataVer = 6; // 600D / 1200D imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x67 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xbc << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x0fb << 1), SEEK_SET); // offset 251 short int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } fseek(ifp, save1 + (0x1e4 << 1), SEEK_SET); // offset 484 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; break; // 1DX / 5DmkIII / 6D / 100D / 650D / 700D / EOS M / 7DmkII / 750D / 760D case 1312: case 1313: case 1316: case 1506: imgdata.makernotes.canon.CanonColorDataVer = 7; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x80 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0xd5 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x114 << 1), SEEK_SET); // offset 276 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 10) { fseek(ifp, save1 + (0x1fd << 1), SEEK_SET); // offset 509 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else if (imgdata.makernotes.canon.CanonColorDataSubVer == 11) { fseek(ifp, save1 + (0x2dd << 1), SEEK_SET); // offset 733 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; // 5DS / 5DS R / 80D / 1300D / 5D4 / 800D / 77D / 6D II / 200D case 1560: case 1592: case 1353: case 1602: imgdata.makernotes.canon.CanonColorDataVer = 8; imgdata.makernotes.canon.CanonColorDataSubVer = get2(); { fseek(ifp, save1 + (0x44 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x49 << 1), SEEK_SET); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Measured][c ^ (c >> 1)] = get2(); fseek(ifp, save1 + (0x85 << 1), SEEK_SET); Canon_WBpresets(2, 12); fseek(ifp, save1 + (0x107 << 1), SEEK_SET); Canon_WBCTpresets(0); // BCAT fseek(ifp, save1 + (0x146 << 1), SEEK_SET); // offset 326 shorts int bls = 0; FORC4 bls += (imgdata.makernotes.canon.ChannelBlackLevel[c] = get2()); imgdata.makernotes.canon.AverageBlackLevel = bls / 4; } if (imgdata.makernotes.canon.CanonColorDataSubVer == 14) // 1300D { fseek(ifp, save1 + (0x231 << 1), SEEK_SET); imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } else { fseek(ifp, save1 + (0x30f << 1), SEEK_SET); // offset 783 shorts imgdata.makernotes.canon.SpecularWhiteLevel = get2(); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.canon.SpecularWhiteLevel; } break; } fseek(ifp, save1, SEEK_SET); } } void CLASS setPentaxBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; switch (id) { case 0x12994: case 0x12aa2: case 0x12b1a: case 0x12b60: case 0x12b62: case 0x12b7e: case 0x12b80: case 0x12b9c: case 0x12b9d: case 0x12ba2: case 0x12c1e: case 0x12c20: case 0x12cd2: case 0x12cd4: case 0x12cfa: case 0x12d72: case 0x12d73: case 0x12db8: case 0x12dfe: case 0x12e6c: case 0x12e76: case 0x12ef8: case 0x12f52: case 0x12f70: case 0x12f71: case 0x12fb6: case 0x12fc0: case 0x12fca: case 0x1301a: case 0x13024: case 0x1309c: case 0x13222: case 0x1322c: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; break; case 0x13092: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_K; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; break; case 0x12e08: case 0x13010: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_MF; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_645; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_MF; break; case 0x12ee4: case 0x12f66: case 0x12f7a: case 0x1302e: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Pentax_Q; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Pentax_Q; break; default: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } return; } void CLASS PentaxISO(ushort c) { int code[] = {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, 50, 100, 200, 400, 800, 1600, 3200, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278}; double value[] = {50, 64, 80, 100, 125, 160, 200, 250, 320, 400, 500, 640, 800, 1000, 1250, 1600, 2000, 2500, 3200, 4000, 5000, 6400, 8000, 10000, 12800, 16000, 20000, 25600, 32000, 40000, 51200, 64000, 80000, 102400, 128000, 160000, 204800, 258000, 325000, 409600, 516000, 650000, 819200, 50, 100, 200, 400, 800, 1600, 3200, 50, 70, 100, 140, 200, 280, 400, 560, 800, 1100, 1600, 2200, 3200, 4500, 6400, 9000, 12800, 18000, 25600, 36000, 51200}; #define numel (sizeof(code) / sizeof(code[0])) int i; for (i = 0; i < numel; i++) { if (code[i] == c) { iso_speed = value[i]; return; } } if (i == numel) iso_speed = 65535.0f; } #undef numel void CLASS PentaxLensInfo(unsigned id, unsigned len) // tag 0x0207 { ushort iLensData = 0; uchar *table_buf; table_buf = (uchar *)malloc(MAX(len, 128)); fread(table_buf, len, 1, ifp); if ((id < 0x12b9c) || (((id == 0x12b9c) || // K100D (id == 0x12b9d) || // K110D (id == 0x12ba2)) && // K100D Super ((!table_buf[20] || (table_buf[20] == 0xff))))) { iLensData = 3; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = (((unsigned)table_buf[0]) << 8) + table_buf[1]; } else switch (len) { case 90: // LensInfo3 iLensData = 13; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 91: // LensInfo4 iLensData = 12; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[3]) << 8) + table_buf[4]; break; case 80: // LensInfo5 case 128: iLensData = 15; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[1] & 0x0f) + table_buf[4]) << 8) + table_buf[5]; break; default: if (id >= 0x12b9c) // LensInfo2 { iLensData = 4; if (imgdata.lens.makernotes.LensID == -1) imgdata.lens.makernotes.LensID = ((unsigned)((table_buf[0] & 0x0f) + table_buf[2]) << 8) + table_buf[3]; } } if (iLensData) { if (table_buf[iLensData + 9] && (fabs(imgdata.lens.makernotes.CurFocal) < 0.1f)) imgdata.lens.makernotes.CurFocal = 10 * (table_buf[iLensData + 9] >> 2) * powf64(4, (table_buf[iLensData + 9] & 0x03) - 2); if (table_buf[iLensData + 10] & 0xf0) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0xf0) >> 4) / 4.0f); if (table_buf[iLensData + 10] & 0x0f) imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 10] & 0x0f) + 10) / 4.0f); if (iLensData != 12) { switch (table_buf[iLensData] & 0x06) { case 0: imgdata.lens.makernotes.MinAp4MinFocal = 22.0f; break; case 2: imgdata.lens.makernotes.MinAp4MinFocal = 32.0f; break; case 4: imgdata.lens.makernotes.MinAp4MinFocal = 45.0f; break; case 6: imgdata.lens.makernotes.MinAp4MinFocal = 16.0f; break; } if (table_buf[iLensData] & 0x70) imgdata.lens.makernotes.LensFStops = ((float)(((table_buf[iLensData] & 0x70) >> 4) ^ 0x07)) / 2.0f + 5.0f; imgdata.lens.makernotes.MinFocusDistance = (float)(table_buf[iLensData + 3] & 0xf8); imgdata.lens.makernotes.FocusRangeIndex = (float)(table_buf[iLensData + 3] & 0x07); if ((table_buf[iLensData + 14] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 14] & 0x7f) - 1) / 32.0f); } else if ((id != 0x12e76) && // K-5 (table_buf[iLensData + 15] > 1) && (fabs(imgdata.lens.makernotes.MaxAp4CurFocal) < 0.7f)) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (float)((table_buf[iLensData + 15] & 0x7f) - 1) / 32.0f); } } free(table_buf); return; } void CLASS setPhaseOneFeatures(unsigned id) { ushort i; static const struct { ushort id; char t_model[32]; } p1_unique[] = { // Phase One section: {1, "Hasselblad V"}, {10, "PhaseOne/Mamiya"}, {12, "Contax 645"}, {16, "Hasselblad V"}, {17, "Hasselblad V"}, {18, "Contax 645"}, {19, "PhaseOne/Mamiya"}, {20, "Hasselblad V"}, {21, "Contax 645"}, {22, "PhaseOne/Mamiya"}, {23, "Hasselblad V"}, {24, "Hasselblad H"}, {25, "PhaseOne/Mamiya"}, {32, "Contax 645"}, {34, "Hasselblad V"}, {35, "Hasselblad V"}, {36, "Hasselblad H"}, {37, "Contax 645"}, {38, "PhaseOne/Mamiya"}, {39, "Hasselblad V"}, {40, "Hasselblad H"}, {41, "Contax 645"}, {42, "PhaseOne/Mamiya"}, {44, "Hasselblad V"}, {45, "Hasselblad H"}, {46, "Contax 645"}, {47, "PhaseOne/Mamiya"}, {48, "Hasselblad V"}, {49, "Hasselblad H"}, {50, "Contax 645"}, {51, "PhaseOne/Mamiya"}, {52, "Hasselblad V"}, {53, "Hasselblad H"}, {54, "Contax 645"}, {55, "PhaseOne/Mamiya"}, {67, "Hasselblad V"}, {68, "Hasselblad H"}, {69, "Contax 645"}, {70, "PhaseOne/Mamiya"}, {71, "Hasselblad V"}, {72, "Hasselblad H"}, {73, "Contax 645"}, {74, "PhaseOne/Mamiya"}, {76, "Hasselblad V"}, {77, "Hasselblad H"}, {78, "Contax 645"}, {79, "PhaseOne/Mamiya"}, {80, "Hasselblad V"}, {81, "Hasselblad H"}, {82, "Contax 645"}, {83, "PhaseOne/Mamiya"}, {84, "Hasselblad V"}, {85, "Hasselblad H"}, {86, "Contax 645"}, {87, "PhaseOne/Mamiya"}, {99, "Hasselblad V"}, {100, "Hasselblad H"}, {101, "Contax 645"}, {102, "PhaseOne/Mamiya"}, {103, "Hasselblad V"}, {104, "Hasselblad H"}, {105, "PhaseOne/Mamiya"}, {106, "Contax 645"}, {112, "Hasselblad V"}, {113, "Hasselblad H"}, {114, "Contax 645"}, {115, "PhaseOne/Mamiya"}, {131, "Hasselblad V"}, {132, "Hasselblad H"}, {133, "Contax 645"}, {134, "PhaseOne/Mamiya"}, {135, "Hasselblad V"}, {136, "Hasselblad H"}, {137, "Contax 645"}, {138, "PhaseOne/Mamiya"}, {140, "Hasselblad V"}, {141, "Hasselblad H"}, {142, "Contax 645"}, {143, "PhaseOne/Mamiya"}, {148, "Hasselblad V"}, {149, "Hasselblad H"}, {150, "Contax 645"}, {151, "PhaseOne/Mamiya"}, {160, "A-250"}, {161, "A-260"}, {162, "A-280"}, {167, "Hasselblad V"}, {168, "Hasselblad H"}, {169, "Contax 645"}, {170, "PhaseOne/Mamiya"}, {172, "Hasselblad V"}, {173, "Hasselblad H"}, {174, "Contax 645"}, {175, "PhaseOne/Mamiya"}, {176, "Hasselblad V"}, {177, "Hasselblad H"}, {178, "Contax 645"}, {179, "PhaseOne/Mamiya"}, {180, "Hasselblad V"}, {181, "Hasselblad H"}, {182, "Contax 645"}, {183, "PhaseOne/Mamiya"}, {208, "Hasselblad V"}, {211, "PhaseOne/Mamiya"}, {448, "Phase One 645AF"}, {457, "Phase One 645DF"}, {471, "Phase One 645DF+"}, {704, "Phase One iXA"}, {705, "Phase One iXA - R"}, {706, "Phase One iXU 150"}, {707, "Phase One iXU 150 - NIR"}, {708, "Phase One iXU 180"}, {721, "Phase One iXR"}, // Leaf section: {333, "Mamiya"}, {329, "Universal"}, {330, "Hasselblad H1/H2"}, {332, "Contax"}, {336, "AFi"}, {327, "Mamiya"}, {324, "Universal"}, {325, "Hasselblad H1/H2"}, {326, "Contax"}, {335, "AFi"}, {340, "Mamiya"}, {337, "Universal"}, {338, "Hasselblad H1/H2"}, {339, "Contax"}, {323, "Mamiya"}, {320, "Universal"}, {322, "Hasselblad H1/H2"}, {321, "Contax"}, {334, "AFi"}, {369, "Universal"}, {370, "Mamiya"}, {371, "Hasselblad H1/H2"}, {372, "Contax"}, {373, "Afi"}, }; imgdata.lens.makernotes.CamID = id; if (id && !imgdata.lens.makernotes.body[0]) { for (i = 0; i < sizeof p1_unique / sizeof *p1_unique; i++) if (id == p1_unique[i].id) { strcpy(imgdata.lens.makernotes.body, p1_unique[i].t_model); } } return; } void CLASS parseFujiMakernotes(unsigned tag, unsigned type) { switch (tag) { case 0x1002: imgdata.makernotes.fuji.WB_Preset = get2(); break; case 0x1011: imgdata.other.FlashEC = getreal(type); break; case 0x1020: imgdata.makernotes.fuji.Macro = get2(); break; case 0x1021: imgdata.makernotes.fuji.FocusMode = get2(); break; case 0x1022: imgdata.makernotes.fuji.AFMode = get2(); break; case 0x1023: imgdata.makernotes.fuji.FocusPixel[0] = get2(); imgdata.makernotes.fuji.FocusPixel[1] = get2(); break; case 0x1034: imgdata.makernotes.fuji.ExrMode = get2(); break; case 0x1050: imgdata.makernotes.fuji.ShutterType = get2(); break; case 0x1400: imgdata.makernotes.fuji.FujiDynamicRange = get2(); break; case 0x1401: imgdata.makernotes.fuji.FujiFilmMode = get2(); break; case 0x1402: imgdata.makernotes.fuji.FujiDynamicRangeSetting = get2(); break; case 0x1403: imgdata.makernotes.fuji.FujiDevelopmentDynamicRange = get2(); break; case 0x140b: imgdata.makernotes.fuji.FujiAutoDynamicRange = get2(); break; case 0x1404: imgdata.lens.makernotes.MinFocal = getreal(type); break; case 0x1405: imgdata.lens.makernotes.MaxFocal = getreal(type); break; case 0x1406: imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); break; case 0x1407: imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); break; case 0x1422: imgdata.makernotes.fuji.ImageStabilization[0] = get2(); imgdata.makernotes.fuji.ImageStabilization[1] = get2(); imgdata.makernotes.fuji.ImageStabilization[2] = get2(); imgdata.shootinginfo.ImageStabilization = (imgdata.makernotes.fuji.ImageStabilization[0] << 9) + imgdata.makernotes.fuji.ImageStabilization[1]; break; case 0x1431: imgdata.makernotes.fuji.Rating = get4(); break; case 0x3820: imgdata.makernotes.fuji.FrameRate = get2(); break; case 0x3821: imgdata.makernotes.fuji.FrameWidth = get2(); break; case 0x3822: imgdata.makernotes.fuji.FrameHeight = get2(); break; } return; } void CLASS setSonyBodyFeatures(unsigned id) { imgdata.lens.makernotes.CamID = id; if ( // FF cameras (id == 257) || // a900 (id == 269) || // a850 (id == 340) || // ILCE-7M2 (id == 318) || // ILCE-7S (id == 350) || // ILCE-7SM2 (id == 311) || // ILCE-7R (id == 347) || // ILCE-7RM2 (id == 306) || // ILCE-7 (id == 298) || // DSC-RX1 (id == 299) || // NEX-VG900 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 354) || // ILCA-99M2 (id == 358) || // ILCE-9 (id == 362) || // ILCE-7RM3 (id == 294) // SLT-99, Hasselblad HV ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } else if ((id == 297) || // DSC-RX100 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_1INCH; } else if (id != 002) // DSC-R1 { imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; } if ( // E-mount cameras, ILCE series (id == 302) || (id == 306) || (id == 311) || (id == 312) || (id == 313) || (id == 318) || (id == 339) || (id == 340) || (id == 346) || (id == 347) || (id == 350) || (id == 358) || (id == 360) || (id == 362)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCE; } else if ( // E-mount cameras, NEX series (id == 278) || (id == 279) || (id == 284) || (id == 288) || (id == 289) || (id == 290) || (id == 293) || (id == 295) || (id == 296) || (id == 299) || (id == 300) || (id == 305) || (id == 307)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Sony_E; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_NEX; } else if ( // A-mount cameras, DSLR series (id == 256) || (id == 257) || (id == 258) || (id == 259) || (id == 260) || (id == 261) || (id == 262) || (id == 263) || (id == 264) || (id == 265) || (id == 266) || (id == 269) || (id == 270) || (id == 273) || (id == 274) || (id == 275) || (id == 282) || (id == 283)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSLR; } else if ( // A-mount cameras, SLT series (id == 280) || (id == 281) || (id == 285) || (id == 286) || (id == 287) || (id == 291) || (id == 292) || (id == 294) || (id == 303)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_SLT; } else if ( // A-mount cameras, ILCA series (id == 319) || (id == 353) || (id == 354)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_ILCA; } else if ( // DSC (id == 002) || // DSC-R1 (id == 297) || // DSC-RX100 (id == 298) || // DSC-RX1 (id == 308) || // DSC-RX100M2 (id == 309) || // DSC-RX10 (id == 310) || // DSC-RX1R (id == 344) || // DSC-RX1RM2 (id == 317) || // DSC-RX100M3 (id == 341) || // DSC-RX100M4 (id == 342) || // DSC-RX10M2 (id == 355) || // DSC-RX10M3 (id == 356) || // DSC-RX100M5 (id == 364) || // DSC-RX0 (id == 365) // DSC-RX10M4 ) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.makernotes.sony.SonyCameraType = LIBRAW_SONY_DSC; } return; } void CLASS parseSonyLensType2(uchar a, uchar b) { ushort lid2; lid2 = (((ushort)a) << 8) | ((ushort)b); if (!lid2) return; if (lid2 < 0x100) { if ((imgdata.lens.makernotes.AdapterID != 0x4900) && (imgdata.lens.makernotes.AdapterID != 0xEF00)) { imgdata.lens.makernotes.AdapterID = lid2; switch (lid2) { case 1: case 2: case 3: case 6: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 44: case 78: case 239: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; break; } } } else imgdata.lens.makernotes.LensID = lid2; if ((lid2 >= 50481) && (lid2 < 50500)) { strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); imgdata.lens.makernotes.AdapterID = 0x4900; } return; } #define strnXcat(buf, string) strncat(buf, string, LIM(sizeof(buf) - strbuflen(buf) - 1, 0, sizeof(buf))) void CLASS parseSonyLensFeatures(uchar a, uchar b) { ushort features; features = (((ushort)a) << 8) | ((ushort)b); if ((imgdata.lens.makernotes.LensMount == LIBRAW_MOUNT_Canon_EF) || (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F) || !features) return; imgdata.lens.makernotes.LensFeatures_pre[0] = 0; imgdata.lens.makernotes.LensFeatures_suf[0] = 0; if ((features & 0x0200) && (features & 0x0100)) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "E"); else if (features & 0x0200) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "FE"); else if (features & 0x0100) strcpy(imgdata.lens.makernotes.LensFeatures_pre, "DT"); if (!imgdata.lens.makernotes.LensFormat && !imgdata.lens.makernotes.LensMount) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FF; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; if ((features & 0x0200) && (features & 0x0100)) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0200) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; } else if (features & 0x0100) { imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_APSC; } } if (features & 0x4000) strnXcat(imgdata.lens.makernotes.LensFeatures_pre, " PZ"); if (features & 0x0008) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " G"); else if (features & 0x0004) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " ZA"); if ((features & 0x0020) && (features & 0x0040)) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Macro"); else if (features & 0x0020) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " STF"); else if (features & 0x0040) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Reflex"); else if (features & 0x0080) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " Fisheye"); if (features & 0x0001) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SSM"); else if (features & 0x0002) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " SAM"); if (features & 0x8000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " OSS"); if (features & 0x2000) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " LE"); if (features & 0x0800) strnXcat(imgdata.lens.makernotes.LensFeatures_suf, " II"); if (imgdata.lens.makernotes.LensFeatures_suf[0] == ' ') memmove(imgdata.lens.makernotes.LensFeatures_suf, imgdata.lens.makernotes.LensFeatures_suf + 1, strbuflen(imgdata.lens.makernotes.LensFeatures_suf) - 1); return; } #undef strnXcat void CLASS process_Sony_0x0116(uchar *buf, unsigned id) { if ((id == 257) || (id == 262) || (id == 269) || (id == 270)) imgdata.other.BatteryTemperature = (float) (buf[1]-32) / 1.8f; else if ((id != 263) && (id != 264) && (id != 265) && (id != 266)) imgdata.other.BatteryTemperature = (float) (buf[2]-32) / 1.8f; return; } void CLASS process_Sony_0x9402(uchar *buf) { if (buf[2] != 0xff) return; short bufx = SonySubstitution[buf[0]]; if ((bufx < 0x0f) || (bufx > 0x1a) || (bufx == 0x16) || (bufx == 0x18)) return; imgdata.other.AmbientTemperature = (float) ((short) SonySubstitution[buf[4]]); return; } void CLASS process_Sony_0x9403(uchar *buf) { short bufx = SonySubstitution[buf[4]]; if ((bufx == 0x00) || (bufx == 0x94)) return; imgdata.other.SensorTemperature = (float) ((short) SonySubstitution[buf[5]]); return; } void CLASS process_Sony_0x9406(uchar *buf) { short bufx = SonySubstitution[buf[0]]; if ((bufx != 0x00) && (bufx == 0x01) && (bufx == 0x03)) return; bufx = SonySubstitution[buf[2]]; if ((bufx != 0x02) && (bufx == 0x03)) return; imgdata.other.BatteryTemperature = (float) (SonySubstitution[buf[5]]-32) / 1.8f; return; } void CLASS process_Sony_0x940c(uchar *buf) { ushort lid2; if ((imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) { switch (SonySubstitution[buf[0x0008]]) { case 1: case 5: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 4: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } lid2 = (((ushort)SonySubstitution[buf[0x000a]]) << 8) | ((ushort)SonySubstitution[buf[0x0009]]); if ((lid2 > 0) && (lid2 < 32784)) parseSonyLensType2(SonySubstitution[buf[0x000a]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0009]]); return; } void CLASS process_Sony_0x9050(uchar *buf, unsigned id) { ushort lid; if ((imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_Sony_E) && (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens)) { if (buf[0]) imgdata.lens.makernotes.MaxAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[0]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; if (buf[1]) imgdata.lens.makernotes.MinAp4CurFocal = my_roundf(powf64(2.0f, ((float)SonySubstitution[buf[1]] / 8.0 - 1.06f) / 2.0f) * 10.0f) / 10.0f; } if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) { if (buf[0x3d] | buf[0x3c]) { lid = SonySubstitution[buf[0x3d]] << 8 | SonySubstitution[buf[0x3c]]; imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 256.0f - 16.0f) / 2.0f); } if (buf[0x105] && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) && (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Sigma_X3F)) imgdata.lens.makernotes.LensMount = SonySubstitution[buf[0x105]]; if (buf[0x106]) imgdata.lens.makernotes.LensFormat = SonySubstitution[buf[0x106]]; } if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { parseSonyLensType2(SonySubstitution[buf[0x0108]], // LensType2 - Sony lens ids SonySubstitution[buf[0x0107]]); } if ((imgdata.lens.makernotes.LensID == -1) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (buf[0x010a] | buf[0x0109])) { imgdata.lens.makernotes.LensID = // LensType - Minolta/Sony lens ids SonySubstitution[buf[0x010a]] << 8 | SonySubstitution[buf[0x0109]]; if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } } if ((id >= 286) && (id <= 293)) // "SLT-A65", "SLT-A77", "NEX-7", "NEX-VG20E", // "SLT-A37", "SLT-A57", "NEX-F3", "Lunar" parseSonyLensFeatures(SonySubstitution[buf[0x115]], SonySubstitution[buf[0x116]]); else if (imgdata.lens.makernotes.CameraMount != LIBRAW_MOUNT_FixedLens) parseSonyLensFeatures(SonySubstitution[buf[0x116]], SonySubstitution[buf[0x117]]); if ((id == 347) || (id == 350) || (id == 357)) { unsigned long long b88 = SonySubstitution[buf[0x88]]; unsigned long long b89 = SonySubstitution[buf[0x89]]; unsigned long long b8a = SonySubstitution[buf[0x8a]]; unsigned long long b8b = SonySubstitution[buf[0x8b]]; unsigned long long b8c = SonySubstitution[buf[0x8c]]; unsigned long long b8d = SonySubstitution[buf[0x8d]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%06llx", (b88 << 40) + (b89 << 32) + (b8a << 24) + (b8b << 16) + (b8c << 8) + b8d); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Minolta_A) && (id > 279) && (id != 282) && (id != 283)) { unsigned long long bf0 = SonySubstitution[buf[0xf0]]; unsigned long long bf1 = SonySubstitution[buf[0xf1]]; unsigned long long bf2 = SonySubstitution[buf[0xf2]]; unsigned long long bf3 = SonySubstitution[buf[0xf3]]; unsigned long long bf4 = SonySubstitution[buf[0xf4]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%05llx", (bf0 << 32) + (bf1 << 24) + (bf2 << 16) + (bf3 << 8) + bf4); } else if ((imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) && (id != 288) && (id != 289) && (id != 290)) { unsigned b7c = SonySubstitution[buf[0x7c]]; unsigned b7d = SonySubstitution[buf[0x7d]]; unsigned b7e = SonySubstitution[buf[0x7e]]; unsigned b7f = SonySubstitution[buf[0x7f]]; sprintf(imgdata.shootinginfo.InternalBodySerial, "%04x", (b7c << 24) + (b7d << 16) + (b7e << 8) + b7f); } return; } void CLASS parseSonyMakernotes(unsigned tag, unsigned type, unsigned len, unsigned dng_writer, uchar *&table_buf_0x9050, ushort &table_buf_0x9050_present, uchar *&table_buf_0x940c, ushort &table_buf_0x940c_present, uchar *&table_buf_0x0116, ushort &table_buf_0x0116_present, uchar *&table_buf_0x9402, ushort &table_buf_0x9402_present, uchar *&table_buf_0x9403, ushort &table_buf_0x9403_present, uchar *&table_buf_0x9406, ushort &table_buf_0x9406_present) { ushort lid; uchar *table_buf; if (tag == 0xb001) // Sony ModelID { unique_id = get2(); setSonyBodyFeatures(unique_id); if (table_buf_0x0116_present) { process_Sony_0x0116(table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } if (table_buf_0x9050_present) { process_Sony_0x9050(table_buf_0x9050, unique_id); free(table_buf_0x9050); table_buf_0x9050_present = 0; } if (table_buf_0x9402_present) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } if (table_buf_0x9403_present) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } if (table_buf_0x9406_present) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } if (table_buf_0x940c_present) { if (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E) { process_Sony_0x940c(table_buf_0x940c); } free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if ((tag == 0x0010) && // CameraInfo strncasecmp(model, "DSLR-A100", 9) && strncasecmp(model, "NEX-5C", 6) && !strncasecmp(make, "SONY", 4) && ((len == 368) || // a700 (len == 5478) || // a850, a900 (len == 5506) || // a200, a300, a350 (len == 6118) || // a230, a290, a330, a380, a390 // a450, a500, a550, a560, a580 // a33, a35, a55 // NEX3, NEX5, NEX5C, NEXC3, VG10E (len == 15360))) { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if (memcmp(table_buf, "\xff\xff\xff\xff\xff\xff\xff\xff", 8) && memcmp(table_buf, "\x00\x00\x00\x00\x00\x00\x00\x00", 8)) { switch (len) { case 368: case 5478: // a700, a850, a900: CameraInfo if ((!dng_writer) || (saneSonyCameraInfo(table_buf[0], table_buf[3], table_buf[2], table_buf[5], table_buf[4], table_buf[7]))) { if (table_buf[0] | table_buf[3]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[0]) * 100 + bcd2dec(table_buf[3]); if (table_buf[2] | table_buf[5]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[2]) * 100 + bcd2dec(table_buf[5]); if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[4]) / 10.0f; if (table_buf[4]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[7]) / 10.0f; parseSonyLensFeatures(table_buf[1], table_buf[6]); } break; default: // CameraInfo2 & 3 if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } } } free(table_buf); } else if ((!dng_writer) && (tag == 0x0020) && // WBInfoA100, needs 0xb028 processing !strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 0x49dc, SEEK_CUR); stmread(imgdata.shootinginfo.InternalBodySerial, 12, ifp); } else if (tag == 0x0104) { imgdata.other.FlashEC = getreal(type); } else if (tag == 0x0105) // Teleconverter { imgdata.lens.makernotes.TeleconverterID = get2(); } else if (tag == 0x0114 && len < 256000) // CameraSettings { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); switch (len) { case 280: case 364: case 332: // CameraSettings and CameraSettings2 are big endian if (table_buf[2] | table_buf[3]) { lid = (((ushort)table_buf[2]) << 8) | ((ushort)table_buf[3]); imgdata.lens.makernotes.CurAp = powf64(2.0f, ((float)lid / 8.0f - 1.0f) / 2.0f); } break; case 1536: case 2048: // CameraSettings3 are little endian parseSonyLensType2(table_buf[1016], table_buf[1015]); if (imgdata.lens.makernotes.LensMount != LIBRAW_MOUNT_Canon_EF) { switch (table_buf[153]) { case 16: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Minolta_A; break; case 17: imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sony_E; break; } } break; } free(table_buf); } else if (tag == 0x0116 && len < 256000) { table_buf_0x0116 = (uchar *)malloc(len); table_buf_0x0116_present = 1; fread(table_buf_0x0116, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x0116 (table_buf_0x0116, unique_id); free(table_buf_0x0116); table_buf_0x0116_present = 0; } } else if (tag == 0x9050 && len < 256000) // little endian { table_buf_0x9050 = (uchar *)malloc(len); table_buf_0x9050_present = 1; fread(table_buf_0x9050, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9050(table_buf_0x9050, imgdata.lens.makernotes.CamID); free(table_buf_0x9050); table_buf_0x9050_present = 0; } } else if (tag == 0x9402 && len < 256000) { table_buf_0x9402 = (uchar *)malloc(len); table_buf_0x9402_present = 1; fread(table_buf_0x9402, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9402(table_buf_0x9402); free(table_buf_0x9402); table_buf_0x9402_present = 0; } } else if (tag == 0x9403 && len < 256000) { table_buf_0x9403 = (uchar *)malloc(len); table_buf_0x9403_present = 1; fread(table_buf_0x9403, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9403(table_buf_0x9403); free(table_buf_0x9403); table_buf_0x9403_present = 0; } } else if (tag == 0x9406 && len < 256000) { table_buf_0x9406 = (uchar *)malloc(len); table_buf_0x9406_present = 1; fread(table_buf_0x9406, len, 1, ifp); if (imgdata.lens.makernotes.CamID) { process_Sony_0x9406(table_buf_0x9406); free(table_buf_0x9406); table_buf_0x9406_present = 0; } } else if (tag == 0x940c && len < 256000) { table_buf_0x940c = (uchar *)malloc(len); table_buf_0x940c_present = 1; fread(table_buf_0x940c, len, 1, ifp); if ((imgdata.lens.makernotes.CamID) && (imgdata.lens.makernotes.CameraMount == LIBRAW_MOUNT_Sony_E)) { process_Sony_0x940c(table_buf_0x940c); free(table_buf_0x940c); table_buf_0x940c_present = 0; } } else if (((tag == 0xb027) || (tag == 0x010c)) && (imgdata.lens.makernotes.LensID == -1)) { imgdata.lens.makernotes.LensID = get4(); if ((imgdata.lens.makernotes.LensID > 0x4900) && (imgdata.lens.makernotes.LensID <= 0x5900)) { imgdata.lens.makernotes.AdapterID = 0x4900; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Sigma_X3F; strcpy(imgdata.lens.makernotes.Adapter, "MC-11"); } else if ((imgdata.lens.makernotes.LensID > 0xEF00) && (imgdata.lens.makernotes.LensID < 0xFFFF) && (imgdata.lens.makernotes.LensID != 0xFF00)) { imgdata.lens.makernotes.AdapterID = 0xEF00; imgdata.lens.makernotes.LensID -= imgdata.lens.makernotes.AdapterID; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Canon_EF; } if (tag == 0x010c) imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Minolta_A; } else if (tag == 0xb02a && len < 256000) // Sony LensSpec { table_buf = (uchar *)malloc(len); fread(table_buf, len, 1, ifp); if ((!dng_writer) || (saneSonyCameraInfo(table_buf[1], table_buf[2], table_buf[3], table_buf[4], table_buf[5], table_buf[6]))) { if (table_buf[1] | table_buf[2]) imgdata.lens.makernotes.MinFocal = bcd2dec(table_buf[1]) * 100 + bcd2dec(table_buf[2]); if (table_buf[3] | table_buf[4]) imgdata.lens.makernotes.MaxFocal = bcd2dec(table_buf[3]) * 100 + bcd2dec(table_buf[4]); if (table_buf[5]) imgdata.lens.makernotes.MaxAp4MinFocal = bcd2dec(table_buf[5]) / 10.0f; if (table_buf[6]) imgdata.lens.makernotes.MaxAp4MaxFocal = bcd2dec(table_buf[6]) / 10.0f; parseSonyLensFeatures(table_buf[0], table_buf[7]); } free(table_buf); } } void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { unsigned ver97 = 0, offset = 0, entries, tag, type, len, save, c; unsigned i; uchar NikonKey, ci, cj, ck; unsigned serial = 0; unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; short morder, sorder = order; char buf[10]; INT64 fsize = ifp->size(); fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ") || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if ((!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG))) base = ftell(ifp); } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); INT64 pos = ifp->tell(); if (len > 8 && pos + len > 2 * fsize) continue; tag |= uptag << 16; if (len > 100 * 1024 * 1024) goto next; // 100Mb tag? No! if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) parseFujiMakernotes(tag, type); else if (!strncasecmp(make, "LEICA", 5)) { if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x1d) // serial number while ((c = fgetc(ifp)) && c != EOF) { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); } else if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0097) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0xa7) // shutter count { NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 37 && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = (int)(100.0 * powf64(2.0, (double)(cc) / 12.0 - 5.0)); break; } } else if (!strncmp(make, "OLYMPUS", 7)) { int SubDirOffsetValid = strncmp(model, "E-300", 5) && strncmp(model, "E-330", 5) && strncmp(model, "E-400", 5) && strncmp(model, "E-500", 5) && strncmp(model, "E-1", 3); if ((tag == 0x2010) || (tag == 0x2020)) { fseek(ifp, save - 4, SEEK_SET); fseek(ifp, base + get4(), SEEK_SET); parse_makernote_0xc634(base, tag, dng_writer); } if (!SubDirOffsetValid && ((len > 4) || (((type == 3) || (type == 8)) && (len > 2)) || (((type == 4) || (type == 9)) && (len > 1)) || (type == 5) || (type > 9))) goto skip_Oly_broken_tags; switch (tag) { case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20100102: stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x20100201: imgdata.lens.makernotes.LensID = (unsigned long long)fgetc(ifp) << 16 | (unsigned long long)(fgetc(ifp), fgetc(ifp)) << 8 | (unsigned long long)fgetc(ifp); imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: if ((!imgdata.lens.LensSerial[0])) stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x20200401: imgdata.other.FlashEC = getreal(type); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } skip_Oly_broken_tags:; } else if (!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && (dng_writer == CameraDNG))) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 12, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7) && (dng_writer == AdobeDNG)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { imgdata.lens.makernotes.CamID = unique_id = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, AdobeDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } #else void CLASS parse_makernote_0xc634(int base, int uptag, unsigned dng_writer) { /*placeholder */} #endif void CLASS parse_makernote(int base, int uptag) { unsigned offset = 0, entries, tag, type, len, save, c; unsigned ver97 = 0, serial = 0, i, wbi = 0, wb[4] = {0, 0, 0, 0}; uchar buf97[324], ci, cj, ck; short morder, sorder = order; char buf[10]; unsigned SamsungKey[11]; uchar NikonKey; #ifdef LIBRAW_LIBRARY_BUILD unsigned custom_serial = 0; unsigned NikonLensDataVersion = 0; unsigned lenNikonLensData = 0; unsigned NikonFlashInfoVersion = 0; uchar *CanonCameraInfo; unsigned lenCanonCameraInfo = 0; unsigned typeCanonCameraInfo = 0; uchar *table_buf; uchar *table_buf_0x9050; ushort table_buf_0x9050_present = 0; uchar *table_buf_0x9402; ushort table_buf_0x9402_present = 0; uchar *table_buf_0x9403; ushort table_buf_0x9403_present = 0; uchar *table_buf_0x9406; ushort table_buf_0x9406_present = 0; uchar *table_buf_0x940c; ushort table_buf_0x940c_present = 0; uchar *table_buf_0x0116; ushort table_buf_0x0116_present = 0; INT64 fsize = ifp->size(); #endif /* The MakerNote might have its own TIFF header (possibly with its own byte-order!), or it might just be a table. */ if (!strncmp(make, "Nokia", 5)) return; fread(buf, 1, 10, ifp); /* printf("===>>buf: 0x"); for (int i = 0; i < sizeof buf; i ++) { printf("%02x", buf[i]); } putchar('\n'); */ if (!strncmp(buf, "KDK", 3) || /* these aren't TIFF tables */ !strncmp(buf, "VER", 3) || !strncmp(buf, "IIII", 4) || !strncmp(buf, "MMMM", 4)) return; if (!strncmp(buf, "KC", 2) || /* Konica KD-400Z, KD-510Z */ !strncmp(buf, "MLY", 3)) { /* Minolta DiMAGE G series */ order = 0x4d4d; while ((i = ftell(ifp)) < data_offset && i < 16384) { wb[0] = wb[2]; wb[2] = wb[1]; wb[1] = wb[3]; wb[3] = get2(); if (wb[1] == 256 && wb[3] == 256 && wb[0] > 256 && wb[0] < 640 && wb[2] > 256 && wb[2] < 640) FORC4 cam_mul[c] = wb[c]; } goto quit; } if (!strcmp(buf, "Nikon")) { base = ftell(ifp); order = get2(); if (get2() != 42) goto quit; offset = get4(); fseek(ifp, offset - 8, SEEK_CUR); } else if (!strcmp(buf, "OLYMPUS") || !strcmp(buf, "PENTAX ")) { base = ftell(ifp) - 10; fseek(ifp, -2, SEEK_CUR); order = get2(); if (buf[0] == 'O') get2(); } else if (!strncmp(buf, "SONY", 4) || !strcmp(buf, "Panasonic")) { goto nf; } else if (!strncmp(buf, "FUJIFILM", 8)) { base = ftell(ifp) - 10; nf: order = 0x4949; fseek(ifp, 2, SEEK_CUR); } else if (!strcmp(buf, "OLYMP") || !strcmp(buf, "LEICA") || !strcmp(buf, "Ricoh") || !strcmp(buf, "EPSON")) fseek(ifp, -2, SEEK_CUR); else if (!strcmp(buf, "AOC") || !strcmp(buf, "QVC")) fseek(ifp, -4, SEEK_CUR); else { fseek(ifp, -10, SEEK_CUR); if (!strncmp(make, "SAMSUNG", 7)) base = ftell(ifp); } // adjust pos & base for Leica M8/M9/M Mono tags and dir in tag 0x3400 if (!strncasecmp(make, "LEICA", 5)) { if (!strncmp(model, "M8", 2) || !strncasecmp(model, "Leica M8", 8) || !strncasecmp(model, "LEICA X", 7)) { base = ftell(ifp) - 8; } else if (!strncasecmp(model, "LEICA M (Typ 240)", 17)) { base = 0; } else if (!strncmp(model, "M9", 2) || !strncasecmp(model, "Leica M9", 8) || !strncasecmp(model, "M Monochrom", 11) || !strncasecmp(model, "Leica M Monochrom", 11)) { if (!uptag) { base = ftell(ifp) - 10; fseek(ifp, 8, SEEK_CUR); } else if (uptag == 0x3400) { fseek(ifp, 10, SEEK_CUR); base += 10; } } else if (!strncasecmp(model, "LEICA T", 7)) { base = ftell(ifp) - 8; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_T; #endif } #ifdef LIBRAW_LIBRARY_BUILD else if (!strncasecmp(model, "LEICA SL", 8)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_SL; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_FF; } #endif } entries = get2(); if (entries > 1000) return; morder = order; while (entries--) { order = morder; tiff_get(base, &tag, &type, &len, &save); tag |= uptag << 16; #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos = ftell(ifp); if (len > 8 && _pos + len > 2 * fsize) continue; if (!strncmp(make, "Canon", 5)) { if (tag == 0x000d && len < 256000) // camera info { if (type != 4) { CanonCameraInfo = (uchar *)malloc(MAX(16,len)); fread(CanonCameraInfo, len, 1, ifp); } else { CanonCameraInfo = (uchar *)malloc(MAX(16,len*4)); fread(CanonCameraInfo, len, 4, ifp); } lenCanonCameraInfo = len; typeCanonCameraInfo = type; } else if (tag == 0x10) // Canon ModelID { unique_id = get4(); unique_id = setCanonBodyFeatures(unique_id); if (lenCanonCameraInfo) { processCanonCameraInfo(unique_id, CanonCameraInfo, lenCanonCameraInfo, typeCanonCameraInfo); free(CanonCameraInfo); CanonCameraInfo = 0; lenCanonCameraInfo = 0; } } else parseCanonMakernotes(tag, type, len); } else if (!strncmp(make, "FUJI", 4)) { if (tag == 0x0010) { char FujiSerial[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; char yy[2], mm[3], dd[3], ystr[16], ynum[16]; int year, nwords, ynum_len; unsigned c; stmread(FujiSerial, len, ifp); nwords = getwords(FujiSerial, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); for (int i = 0; i < nwords; i++) { mm[2] = dd[2] = 0; if (strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) < 18) if (i == 0) strncpy(imgdata.shootinginfo.InternalBodySerial, words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s", imgdata.shootinginfo.InternalBodySerial, words[i]); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { strncpy(dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 14, 2); strncpy(mm, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 16, 2); strncpy(yy, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18, 2); year = (yy[0] - '0') * 10 + (yy[1] - '0'); if (year < 70) year += 2000; else year += 1900; ynum_len = (int)strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 18; strncpy(ynum, words[i], ynum_len); ynum[ynum_len] = 0; for (int j = 0; ynum[j] && ynum[j + 1] && sscanf(ynum + j, "%2x", &c); j += 2) ystr[j / 2] = c; ystr[ynum_len / 2 + 1] = 0; strcpy(model2, ystr); if (i == 0) { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; if (nwords == 1) snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s", words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12, ystr, year, mm, dd); else snprintf(tbuf, sizeof(tbuf), "%s %d:%s:%s %s", ystr, year, mm, dd, words[0] + strnlen(words[0], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } else { char tbuf[sizeof(imgdata.shootinginfo.InternalBodySerial)]; snprintf(tbuf, sizeof(tbuf), "%s %s %d:%s:%s %s", imgdata.shootinginfo.InternalBodySerial, ystr, year, mm, dd, words[i] + strnlen(words[i], sizeof(imgdata.shootinginfo.InternalBodySerial) - 1) - 12); strncpy(imgdata.shootinginfo.InternalBodySerial, tbuf, sizeof(imgdata.shootinginfo.InternalBodySerial) - 1); } } } } else parseFujiMakernotes(tag, type); } else if (!strncasecmp(model, "Hasselblad X1D", 14) || !strncasecmp(model, "Hasselblad H6D", 14) || !strncasecmp(model, "Hasselblad A6D", 14)) { if (tag == 0x0045) { imgdata.makernotes.hasselblad.BaseISO = get4(); } else if (tag == 0x0046) { imgdata.makernotes.hasselblad.Gain = getreal(type); } } else if (!strncasecmp(make, "LEICA", 5)) { if (((tag == 0x035e) || (tag == 0x035f)) && (type == 10) && (len == 9)) { int ind = tag == 0x035e ? 0 : 1; for (int j = 0; j < 3; j++) FORCC imgdata.color.dng_color[ind].forwardmatrix[j][c] = getreal(type); imgdata.color.dng_color[ind].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; } if (tag == 0x34003402) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0320) && (type == 9) && (len == 1) && !strncasecmp (make, "Leica Camera AG", 15) && !strncmp (buf, "LEICA", 5) && (buf[5] == 0) && (buf[6] == 0) && (buf[7] == 0) ) imgdata.other.CameraTemperature = getreal(type); if ((tag == 0x0303) && (type != 4)) { stmread(imgdata.lens.makernotes.Lens, len, ifp); } if ((tag == 0x3405) || (tag == 0x0310) || (tag == 0x34003405)) { imgdata.lens.makernotes.LensID = get4(); imgdata.lens.makernotes.LensID = ((imgdata.lens.makernotes.LensID >> 2) << 8) | (imgdata.lens.makernotes.LensID & 0x3); if (imgdata.lens.makernotes.LensID != -1) { if ((model[0] == 'M') || !strncasecmp(model, "LEICA M", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_M; } else if ((model[0] == 'S') || !strncasecmp(model, "LEICA S", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_S; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Leica_S; } } } else if (((tag == 0x0313) || (tag == 0x34003406)) && (fabs(imgdata.lens.makernotes.CurAp) < 0.17f) && ((type == 10) || (type == 5))) { imgdata.lens.makernotes.CurAp = getreal(type); if (imgdata.lens.makernotes.CurAp > 126.3) imgdata.lens.makernotes.CurAp = 0.0f; } else if (tag == 0x3400) { parse_makernote(base, 0x3400); } } else if (!strncmp(make, "NIKON", 5)) { if (tag == 0x000a) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } else if (tag == 0x0012) { char a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) imgdata.other.FlashEC = (float)(a * b) / (float)c; } else if (tag == 0x003b) // all 1s for regular exposures { imgdata.makernotes.nikon.ME_WB[0] = getreal(type); imgdata.makernotes.nikon.ME_WB[2] = getreal(type); imgdata.makernotes.nikon.ME_WB[1] = getreal(type); imgdata.makernotes.nikon.ME_WB[3] = getreal(type); } else if (tag == 0x0082) // lens attachment { stmread(imgdata.lens.makernotes.Attachment, len, ifp); } else if (tag == 0x0083) // lens type { imgdata.lens.nikon.NikonLensType = fgetc(ifp); } else if (tag == 0x0084) // lens { imgdata.lens.makernotes.MinFocal = getreal(type); imgdata.lens.makernotes.MaxFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MinFocal = getreal(type); imgdata.lens.makernotes.MaxAp4MaxFocal = getreal(type); } else if (tag == 0x008b) // lens f-stops { uchar a, b, c; a = fgetc(ifp); b = fgetc(ifp); c = fgetc(ifp); if (c) { imgdata.lens.nikon.NikonLensFStops = a * b * (12 / c); imgdata.lens.makernotes.LensFStops = (float)imgdata.lens.nikon.NikonLensFStops / 12.0f; } } else if (tag == 0x0093) // Nikon compression { imgdata.makernotes.nikon.NEFCompression = i = get2(); if ((i == 7) || (i == 9)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0098) // contains lens data { for (i = 0; i < 4; i++) { NikonLensDataVersion = NikonLensDataVersion * 10 + fgetc(ifp) - '0'; } switch (NikonLensDataVersion) { case 100: lenNikonLensData = 9; break; case 101: case 201: // encrypted, starting from v.201 case 202: case 203: lenNikonLensData = 15; break; case 204: lenNikonLensData = 16; break; case 400: lenNikonLensData = 459; break; case 401: lenNikonLensData = 590; break; case 402: lenNikonLensData = 509; break; case 403: lenNikonLensData = 879; break; } if (lenNikonLensData > 0) { table_buf = (uchar *)malloc(lenNikonLensData); fread(table_buf, lenNikonLensData, 1, ifp); if ((NikonLensDataVersion < 201) && lenNikonLensData) { processNikonLensData(table_buf, lenNikonLensData); free(table_buf); lenNikonLensData = 0; } } } else if (tag == 0x00a0) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x00a8) // contains flash data { for (i = 0; i < 4; i++) { NikonFlashInfoVersion = NikonFlashInfoVersion * 10 + fgetc(ifp) - '0'; } } else if (tag == 0x00b0) { get4(); // ME tag version, 4 symbols imgdata.makernotes.nikon.ExposureMode = get4(); imgdata.makernotes.nikon.nMEshots = get4(); imgdata.makernotes.nikon.MEgainOn = get4(); } } else if (!strncmp(make, "OLYMPUS", 7)) { switch (tag) { case 0x0404: case 0x101a: case 0x20100101: if (!imgdata.shootinginfo.BodySerial[0]) stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0x20100102: if (!imgdata.shootinginfo.InternalBodySerial[0]) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); break; case 0x0207: case 0x20100100: { uchar sOlyID[8]; fread(sOlyID, MIN(len, 7), 1, ifp); sOlyID[7] = 0; OlyID = sOlyID[0]; i = 1; while (i < 7 && sOlyID[i]) { OlyID = OlyID << 8 | sOlyID[i]; i++; } setOlympusBodyFeatures(OlyID); } break; case 0x1002: imgdata.lens.makernotes.CurAp = powf64(2.0f, getreal(type) / 2); break; case 0x20401112: imgdata.makernotes.olympus.OlympusCropID = get2(); break; case 0x20401113: FORC4 imgdata.makernotes.olympus.OlympusFrame[c] = get2(); break; case 0x20100201: { unsigned long long oly_lensid[3]; oly_lensid[0] = fgetc(ifp); fgetc(ifp); oly_lensid[1] = fgetc(ifp); oly_lensid[2] = fgetc(ifp); imgdata.lens.makernotes.LensID = (oly_lensid[0] << 16) | (oly_lensid[1] << 8) | oly_lensid[2]; } imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FT; imgdata.lens.makernotes.LensFormat = LIBRAW_FORMAT_FT; if (((imgdata.lens.makernotes.LensID < 0x20000) || (imgdata.lens.makernotes.LensID > 0x4ffff)) && (imgdata.lens.makernotes.LensID & 0x10)) { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_mFT; } break; case 0x20100202: stmread(imgdata.lens.LensSerial, len, ifp); break; case 0x20100203: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x20100205: imgdata.lens.makernotes.MaxAp4MinFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100206: imgdata.lens.makernotes.MaxAp4MaxFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100207: imgdata.lens.makernotes.MinFocal = (float)get2(); break; case 0x20100208: imgdata.lens.makernotes.MaxFocal = (float)get2(); if (imgdata.lens.makernotes.MaxFocal > 1000.0f) imgdata.lens.makernotes.MaxFocal = imgdata.lens.makernotes.MinFocal; break; case 0x2010020a: imgdata.lens.makernotes.MaxAp4CurFocal = powf64(sqrt(2.0f), get2() / 256.0f); break; case 0x20100301: imgdata.lens.makernotes.TeleconverterID = fgetc(ifp) << 8; fgetc(ifp); imgdata.lens.makernotes.TeleconverterID = imgdata.lens.makernotes.TeleconverterID | fgetc(ifp); break; case 0x20100303: stmread(imgdata.lens.makernotes.Teleconverter, len, ifp); break; case 0x20100403: stmread(imgdata.lens.makernotes.Attachment, len, ifp); break; case 0x1007: imgdata.other.SensorTemperature = (float)get2(); break; case 0x1008: imgdata.other.LensTemperature = (float)get2(); break; case 0x20401306: { int temp = get2(); if ((temp != 0) && (temp != 100)) { if (temp < 61) imgdata.other.CameraTemperature = (float) temp; else imgdata.other.CameraTemperature = (float) (temp-32) / 1.8f; if ((OlyID == 0x4434353933ULL) && // TG-5 (imgdata.other.exifAmbientTemperature > -273.15f)) imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; } } break; case 0x20501500: if (OlyID != 0x0ULL) { short temp = get2(); if ((OlyID == 0x4434303430ULL) || // E-1 (OlyID == 0x5330303336ULL) || // E-M5 (len != 1)) imgdata.other.SensorTemperature = (float)temp; else if ((temp != -32768) && (temp != 0)) { if (temp > 199) imgdata.other.SensorTemperature = 86.474958f - 0.120228f*(float)temp; else imgdata.other.SensorTemperature = (float)temp; } } break; } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(make, "RICOH", 5)) && !strncmp(model, "GR", 2)) { if (tag == 0x0005) { char buffer[17]; int count = 0; fread(buffer, 16, 1, ifp); buffer[16] = 0; for (int i = 0; i < 16; i++) { // sprintf(imgdata.shootinginfo.InternalBodySerial+2*i, "%02x", buffer[i]); if ((isspace(buffer[i])) || (buffer[i] == 0x2D) || (isalnum(buffer[i]))) count++; } if (count == 16) { sprintf(imgdata.shootinginfo.BodySerial, "%8s", buffer + 8); buffer[8] = 0; sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else { sprintf(imgdata.shootinginfo.BodySerial, "%02x%02x%02x%02x", buffer[4], buffer[5], buffer[6], buffer[7]); sprintf(imgdata.shootinginfo.InternalBodySerial, "%02x%02x%02x%02x", buffer[8], buffer[9], buffer[10], buffer[11]); } } else if ((tag == 0x1001) && (type == 3)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; imgdata.lens.makernotes.FocalType = 1; } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } } else if (!strncmp(make, "RICOH", 5) && strncmp(model, "PENTAX", 6)) { if ((tag == 0x0005) && !strncmp(model, "GXR", 3)) { char buffer[9]; buffer[8] = 0; fread(buffer, 8, 1, ifp); sprintf(imgdata.shootinginfo.InternalBodySerial, "%8s", buffer); } else if ((tag == 0x100b) && (type == 10)) { imgdata.other.FlashEC = getreal(type); } else if ((tag == 0x1017) && (get2() == 2)) { strcpy(imgdata.lens.makernotes.Attachment, "Wide-Angle Adapter"); } else if (tag == 0x1500) { imgdata.lens.makernotes.CurFocal = getreal(type); } else if ((tag == 0x2001) && !strncmp(model, "GXR", 3)) { short ntags, cur_tag; fseek(ifp, 20, SEEK_CUR); ntags = get2(); cur_tag = get2(); while (cur_tag != 0x002c) { fseek(ifp, 10, SEEK_CUR); cur_tag = get2(); } fseek(ifp, 6, SEEK_CUR); fseek(ifp, get4() + 20, SEEK_SET); stread(imgdata.shootinginfo.BodySerial, 12, ifp); get2(); imgdata.lens.makernotes.LensID = getc(ifp) - '0'; switch (imgdata.lens.makernotes.LensID) { case 1: case 2: case 3: case 5: case 6: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_RicohModule; break; case 8: imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Leica_M; imgdata.lens.makernotes.CameraFormat = LIBRAW_FORMAT_APSC; imgdata.lens.makernotes.LensID = -1; break; default: imgdata.lens.makernotes.LensID = -1; } fseek(ifp, 17, SEEK_CUR); stread(imgdata.lens.LensSerial, 12, ifp); } } else if ((!strncmp(make, "PENTAX", 6) || !strncmp(model, "PENTAX", 6) || (!strncmp(make, "SAMSUNG", 7) && dng_version)) && strncmp(model, "GR", 2)) { if (tag == 0x0005) { unique_id = get4(); setPentaxBodyFeatures(unique_id); } else if (tag == 0x0013) { imgdata.lens.makernotes.CurAp = (float)get2() / 10.0f; } else if (tag == 0x0014) { PentaxISO(get2()); } else if (tag == 0x001d) { imgdata.lens.makernotes.CurFocal = (float)get4() / 100.0f; } else if (tag == 0x003f) { imgdata.lens.makernotes.LensID = fgetc(ifp) << 8 | fgetc(ifp); } else if (tag == 0x0047) { imgdata.other.CameraTemperature = (float)fgetc(ifp); } else if (tag == 0x004d) { if (type == 9) imgdata.other.FlashEC = getreal(type) / 256.0f; else imgdata.other.FlashEC = (float)((signed short)fgetc(ifp)) / 6.0f; } else if (tag == 0x007e) { imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = (long)(-1) * get4(); } else if (tag == 0x0207) { if (len < 65535) // Safety belt PentaxLensInfo(imgdata.lens.makernotes.CamID, len); } else if ((tag >= 0x020d) && (tag <= 0x0214)) { FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list1[tag - 0x020d]][c ^ (c >> 1)] = get2(); } else if (tag == 0x0221) { int nWB = get2(); if (nWB <= sizeof(imgdata.color.WBCT_Coeffs) / sizeof(imgdata.color.WBCT_Coeffs[0])) for (int i = 0; i < nWB; i++) { imgdata.color.WBCT_Coeffs[i][0] = (unsigned)0xcfc6 - get2(); fseek(ifp, 2, SEEK_CUR); imgdata.color.WBCT_Coeffs[i][1] = get2(); imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = 0x2000; imgdata.color.WBCT_Coeffs[i][3] = get2(); } } else if (tag == 0x0215) { fseek(ifp, 16, SEEK_CUR); sprintf(imgdata.shootinginfo.InternalBodySerial, "%d", get4()); } else if (tag == 0x0229) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0x022d) { int wb_ind; getc(ifp); for (int wb_cnt = 0; wb_cnt < nPentax_wb_list2; wb_cnt++) { wb_ind = getc(ifp); if (wb_ind < nPentax_wb_list2) FORC4 imgdata.color.WB_Coeffs[Pentax_wb_list2[wb_ind]][c ^ (c >> 1)] = get2(); } } else if (tag == 0x0239) // Q-series lens info (LensInfoQ) { char LensInfo[20]; fseek(ifp, 2, SEEK_CUR); stread(imgdata.lens.makernotes.Lens, 30, ifp); strcat(imgdata.lens.makernotes.Lens, " "); stread(LensInfo, 20, ifp); strcat(imgdata.lens.makernotes.Lens, LensInfo); } } else if (!strncmp(make, "SAMSUNG", 7)) { if (tag == 0x0002) { if (get4() == 0x2000) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX; } else if (!strncmp(model, "NX mini", 7)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Samsung_NX_M; } else { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } } else if (tag == 0x0003) { unique_id = imgdata.lens.makernotes.CamID = get4(); } else if (tag == 0x0043) { int temp = get4(); if (temp) { imgdata.other.CameraTemperature = (float) temp; if (get4() == 10) imgdata.other.CameraTemperature /= 10.0f; } } else if (tag == 0xa002) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); } else if (tag == 0xa003) { imgdata.lens.makernotes.LensID = get2(); if (imgdata.lens.makernotes.LensID) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Samsung_NX; } else if (tag == 0xa005) { stmread(imgdata.lens.InternalLensSerial, len, ifp); } else if (tag == 0xa019) { imgdata.lens.makernotes.CurAp = getreal(type); } else if (tag == 0xa01a) { imgdata.lens.makernotes.FocalLengthIn35mmFormat = get4() / 10.0f; if (imgdata.lens.makernotes.FocalLengthIn35mmFormat < 10.0f) imgdata.lens.makernotes.FocalLengthIn35mmFormat *= 10.0f; } } else if (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "Konica", 6) || !strncasecmp(make, "Minolta", 7) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "Lusso", 5) || !strncasecmp(model, "HV", 2)))) { parseSonyMakernotes(tag, type, len, nonDNG, table_buf_0x9050, table_buf_0x9050_present, table_buf_0x940c, table_buf_0x940c_present, table_buf_0x0116, table_buf_0x0116_present, table_buf_0x9402, table_buf_0x9402_present, table_buf_0x9403, table_buf_0x9403_present, table_buf_0x9406, table_buf_0x9406_present); } fseek(ifp, _pos, SEEK_SET); #endif if (tag == 2 && strstr(make, "NIKON") && !iso_speed) iso_speed = (get2(), get2()); if (tag == 37 && strstr(make, "NIKON") && (!iso_speed || iso_speed == 65535)) { unsigned char cc; fread(&cc, 1, 1, ifp); iso_speed = int(100.0 * powf64(2.0f, float(cc) / 12.0 - 5.0)); } if (tag == 4 && len > 26 && len < 35) { if ((i = (get4(), get2())) != 0x7fff && (!iso_speed || iso_speed == 65535)) iso_speed = 50 * powf64(2.0, i / 32.0 - 4); #ifdef LIBRAW_LIBRARY_BUILD get4(); #else if ((i = (get2(), get2())) != 0x7fff && !aperture) aperture = powf64(2.0, i / 64.0); #endif if ((i = get2()) != 0xffff && !shutter) shutter = powf64(2.0, (short)i / -32.0); wbi = (get2(), get2()); shot_order = (get2(), get2()); } if ((tag == 4 || tag == 0x114) && !strncmp(make, "KONICA", 6)) { fseek(ifp, tag == 4 ? 140 : 160, SEEK_CUR); switch (get2()) { case 72: flip = 0; break; case 76: flip = 6; break; case 82: flip = 5; break; } } if (tag == 7 && type == 2 && len > 20) fgets(model2, 64, ifp); if (tag == 8 && type == 4) shot_order = get4(); if (tag == 9 && !strncmp(make, "Canon", 5)) fread(artist, 64, 1, ifp); if (tag == 0xc && len == 4) FORC3 cam_mul[(c << 1 | c >> 1) & 3] = getreal(type); if (tag == 0xd && type == 7 && get2() == 0xaaaa) { #if 0 /* Canon rotation data is handled by EXIF.Orientation */ for (c = i = 2; (ushort)c != 0xbbbb && i < len; i++) c = c << 8 | fgetc(ifp); while ((i += 4) < len - 5) if (get4() == 257 && (i = len) && (c = (get4(), fgetc(ifp))) < 3) flip = "065"[c] - '0'; #endif } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x10 && type == 4) unique_id = get4(); #endif #ifdef LIBRAW_LIBRARY_BUILD INT64 _pos2 = ftell(ifp); if (!strncasecmp(make, "Olympus", 7)) { short nWB, tWB; if ((tag == 0x20300108) || (tag == 0x20310109)) imgdata.makernotes.olympus.ColorSpace = get2(); if ((tag == 0x20400101) && (len == 2) && (!strncasecmp(model, "E-410", 5) || !strncasecmp(model, "E-510", 5))) { int i; for (i = 0; i < 64; i++) imgdata.color.WBCT_Coeffs[i][2] = imgdata.color.WBCT_Coeffs[i][4] = imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; for (i = 64; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } if ((tag >= 0x20400101) && (tag <= 0x20400111)) { nWB = tag - 0x20400101; tWB = Oly_wb_list2[nWB << 1]; ushort CT = Oly_wb_list2[(nWB << 1) | 1]; int wb[4]; wb[0] = get2(); wb[2] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][0] = wb[0]; imgdata.color.WB_Coeffs[tWB][2] = wb[2]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][0] = CT; imgdata.color.WBCT_Coeffs[nWB - 1][1] = wb[0]; imgdata.color.WBCT_Coeffs[nWB - 1][3] = wb[2]; } if (len == 4) { wb[1] = get2(); wb[3] = get2(); if (tWB != 0x100) { imgdata.color.WB_Coeffs[tWB][1] = wb[1]; imgdata.color.WB_Coeffs[tWB][3] = wb[3]; } if (CT) { imgdata.color.WBCT_Coeffs[nWB - 1][2] = wb[1]; imgdata.color.WBCT_Coeffs[nWB - 1][4] = wb[3]; } } } if ((tag >= 0x20400112) && (tag <= 0x2040011e)) { nWB = tag - 0x20400112; int wbG = get2(); tWB = Oly_wb_list2[nWB << 1]; if (nWB) imgdata.color.WBCT_Coeffs[nWB - 1][2] = imgdata.color.WBCT_Coeffs[nWB - 1][4] = wbG; if (tWB != 0x100) imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = wbG; } if (tag == 0x20400121) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); if (len == 4) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = get2(); } } if (tag == 0x2040011f) { int wbG = get2(); if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = wbG; FORC4 if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][0]) imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + c][3] = wbG; } if ((tag == 0x30000110) && strcmp(software, "v757-71")) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][2] = get2(); if (len == 2) { for (int i = 0; i < 256; i++) imgdata.color.WB_Coeffs[i][1] = imgdata.color.WB_Coeffs[i][3] = 0x100; } } if ((((tag >= 0x30000120) && (tag <= 0x30000124)) || ((tag >= 0x30000130) && (tag <= 0x30000133))) && strcmp(software, "v757-71")) { int wb_ind; if (tag <= 0x30000124) wb_ind = tag - 0x30000120; else wb_ind = tag - 0x30000130 + 5; imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][0] = get2(); imgdata.color.WB_Coeffs[Oly_wb_list1[wb_ind]][2] = get2(); } if ((tag == 0x20400805) && (len == 2)) { imgdata.makernotes.olympus.OlympusSensorCalibration[0] = getreal(type); imgdata.makernotes.olympus.OlympusSensorCalibration[1] = getreal(type); FORC4 imgdata.color.linear_max[c] = imgdata.makernotes.olympus.OlympusSensorCalibration[0]; } if (tag == 0x20200401) { imgdata.other.FlashEC = getreal(type); } } fseek(ifp, _pos2, SEEK_SET); #endif if (tag == 0x11 && is_raw && !strncmp(make, "NIKON", 5)) { fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); } if (tag == 0x14 && type == 7) { if (len == 2560) { fseek(ifp, 1248, SEEK_CUR); goto get2_256; } fread(buf, 1, 10, ifp); if (!strncmp(buf, "NRW ", 4)) { fseek(ifp, strcmp(buf + 4, "0100") ? 46 : 1546, SEEK_CUR); cam_mul[0] = get4() << 2; cam_mul[1] = get4() + get4(); cam_mul[2] = get4() << 2; } } if (tag == 0x15 && type == 2 && is_raw) fread(model, 64, 1, ifp); if (strstr(make, "PENTAX")) { if (tag == 0x1b) tag = 0x1018; if (tag == 0x1c) tag = 0x1017; } if (tag == 0x1d) { while ((c = fgetc(ifp)) && c != EOF) #ifdef LIBRAW_LIBRARY_BUILD { if ((!custom_serial) && (!isdigit(c))) { if ((strbuflen(model) == 3) && (!strcmp(model, "D50"))) { custom_serial = 34; } else { custom_serial = 96; } } #endif serial = serial * 10 + (isdigit(c) ? c - '0' : c % 10); #ifdef LIBRAW_LIBRARY_BUILD } if (!imgdata.shootinginfo.BodySerial[0]) sprintf(imgdata.shootinginfo.BodySerial, "%d", serial); #endif } if (tag == 0x29 && type == 1) { // Canon PowerShot G9 c = wbi < 18 ? "012347800000005896"[wbi] - '0' : 0; fseek(ifp, 8 + c * 32, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get4(); } #ifndef LIBRAW_LIBRARY_BUILD if (tag == 0x3d && type == 3 && len == 4) FORC4 cblack[c ^ c >> 1] = get2() >> (14 - tiff_bps); #endif if (tag == 0x81 && type == 4) { data_offset = get4(); fseek(ifp, data_offset + 41, SEEK_SET); raw_height = get2() * 2; raw_width = get2(); filters = 0x61616161; } if ((tag == 0x81 && type == 7) || (tag == 0x100 && type == 7) || (tag == 0x280 && type == 1)) { thumb_offset = ftell(ifp); thumb_length = len; } if (tag == 0x88 && type == 4 && (thumb_offset = get4())) thumb_offset += base; if (tag == 0x89 && type == 4) thumb_length = get4(); if (tag == 0x8c || tag == 0x96) meta_offset = ftell(ifp); if (tag == 0x97) { for (i = 0; i < 4; i++) ver97 = ver97 * 10 + fgetc(ifp) - '0'; switch (ver97) { case 100: fseek(ifp, 68, SEEK_CUR); FORC4 cam_mul[(c >> 1) | ((c & 1) << 1)] = get2(); break; case 102: fseek(ifp, 6, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); break; case 103: fseek(ifp, 16, SEEK_CUR); FORC4 cam_mul[c] = get2(); } if (ver97 >= 200) { if (ver97 != 205) fseek(ifp, 280, SEEK_CUR); fread(buf97, 324, 1, ifp); } } if ((tag == 0xa1) && (type == 7) && strncasecmp(make, "Samsung", 7)) { order = 0x4949; fseek(ifp, 140, SEEK_CUR); FORC3 cam_mul[c] = get4(); } if (tag == 0xa4 && type == 3) { fseek(ifp, wbi * 48, SEEK_CUR); FORC3 cam_mul[c] = get2(); } if (tag == 0xa7) { // shutter count NikonKey = fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp) ^ fgetc(ifp); if ((unsigned)(ver97 - 200) < 17) { ci = xlat[0][serial & 0xff]; cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < 324; i++) buf97[i] ^= (cj += ci * ck++); i = "66666>666;6A;:;55"[ver97 - 200] - '0'; FORC4 cam_mul[c ^ (c >> 1) ^ (i & 1)] = sget2(buf97 + (i & -2) + c * 2); } #ifdef LIBRAW_LIBRARY_BUILD if ((NikonLensDataVersion > 200) && lenNikonLensData) { if (custom_serial) { ci = xlat[0][custom_serial]; } else { ci = xlat[0][serial & 0xff]; } cj = xlat[1][NikonKey]; ck = 0x60; for (i = 0; i < lenNikonLensData; i++) table_buf[i] ^= (cj += ci * ck++); processNikonLensData(table_buf, lenNikonLensData); lenNikonLensData = 0; free(table_buf); } if (ver97 == 601) // Coolpix A { imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; } #endif } if (tag == 0xb001 && type == 3) // Sony ModelID { unique_id = get2(); } if (tag == 0x200 && len == 3) shot_order = (get4(), get4()); if (tag == 0x200 && len == 4) // Pentax black level FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x201 && len == 4) // Pentax As Shot WB FORC4 cam_mul[c ^ (c >> 1)] = get2(); if (tag == 0x220 && type == 7) meta_offset = ftell(ifp); if (tag == 0x401 && type == 4 && len == 4) FORC4 cblack[c ^ c >> 1] = get4(); #ifdef LIBRAW_LIBRARY_BUILD // not corrected for file bitcount, to be patched in open_datastream if (tag == 0x03d && strstr(make, "NIKON") && len == 4) { FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black += i; } #endif if (tag == 0xe01) { /* Nikon Capture Note */ #ifdef LIBRAW_LIBRARY_BUILD int loopc = 0; #endif order = 0x4949; fseek(ifp, 22, SEEK_CUR); for (offset = 22; offset + 22 < len; offset += 22 + i) { #ifdef LIBRAW_LIBRARY_BUILD if (loopc++ > 1024) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif tag = get4(); fseek(ifp, 14, SEEK_CUR); i = get4() - 4; if (tag == 0x76a43207) flip = get2(); else fseek(ifp, i, SEEK_CUR); } } if (tag == 0xe80 && len == 256 && type == 7) { fseek(ifp, 48, SEEK_CUR); cam_mul[0] = get2() * 508 * 1.078 / 0x10000; cam_mul[2] = get2() * 382 * 1.173 / 0x10000; } if (tag == 0xf00 && type == 7) { if (len == 614) fseek(ifp, 176, SEEK_CUR); else if (len == 734 || len == 1502) fseek(ifp, 148, SEEK_CUR); else goto next; goto get2_256; } if (((tag == 0x1011 && len == 9) || tag == 0x20400200) && strcmp(software, "v757-71")) for (i = 0; i < 3; i++) { #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.makernotes.olympus.ColorSpace) { FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; } else { FORC3 imgdata.color.ccm[i][c] = ((short)get2()) / 256.0; } #else FORC3 cmatrix[i][c] = ((short)get2()) / 256.0; #endif } if ((tag == 0x1012 || tag == 0x20400600) && len == 4) FORC4 cblack[c ^ c >> 1] = get2(); if (tag == 0x1017 || tag == 0x20400100) cam_mul[0] = get2() / 256.0; if (tag == 0x1018 || tag == 0x20400100) cam_mul[2] = get2() / 256.0; if (tag == 0x2011 && len == 2) { get2_256: order = 0x4d4d; cam_mul[0] = get2() / 256.0; cam_mul[2] = get2() / 256.0; } if ((tag | 0x70) == 0x2070 && (type == 4 || type == 13)) fseek(ifp, get4() + base, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD // IB start if (tag == 0x2010) { INT64 _pos3 = ftell(ifp); parse_makernote(base, 0x2010); fseek(ifp, _pos3, SEEK_SET); } if (((tag == 0x2020) || (tag == 0x3000) || (tag == 0x2030) || (tag == 0x2031) || (tag == 0x2050)) && ((type == 7) || (type == 13)) && !strncasecmp(make, "Olympus", 7)) { INT64 _pos3 = ftell(ifp); parse_makernote(base, tag); fseek(ifp, _pos3, SEEK_SET); } // IB end #endif if ((tag == 0x2020) && ((type == 7) || (type == 13)) && !strncmp(buf, "OLYMP", 5)) parse_thumb_note(base, 257, 258); if (tag == 0x2040) parse_makernote(base, 0x2040); if (tag == 0xb028) { fseek(ifp, get4() + base, SEEK_SET); parse_thumb_note(base, 136, 137); } if (tag == 0x4001 && len > 500 && len < 100000) { i = len == 582 ? 50 : len == 653 ? 68 : len == 5120 ? 142 : 126; fseek(ifp, i, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); for (i += 18; i <= len; i += 10) { get2(); FORC4 sraw_mul[c ^ (c >> 1)] = get2(); if (sraw_mul[1] == 1170) break; } } if (!strncasecmp(make, "Samsung", 7)) { if (tag == 0xa020) // get the full Samsung encryption key for (i = 0; i < 11; i++) SamsungKey[i] = get4(); if (tag == 0xa021) // get and decode Samsung cam_mul array FORC4 cam_mul[c ^ (c >> 1)] = get4() - SamsungKey[c]; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0xa022) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get4() - SamsungKey[c + 4]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] >> 4; } } if (tag == 0xa023) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] = get4() - SamsungKey[8]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = get4() - SamsungKey[9]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = get4() - SamsungKey[10]; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][2] = get4() - SamsungKey[0]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Ill_A][3] >> 4; } } if (tag == 0xa024) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][c ^ (c >> 1)] = get4() - SamsungKey[c + 1]; if (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][0] < (imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 1)) { imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][1] >> 4; imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_D65][3] >> 4; } } /* if (tag == 0xa025) { i = get4(); imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = i - SamsungKey[0]; printf ("Samsung 0xa025 %d\n", i); } */ if (tag == 0xa030 && len == 9) for (i = 0; i < 3; i++) FORC3 imgdata.color.ccm[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; #endif if (tag == 0xa031 && len == 9) // get and decode Samsung color matrix for (i = 0; i < 3; i++) FORC3 cmatrix[i][c] = (float)((short)((get4() + SamsungKey[i * 3 + c]))) / 256.0; if (tag == 0xa028) FORC4 cblack[c ^ (c >> 1)] = get4() - SamsungKey[c]; } else { // Somebody else use 0xa021 and 0xa028? if (tag == 0xa021) FORC4 cam_mul[c ^ (c >> 1)] = get4(); if (tag == 0xa028) FORC4 cam_mul[c ^ (c >> 1)] -= get4(); } #ifdef LIBRAW_LIBRARY_BUILD if (tag == 0x4021 && (imgdata.makernotes.canon.multishot[0] = get4()) && (imgdata.makernotes.canon.multishot[1] = get4())) { if (len >= 4) { imgdata.makernotes.canon.multishot[2] = get4(); imgdata.makernotes.canon.multishot[3] = get4(); } FORC4 cam_mul[c] = 1024; } #else if (tag == 0x4021 && get4() && get4()) FORC4 cam_mul[c] = 1024; #endif next: fseek(ifp, save, SEEK_SET); } quit: order = sorder; } /* Since the TIFF DateTime string has no timezone information, assume that the camera's clock was set to Universal Time. */ void CLASS get_timestamp(int reversed) { struct tm t; char str[20]; int i; str[19] = 0; if (reversed) for (i = 19; i--;) str[i] = fgetc(ifp); else fread(str, 19, 1, ifp); memset(&t, 0, sizeof t); if (sscanf(str, "%d:%d:%d %d:%d:%d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec) != 6) return; t.tm_year -= 1900; t.tm_mon -= 1; t.tm_isdst = -1; if (mktime(&t) > 0) timestamp = mktime(&t); } void CLASS parse_exif(int base) { unsigned kodak, entries, tag, type, len, save, c; double expo, ape; kodak = !strncmp(make, "EASTMAN", 7) && tiff_nifds < 3; entries = get2(); if (!strncmp(make, "Hasselblad", 10) && (tiff_nifds > 3) && (entries > 512)) return; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && savepos + len > fsize * 2) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.dng.MinFocal = getreal(type); imgdata.lens.dng.MaxFocal = getreal(type); imgdata.lens.dng.MaxAp4MinFocal = getreal(type); imgdata.lens.dng.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; #endif case 33434: tiff_ifd[tiff_nifds - 1].t_shutter = shutter = getreal(type); break; case 33437: aperture = getreal(type); break; // 0x829d FNumber case 34855: iso_speed = get2(); break; case 34865: if (iso_speed == 0xffff && !strncasecmp(make, "FUJI", 4)) iso_speed = getreal(type); break; case 34866: if (iso_speed == 0xffff && (!strncasecmp(make, "SONY", 4) || !strncasecmp(make, "CANON", 5))) iso_speed = getreal(type); break; case 36867: case 36868: get_timestamp(0); break; case 37377: if ((expo = -getreal(type)) < 128 && shutter == 0.) tiff_ifd[tiff_nifds - 1].t_shutter = shutter = powf64(2.0, expo); break; case 37378: // 0x9202 ApertureValue if ((fabs(ape = getreal(type)) < 256.0) && (!aperture)) aperture = powf64(2.0, ape / 2); break; case 37385: flash_used = getreal(type); break; case 37386: focal_len = getreal(type); break; case 37500: // tag 0x927c #ifdef LIBRAW_LIBRARY_BUILD if (((make[0] == '\0') && (!strncmp(model, "ov5647", 6))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_OV5647", 9))) || ((!strncmp(make, "RaspberryPi", 11)) && (!strncmp(model, "RP_imx219", 9)))) { char mn_text[512]; char *pos; char ccms[512]; ushort l; float num; fgets(mn_text, len, ifp); pos = strstr(mn_text, "gain_r="); if (pos) cam_mul[0] = atof(pos + 7); pos = strstr(mn_text, "gain_b="); if (pos) cam_mul[2] = atof(pos + 7); if ((cam_mul[0] > 0.001f) && (cam_mul[2] > 0.001f)) cam_mul[1] = cam_mul[3] = 1.0f; else cam_mul[0] = cam_mul[2] = 0.0f; pos = strstr(mn_text, "ccm=") + 4; l = strstr(pos, " ") - pos; memcpy(ccms, pos, l); ccms[l] = '\0'; pos = strtok(ccms, ","); for (l = 0; l < 4; l++) { num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[l][c] = (float)atoi(pos); num += imgdata.color.ccm[l][c]; pos = strtok(NULL, ","); } if (num > 0.01) FORC3 imgdata.color.ccm[l][c] = imgdata.color.ccm[l][c] / num; } } else #endif parse_makernote(base, 0); break; case 40962: if (kodak) raw_width = get4(); break; case 40963: if (kodak) raw_height = get4(); break; case 41730: if (get4() == 0x20002) for (exif_cfa = c = 0; c < 8; c += 2) exif_cfa |= fgetc(ifp) * 0x01010101 << c; } fseek(ifp, save, SEEK_SET); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS parse_gps_libraw(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); if (entries > 200) return; if (entries > 0) imgdata.other.parsed_gps.gpsparsed = 1; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: imgdata.other.parsed_gps.latref = getc(ifp); break; case 3: imgdata.other.parsed_gps.longref = getc(ifp); break; case 5: imgdata.other.parsed_gps.altref = getc(ifp); break; case 2: if (len == 3) FORC(3) imgdata.other.parsed_gps.latitude[c] = getreal(type); break; case 4: if (len == 3) FORC(3) imgdata.other.parsed_gps.longtitude[c] = getreal(type); break; case 7: if (len == 3) FORC(3) imgdata.other.parsed_gps.gpstimestamp[c] = getreal(type); break; case 6: imgdata.other.parsed_gps.altitude = getreal(type); break; case 9: imgdata.other.parsed_gps.gpsstatus = getc(ifp); break; } fseek(ifp, save, SEEK_SET); } } #endif void CLASS parse_gps(int base) { unsigned entries, tag, type, len, save, c; entries = get2(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (len > 1024) continue; // no GPS tags are 1k or larger switch (tag) { case 1: case 3: case 5: gpsdata[29 + tag / 2] = getc(ifp); break; case 2: case 4: case 7: FORC(6) gpsdata[tag / 3 * 6 + c] = get4(); break; case 6: FORC(2) gpsdata[18 + c] = get4(); break; case 18: case 29: fgets((char *)(gpsdata + 14 + tag / 3), MIN(len, 12), ifp); } fseek(ifp, save, SEEK_SET); } } void CLASS romm_coeff(float romm_cam[3][3]) { static const float rgb_romm[3][3] = /* ROMM == Kodak ProPhoto */ {{2.034193, -0.727420, -0.306766}, {-0.228811, 1.231729, -0.002922}, {-0.008565, -0.153273, 1.161839}}; int i, j, k; for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) for (cmatrix[i][j] = k = 0; k < 3; k++) cmatrix[i][j] += rgb_romm[i][k] * romm_cam[k][j]; } void CLASS parse_mos(int offset) { char data[40]; int skip, from, i, c, neut[4], planes = 0, frot = 0; static const char *mod[] = {"", "DCB2", "Volare", "Cantare", "CMost", "Valeo 6", "Valeo 11", "Valeo 22", "Valeo 11p", "Valeo 17", "", "Aptus 17", "Aptus 22", "Aptus 75", "Aptus 65", "Aptus 54S", "Aptus 65S", "Aptus 75S", "AFi 5", "AFi 6", "AFi 7", "AFi-II 7", "Aptus-II 7", "", "Aptus-II 6", "", "", "Aptus-II 10", "Aptus-II 5", "", "", "", "", "Aptus-II 10R", "Aptus-II 8", "", "Aptus-II 12", "", "AFi-II 12"}; float romm_cam[3][3]; fseek(ifp, offset, SEEK_SET); while (1) { if (get4() != 0x504b5453) break; get4(); fread(data, 1, 40, ifp); skip = get4(); from = ftell(ifp); // IB start #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(data, "CameraObj_camera_type")) { stmread(imgdata.lens.makernotes.body, skip, ifp); } if (!strcmp(data, "back_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.BodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.BodySerial)); strcpy(imgdata.shootinginfo.BodySerial, words[0]); } if (!strcmp(data, "CaptProf_serial_number")) { char buffer[sizeof(imgdata.shootinginfo.InternalBodySerial)]; char *words[4]; int nwords; stmread(buffer, skip, ifp); nwords = getwords(buffer, words, 4, sizeof(imgdata.shootinginfo.InternalBodySerial)); strcpy(imgdata.shootinginfo.InternalBodySerial, words[0]); } #endif // IB end if (!strcmp(data, "JPEG_preview_data")) { thumb_offset = from; thumb_length = skip; } if (!strcmp(data, "icc_camera_profile")) { profile_offset = from; profile_length = skip; } if (!strcmp(data, "ShootObj_back_type")) { fscanf(ifp, "%d", &i); if ((unsigned)i < sizeof mod / sizeof(*mod)) strcpy(model, mod[i]); } if (!strcmp(data, "icc_camera_to_tone_matrix")) { for (i = 0; i < 9; i++) ((float *)romm_cam)[i] = int_to_float(get4()); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_color_matrix")) { for (i = 0; i < 9; i++) fscanf(ifp, "%f", (float *)romm_cam + i); romm_coeff(romm_cam); } if (!strcmp(data, "CaptProf_number_of_planes")) fscanf(ifp, "%d", &planes); if (!strcmp(data, "CaptProf_raw_data_rotation")) fscanf(ifp, "%d", &flip); if (!strcmp(data, "CaptProf_mosaic_pattern")) FORC4 { fscanf(ifp, "%d", &i); if (i == 1) frot = c ^ (c >> 1); } if (!strcmp(data, "ImgProf_rotation_angle")) { fscanf(ifp, "%d", &i); flip = i - flip; } if (!strcmp(data, "NeutObj_neutrals") && !cam_mul[0]) { FORC4 fscanf(ifp, "%d", neut + c); FORC3 cam_mul[c] = (float)neut[0] / neut[c + 1]; } if (!strcmp(data, "Rows_data")) load_flags = get4(); parse_mos(from); fseek(ifp, skip + from, SEEK_SET); } if (planes) filters = (planes == 1) * 0x01010101 * (uchar) "\x94\x61\x16\x49"[(flip / 90 + frot) & 3]; } void CLASS linear_table(unsigned len) { int i; if (len > 0x10000) len = 0x10000; read_shorts(curve, len); for (i = len; i < 0x10000; i++) curve[i] = curve[i - 1]; maximum = curve[len < 0x1000 ? 0xfff : len - 1]; } #ifdef LIBRAW_LIBRARY_BUILD void CLASS Kodak_WB_0x08tags(int wb, unsigned type) { float mul[3] = {1, 1, 1}, num, mul2; int c; FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; imgdata.color.WB_Coeffs[wb][1] = imgdata.color.WB_Coeffs[wb][3] = mul[1]; mul2 = mul[1] * mul[1]; imgdata.color.WB_Coeffs[wb][0] = mul2 / mul[0]; imgdata.color.WB_Coeffs[wb][2] = mul2 / mul[2]; return; } /* Thanks to Alexey Danilchenko for wb as-shot parsing code */ void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; // int a_blck = 0; entries = get2(); if (entries > 1024) return; INT64 fsize = ifp->size(); while (entries--) { tiff_get(base, &tag, &type, &len, &save); INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > 2 * fsize) continue; if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | 0x20000, type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } if (tag == 1011) imgdata.other.FlashEC = getreal(type); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0f, get2()); wbi = -2; } if ((tag == 1030) && (len == 1)) imgdata.other.CameraTemperature = getreal(type); if ((tag == 1043) && (len == 1)) imgdata.other.SensorTemperature = getreal(type); if ((tag == 0x03ef) && (!strcmp(model, "EOS D2000C"))) black = get2(); if ((tag == 0x03f0) && (!strcmp(model, "EOS D2000C"))) { if (black) // already set by tag 0x03ef black = (black + get2()) / 2; else black = get2(); } INT64 _pos2 = ftell(ifp); if (tag == 0x0848) Kodak_WB_0x08tags(LIBRAW_WBI_Daylight, type); if (tag == 0x0849) Kodak_WB_0x08tags(LIBRAW_WBI_Tungsten, type); if (tag == 0x084a) Kodak_WB_0x08tags(LIBRAW_WBI_Fluorescent, type); if (tag == 0x084b) Kodak_WB_0x08tags(LIBRAW_WBI_Flash, type); if (tag == 0x084c) Kodak_WB_0x08tags(LIBRAW_WBI_Custom, type); if (tag == 0x084d) Kodak_WB_0x08tags(LIBRAW_WBI_Auto, type); if (tag == 0x0e93) imgdata.color.linear_max[0] = imgdata.color.linear_max[1] = imgdata.color.linear_max[2] = imgdata.color.linear_max[3] = get2(); if (tag == 0x09ce) stmread(imgdata.shootinginfo.InternalBodySerial, len, ifp); if (tag == 0xfa00) stmread(imgdata.shootinginfo.BodySerial, len, ifp); if (tag == 0xfa27) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; } if (tag == 0xfa28) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; } if (tag == 0xfa29) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; } if (tag == 0xfa2a) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; } fseek(ifp, _pos2, SEEK_SET); if (tag == 2120 + wbi || (wbi < 0 && tag == 2125)) /* use Auto WB if illuminant index is not set */ { FORC3 mul[c] = (num = getreal(type)) == 0 ? 1 : num; FORC3 cam_mul[c] = mul[1] / mul[c]; /* normalise against green */ } if (tag == 2317) linear_table(len); if (tag == 0x903) iso_speed = getreal(type); // if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #else void CLASS parse_kodak_ifd(int base) { unsigned entries, tag, type, len, save; int i, c, wbi = -2, wbtemp = 6500; float mul[3] = {1, 1, 1}, num; static const int wbtag[] = {64037, 64040, 64039, 64041, -1, -1, 64042}; entries = get2(); if (entries > 1024) return; while (entries--) { tiff_get(base, &tag, &type, &len, &save); if (tag == 1020) wbi = getint(type); if (tag == 1021 && len == 72) { /* WB set in software */ fseek(ifp, 40, SEEK_CUR); FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, get2()); wbi = -2; } if (tag == 2118) wbtemp = getint(type); if (tag == 2120 + wbi && wbi >= 0) FORC3 cam_mul[c] = 2048.0 / fMAX(1.0, getreal(type)); if (tag == 2130 + wbi) FORC3 mul[c] = getreal(type); if (tag == 2140 + wbi && wbi >= 0) FORC3 { for (num = i = 0; i < 4; i++) num += getreal(type) * pow(wbtemp / 100.0, i); cam_mul[c] = 2048 / fMAX(1.0, (num * mul[c])); } if (tag == 2317) linear_table(len); if (tag == 6020) iso_speed = getint(type); if (tag == 64013) wbi = fgetc(ifp); if ((unsigned)wbi < 7 && tag == wbtag[wbi]) FORC3 cam_mul[c] = get4(); if (tag == 64019) width = getint(type); if (tag == 64020) height = (getint(type) + 1) & -2; fseek(ifp, save, SEEK_SET); } } #endif int CLASS parse_tiff_ifd(int base) { unsigned entries, tag, type, len, plen = 16, save; int ifd, use_cm = 0, cfa, i, j, c, ima_len = 0; char *cbuf, *cp; uchar cfa_pat[16], cfa_pc[] = {0, 1, 2, 3}, tab[256]; double fm[3][4], cc[4][4], cm[4][3], cam_xyz[4][3], num; double ab[] = {1, 1, 1, 1}, asn[] = {0, 0, 0, 0}, xyz[] = {1, 1, 1}; unsigned sony_curve[] = {0, 0, 0, 0, 0, 4095}; unsigned *buf, sony_offset = 0, sony_length = 0, sony_key = 0; struct jhead jh; int pana_raw = 0; #ifndef LIBRAW_LIBRARY_BUILD FILE *sfp; #endif if (tiff_nifds >= sizeof tiff_ifd / sizeof tiff_ifd[0]) return 1; ifd = tiff_nifds++; for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) cc[j][i] = i == j; entries = get2(); if (entries > 512) return 1; #ifdef LIBRAW_LIBRARY_BUILD INT64 fsize = ifp->size(); #endif while (entries--) { tiff_get(base, &tag, &type, &len, &save); #ifdef LIBRAW_LIBRARY_BUILD INT64 savepos = ftell(ifp); if (len > 8 && len + savepos > fsize * 2) continue; // skip tag pointing out of 2xfile if (callbacks.exif_cb) { callbacks.exif_cb(callbacks.exifparser_data, tag | (pana_raw ? 0x30000 : 0), type, len, order, ifp); fseek(ifp, savepos, SEEK_SET); } #endif #ifdef LIBRAW_LIBRARY_BUILD if (!strncasecmp(make, "SONY", 4) || (!strncasecmp(make, "Hasselblad", 10) && (!strncasecmp(model, "Stellar", 7) || !strncasecmp(model, "Lunar", 5) || !strncasecmp(model, "HV", 2)))) { switch (tag) { case 0x7300: // SR2 black level for (int i = 0; i < 4 && i < len; i++) cblack[i] = get2(); break; case 0x7302: FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c < 2)] = get2(); break; case 0x7312: { int i, lc[4]; FORC4 lc[c] = get2(); i = (lc[1] == 1024 && lc[2] == 1024) << 1; SWAP(lc[i], lc[i + 1]); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c] = lc[c]; } break; case 0x7480: case 0x7820: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1]; break; case 0x7481: case 0x7821: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1]; break; case 0x7482: case 0x7822: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1]; break; case 0x7483: case 0x7823: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1]; break; case 0x7484: case 0x7824: imgdata.color.WBCT_Coeffs[0][0] = 4500; FORC3 imgdata.color.WBCT_Coeffs[0][c + 1] = get2(); imgdata.color.WBCT_Coeffs[0][4] = imgdata.color.WBCT_Coeffs[0][2]; break; case 0x7486: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Fluorescent][1]; break; case 0x7825: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1]; break; case 0x7826: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1]; break; case 0x7827: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1]; break; case 0x7828: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1]; break; case 0x7829: FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][1]; break; case 0x782a: imgdata.color.WBCT_Coeffs[1][0] = 8500; FORC3 imgdata.color.WBCT_Coeffs[1][c + 1] = get2(); imgdata.color.WBCT_Coeffs[1][4] = imgdata.color.WBCT_Coeffs[1][2]; break; case 0x782b: imgdata.color.WBCT_Coeffs[2][0] = 6000; FORC3 imgdata.color.WBCT_Coeffs[2][c + 1] = get2(); imgdata.color.WBCT_Coeffs[2][4] = imgdata.color.WBCT_Coeffs[2][2]; break; case 0x782c: imgdata.color.WBCT_Coeffs[3][0] = 3200; FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][c] = imgdata.color.WBCT_Coeffs[3][c + 1] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][3] = imgdata.color.WBCT_Coeffs[3][4] = imgdata.color.WB_Coeffs[LIBRAW_WBI_StudioTungsten][1]; break; case 0x782d: imgdata.color.WBCT_Coeffs[4][0] = 2500; FORC3 imgdata.color.WBCT_Coeffs[4][c + 1] = get2(); imgdata.color.WBCT_Coeffs[4][4] = imgdata.color.WBCT_Coeffs[4][2]; break; case 0x787f: FORC3 imgdata.color.linear_max[c] = get2(); imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; break; } } #endif switch (tag) { case 1: if (len == 4) pana_raw = get4(); break; case 5: width = get2(); break; case 6: height = get2(); break; case 7: width += get2(); break; case 9: if ((i = get2())) filters = i; #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += i; #endif break; case 8: case 10: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) pana_black[3] += get2(); #endif break; case 14: case 15: case 16: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { imgdata.color.linear_max[tag - 14] = get2(); if (tag == 15) imgdata.color.linear_max[3] = imgdata.color.linear_max[1]; } #endif break; case 17: case 18: if (type == 3 && len == 1) cam_mul[(tag - 17) * 2] = get2() / 256.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 19: if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = 0x100; } else get4(); } } break; #endif case 23: if (type == 3) iso_speed = get2(); break; case 28: case 29: case 30: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw && len == 1 && type == 3) { pana_black[tag - 28] = get2(); } else #endif { cblack[tag - 28] = get2(); cblack[3] = cblack[1]; } break; case 36: case 37: case 38: cam_mul[tag - 36] = get2(); break; case 39: #ifdef LIBRAW_LIBRARY_BUILD if (pana_raw) { ushort nWB, cnt, tWB; nWB = get2(); if (nWB > 0x100) break; for (cnt = 0; cnt < nWB; cnt++) { tWB = get2(); if (tWB < 0x100) { imgdata.color.WB_Coeffs[tWB][0] = get2(); imgdata.color.WB_Coeffs[tWB][1] = imgdata.color.WB_Coeffs[tWB][3] = get2(); imgdata.color.WB_Coeffs[tWB][2] = get2(); } else fseek(ifp, 6, SEEK_CUR); } } break; #endif if (len < 50 || cam_mul[0]) break; fseek(ifp, 12, SEEK_CUR); FORC3 cam_mul[c] = get2(); break; case 46: if (type != 7 || fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) break; thumb_offset = ftell(ifp) - 2; thumb_length = len; break; case 61440: /* Fuji HS10 table */ fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; case 2: case 256: case 61441: /* ImageWidth */ tiff_ifd[ifd].t_width = getint(type); break; case 3: case 257: case 61442: /* ImageHeight */ tiff_ifd[ifd].t_height = getint(type); break; case 258: /* BitsPerSample */ case 61443: tiff_ifd[ifd].samples = len & 7; tiff_ifd[ifd].bps = getint(type); if (tiff_bps < tiff_ifd[ifd].bps) tiff_bps = tiff_ifd[ifd].bps; break; case 61446: raw_height = 0; if (tiff_ifd[ifd].bps > 12) break; load_raw = &CLASS packed_load_raw; load_flags = get4() ? 24 : 80; break; case 259: /* Compression */ tiff_ifd[ifd].comp = getint(type); break; case 262: /* PhotometricInterpretation */ tiff_ifd[ifd].phint = get2(); break; case 270: /* ImageDescription */ fread(desc, 512, 1, ifp); break; case 271: /* Make */ fgets(make, 64, ifp); break; case 272: /* Model */ fgets(model, 64, ifp); break; #ifdef LIBRAW_LIBRARY_BUILD case 278: tiff_ifd[ifd].rows_per_strip = getint(type); break; #endif case 280: /* Panasonic RW2 offset */ if (type != 4) break; load_raw = &CLASS panasonic_load_raw; load_flags = 0x2008; case 273: /* StripOffset */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_offsets = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_offsets_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_offsets[i] = get4() + base; fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 513: /* JpegIFOffset */ case 61447: tiff_ifd[ifd].offset = get4() + base; if (!tiff_ifd[ifd].bps && tiff_ifd[ifd].offset > 0) { fseek(ifp, tiff_ifd[ifd].offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { tiff_ifd[ifd].comp = 6; tiff_ifd[ifd].t_width = jh.wide; tiff_ifd[ifd].t_height = jh.high; tiff_ifd[ifd].bps = jh.bits; tiff_ifd[ifd].samples = jh.clrs; if (!(jh.sraw || (jh.clrs & 1))) tiff_ifd[ifd].t_width *= jh.clrs; if ((tiff_ifd[ifd].t_width > 4 * tiff_ifd[ifd].t_height) & ~jh.clrs) { tiff_ifd[ifd].t_width /= 2; tiff_ifd[ifd].t_height *= 2; } i = order; parse_tiff(tiff_ifd[ifd].offset + 12); order = i; } } break; case 274: /* Orientation */ tiff_ifd[ifd].t_flip = "50132467"[get2() & 7] - '0'; break; case 277: /* SamplesPerPixel */ tiff_ifd[ifd].samples = getint(type) & 7; break; case 279: /* StripByteCounts */ #ifdef LIBRAW_LIBRARY_BUILD if (len > 1 && len < 16384) { off_t sav = ftell(ifp); tiff_ifd[ifd].strip_byte_counts = (int *)calloc(len, sizeof(int)); tiff_ifd[ifd].strip_byte_counts_count = len; for (int i = 0; i < len; i++) tiff_ifd[ifd].strip_byte_counts[i] = get4(); fseek(ifp, sav, SEEK_SET); // restore position } /* fallback */ #endif case 514: case 61448: tiff_ifd[ifd].bytes = get4(); break; case 61454: // FujiFilm "As Shot" FORC3 cam_mul[(4 - c) % 3] = getint(type); break; case 305: case 11: /* Software */ fgets(software, 64, ifp); if (!strncmp(software, "Adobe", 5) || !strncmp(software, "dcraw", 5) || !strncmp(software, "UFRaw", 5) || !strncmp(software, "Bibble", 6) || !strcmp(software, "Digital Photo Professional")) is_raw = 0; break; case 306: /* DateTime */ get_timestamp(0); break; case 315: /* Artist */ fread(artist, 64, 1, ifp); break; case 317: tiff_ifd[ifd].predictor = getint(type); break; case 322: /* TileWidth */ tiff_ifd[ifd].t_tile_width = getint(type); break; case 323: /* TileLength */ tiff_ifd[ifd].t_tile_length = getint(type); break; case 324: /* TileOffsets */ tiff_ifd[ifd].offset = len > 1 ? ftell(ifp) : get4(); if (len == 1) tiff_ifd[ifd].t_tile_width = tiff_ifd[ifd].t_tile_length = 0; if (len == 4) { load_raw = &CLASS sinar_4shot_load_raw; is_raw = 5; } break; case 325: tiff_ifd[ifd].bytes = len > 1 ? ftell(ifp) : get4(); break; case 330: /* SubIFDs */ if (!strcmp(model, "DSLR-A100") && tiff_ifd[ifd].t_width == 3872) { load_raw = &CLASS sony_arw_load_raw; data_offset = get4() + base; ifd++; #ifdef LIBRAW_LIBRARY_BUILD if (ifd >= sizeof tiff_ifd / sizeof tiff_ifd[0]) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif break; } #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Hasselblad", 10) && libraw_internal_data.unpacker_data.hasselblad_parser_flag) { fseek(ifp, ftell(ifp) + 4, SEEK_SET); fseek(ifp, get4() + base, SEEK_SET); parse_tiff_ifd(base); break; } #endif if (len > 1000) len = 1000; /* 1000 SubIFDs is enough */ while (len--) { i = ftell(ifp); fseek(ifp, get4() + base, SEEK_SET); if (parse_tiff_ifd(base)) break; fseek(ifp, i + 4, SEEK_SET); } break; case 339: tiff_ifd[ifd].sample_format = getint(type); break; case 400: strcpy(make, "Sarnoff"); maximum = 0xfff; break; #ifdef LIBRAW_LIBRARY_BUILD case 700: if ((type == 1 || type == 2 || type == 6 || type == 7) && len > 1 && len < 5100000) { xmpdata = (char *)malloc(xmplen = len + 1); fread(xmpdata, len, 1, ifp); xmpdata[len] = 0; } break; #endif case 28688: FORC4 sony_curve[c + 1] = get2() >> 2 & 0xfff; for (i = 0; i < 5; i++) for (j = sony_curve[i] + 1; j <= sony_curve[i + 1]; j++) curve[j] = curve[j - 1] + (1 << i); break; case 29184: sony_offset = get4(); break; case 29185: sony_length = get4(); break; case 29217: sony_key = get4(); break; case 29264: parse_minolta(ftell(ifp)); raw_width = 0; break; case 29443: FORC4 cam_mul[c ^ (c < 2)] = get2(); break; case 29459: FORC4 cam_mul[c] = get2(); i = (cam_mul[1] == 1024 && cam_mul[2] == 1024) << 1; SWAP(cam_mul[i], cam_mul[i + 1]) break; #ifdef LIBRAW_LIBRARY_BUILD case 30720: // Sony matrix, Sony_SR2SubIFD_0x7800 for (i = 0; i < 3; i++) { float num = 0.0; for (c = 0; c < 3; c++) { imgdata.color.ccm[i][c] = (float)((short)get2()); num += imgdata.color.ccm[i][c]; } if (num > 0.01) FORC3 imgdata.color.ccm[i][c] = imgdata.color.ccm[i][c] / num; } break; #endif case 29456: // Sony black level, Sony_SR2SubIFD_0x7310, no more needs to be divided by 4 FORC4 cblack[c ^ c >> 1] = get2(); i = cblack[3]; FORC3 if (i > cblack[c]) i = cblack[c]; FORC4 cblack[c] -= i; black = i; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("...Sony black: %u cblack: %u %u %u %u\n"), black, cblack[0], cblack[1], cblack[2], cblack[3]); #endif break; case 33405: /* Model2 */ fgets(model2, 64, ifp); break; case 33421: /* CFARepeatPatternDim */ if (get2() == 6 && get2() == 6) filters = 9; break; case 33422: /* CFAPattern */ if (filters == 9) { FORC(36)((char *)xtrans)[c] = fgetc(ifp) & 3; break; } case 64777: /* Kodak P-series */ if (len == 36) { filters = 9; colors = 3; FORC(36) xtrans[0][c] = fgetc(ifp) & 3; } else if (len > 0) { if ((plen = len) > 16) plen = 16; fread(cfa_pat, 1, plen, ifp); for (colors = cfa = i = 0; i < plen && colors < 4; i++) { colors += !(cfa & (1 << cfa_pat[i])); cfa |= 1 << cfa_pat[i]; } if (cfa == 070) memcpy(cfa_pc, "\003\004\005", 3); /* CMY */ if (cfa == 072) memcpy(cfa_pc, "\005\003\004\001", 4); /* GMCY */ goto guess_cfa_pc; } break; case 33424: case 65024: fseek(ifp, get4() + base, SEEK_SET); parse_kodak_ifd(base); break; case 33434: /* ExposureTime */ tiff_ifd[ifd].t_shutter = shutter = getreal(type); break; case 33437: /* FNumber */ aperture = getreal(type); break; #ifdef LIBRAW_LIBRARY_BUILD // IB start case 0x9400: imgdata.other.exifAmbientTemperature = getreal(type); if ((imgdata.other.CameraTemperature > -273.15f) && (OlyID == 0x4434353933ULL)) // TG-5 imgdata.other.CameraTemperature += imgdata.other.exifAmbientTemperature; break; case 0x9401: imgdata.other.exifHumidity = getreal(type); break; case 0x9402: imgdata.other.exifPressure = getreal(type); break; case 0x9403: imgdata.other.exifWaterDepth = getreal(type); break; case 0x9404: imgdata.other.exifAcceleration = getreal(type); break; case 0x9405: imgdata.other.exifCameraElevationAngle = getreal(type); break; case 0xa405: // FocalLengthIn35mmFormat imgdata.lens.FocalLengthIn35mmFormat = get2(); break; case 0xa431: // BodySerialNumber case 0xc62f: stmread(imgdata.shootinginfo.BodySerial, len, ifp); break; case 0xa432: // LensInfo, 42034dec, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa435: // LensSerialNumber stmread(imgdata.lens.LensSerial, len, ifp); break; case 0xc630: // DNG LensInfo, Lens Specification per EXIF standard imgdata.lens.MinFocal = getreal(type); imgdata.lens.MaxFocal = getreal(type); imgdata.lens.MaxAp4MinFocal = getreal(type); imgdata.lens.MaxAp4MaxFocal = getreal(type); break; case 0xa433: // LensMake stmread(imgdata.lens.LensMake, len, ifp); break; case 0xa434: // LensModel stmread(imgdata.lens.Lens, len, ifp); if (!strncmp(imgdata.lens.Lens, "----", 4)) imgdata.lens.Lens[0] = 0; break; case 0x9205: imgdata.lens.EXIF_MaxAp = powf64(2.0f, (getreal(type) / 2.0f)); break; // IB end #endif case 34306: /* Leaf white balance */ FORC4 cam_mul[c ^ 1] = 4096.0 / get2(); break; case 34307: /* Leaf CatchLight color matrix */ fread(software, 1, 7, ifp); if (strncmp(software, "MATRIX", 6)) break; colors = 4; for (raw_color = i = 0; i < 3; i++) { FORC4 fscanf(ifp, "%f", &rgb_cam[i][c ^ 1]); if (!use_camera_wb) continue; num = 0; FORC4 num += rgb_cam[i][c]; FORC4 rgb_cam[i][c] /= MAX(1, num); } break; case 34310: /* Leaf metadata */ parse_mos(ftell(ifp)); case 34303: strcpy(make, "Leaf"); break; case 34665: /* EXIF tag */ fseek(ifp, get4() + base, SEEK_SET); parse_exif(base); break; case 34853: /* GPSInfo tag */ { unsigned pos; fseek(ifp, pos = (get4() + base), SEEK_SET); parse_gps(base); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, pos, SEEK_SET); parse_gps_libraw(base); #endif } break; case 34675: /* InterColorProfile */ case 50831: /* AsShotICCProfile */ profile_offset = ftell(ifp); profile_length = len; break; case 37122: /* CompressedBitsPerPixel */ kodak_cbpp = get4(); break; case 37386: /* FocalLength */ focal_len = getreal(type); break; case 37393: /* ImageNumber */ shot_order = getint(type); break; case 37400: /* old Kodak KDC tag */ for (raw_color = i = 0; i < 3; i++) { getreal(type); FORC3 rgb_cam[i][c] = getreal(type); } break; case 40976: strip_offset = get4(); switch (tiff_ifd[ifd].comp) { case 32770: load_raw = &CLASS samsung_load_raw; break; case 32772: load_raw = &CLASS samsung2_load_raw; break; case 32773: load_raw = &CLASS samsung3_load_raw; break; } break; case 46275: /* Imacon tags */ strcpy(make, "Imacon"); data_offset = ftell(ifp); ima_len = len; break; case 46279: if (!ima_len) break; fseek(ifp, 38, SEEK_CUR); case 46274: fseek(ifp, 40, SEEK_CUR); raw_width = get4(); raw_height = get4(); left_margin = get4() & 7; width = raw_width - left_margin - (get4() & 7); top_margin = get4() & 7; height = raw_height - top_margin - (get4() & 7); if (raw_width == 7262 && ima_len == 234317952) { height = 5412; width = 7216; left_margin = 7; filters = 0; } else if (raw_width == 7262) { height = 5444; width = 7244; left_margin = 7; } fseek(ifp, 52, SEEK_CUR); FORC3 cam_mul[c] = getreal(11); fseek(ifp, 114, SEEK_CUR); flip = (get2() >> 7) * 90; if (width * height * 6 == ima_len) { if (flip % 180 == 90) SWAP(width, height); raw_width = width; raw_height = height; left_margin = top_margin = filters = flip = 0; } sprintf(model, "Ixpress %d-Mp", height * width / 1000000); load_raw = &CLASS imacon_full_load_raw; if (filters) { if (left_margin & 1) filters = 0x61616161; load_raw = &CLASS unpacked_load_raw; } maximum = 0xffff; break; case 50454: /* Sinar tag */ case 50455: if (len < 1 || len > 2560000 || !(cbuf = (char *)malloc(len))) break; #ifndef LIBRAW_LIBRARY_BUILD fread(cbuf, 1, len, ifp); #else if (fread(cbuf, 1, len, ifp) != len) throw LIBRAW_EXCEPTION_IO_CORRUPT; // cbuf to be free'ed in recycle #endif cbuf[len - 1] = 0; for (cp = cbuf - 1; cp && cp < cbuf + len; cp = strchr(cp, '\n')) if (!strncmp(++cp, "Neutral ", 8)) sscanf(cp + 8, "%f %f %f", cam_mul, cam_mul + 1, cam_mul + 2); free(cbuf); break; case 50458: if (!make[0]) strcpy(make, "Hasselblad"); break; case 50459: /* Hasselblad tag */ #ifdef LIBRAW_LIBRARY_BUILD libraw_internal_data.unpacker_data.hasselblad_parser_flag = 1; #endif i = order; j = ftell(ifp); c = tiff_nifds; order = get2(); fseek(ifp, j + (get2(), get4()), SEEK_SET); parse_tiff_ifd(j); maximum = 0xffff; tiff_nifds = c; order = i; break; case 50706: /* DNGVersion */ FORC4 dng_version = (dng_version << 8) + fgetc(ifp); if (!make[0]) strcpy(make, "DNG"); is_raw = 1; break; case 50708: /* UniqueCameraModel */ #ifdef LIBRAW_LIBRARY_BUILD stmread(imgdata.color.UniqueCameraModel, len, ifp); imgdata.color.UniqueCameraModel[sizeof(imgdata.color.UniqueCameraModel) - 1] = 0; #endif if (model[0]) break; #ifndef LIBRAW_LIBRARY_BUILD fgets(make, 64, ifp); #else strncpy(make, imgdata.color.UniqueCameraModel, MIN(len, sizeof(imgdata.color.UniqueCameraModel))); #endif if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } break; case 50710: /* CFAPlaneColor */ if (filters == 9) break; if (len > 4) len = 4; colors = len; fread(cfa_pc, 1, colors, ifp); guess_cfa_pc: FORCC tab[cfa_pc[c]] = c; cdesc[c] = 0; for (i = 16; i--;) filters = filters << 2 | tab[cfa_pat[i % plen]]; filters -= !filters; break; case 50711: /* CFALayout */ if (get2() == 2) fuji_width = 1; break; case 291: case 50712: /* LinearizationTable */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_LINTABLE; tiff_ifd[ifd].lineartable_offset = ftell(ifp); tiff_ifd[ifd].lineartable_len = len; #endif linear_table(len); break; case 50713: /* BlackLevelRepeatDim */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_cblack[4] = #endif cblack[4] = get2(); #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[5] = get2(); if (cblack[4] * cblack[5] > (sizeof(cblack) / sizeof(cblack[0]) - 6)) #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_cblack[4] = tiff_ifd[ifd].dng_levels.dng_cblack[5] = #endif cblack[4] = cblack[5] = 1; break; #ifdef LIBRAW_LIBRARY_BUILD case 0xf00d: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { FORC3 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][(4 - c) % 3] = getint(type); imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][1]; } break; case 0xf00c: if (strcmp(model, "X-A3") && strcmp(model, "X-A10")) { unsigned fwb[4]; FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; if ((fwb[3] == 17) && (libraw_internal_data.unpacker_data.lenRAFData > 3) && (libraw_internal_data.unpacker_data.lenRAFData < 10240000)) { INT64 f_save = ftell(ifp); ushort *rafdata = (ushort *)malloc(sizeof(ushort) * libraw_internal_data.unpacker_data.lenRAFData); fseek(ifp, libraw_internal_data.unpacker_data.posRAFData, SEEK_SET); fread(rafdata, sizeof(ushort), libraw_internal_data.unpacker_data.lenRAFData, ifp); fseek(ifp, f_save, SEEK_SET); int fj, found = 0; for (int fi = 0; fi < (libraw_internal_data.unpacker_data.lenRAFData - 3); fi++) { if ((fwb[0] == rafdata[fi]) && (fwb[1] == rafdata[fi + 1]) && (fwb[2] == rafdata[fi + 2])) { if (rafdata[fi - 15] != fwb[0]) continue; for (int wb_ind = 0, ofst = fi - 15; wb_ind < nFuji_wb_list1; wb_ind++, ofst += 3) { imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][1] = imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][3] = rafdata[ofst]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][0] = rafdata[ofst + 1]; imgdata.color.WB_Coeffs[Fuji_wb_list1[wb_ind]][2] = rafdata[ofst + 2]; } fi += 0x60; for (fj = fi; fj < (fi + 15); fj += 3) if (rafdata[fj] != rafdata[fi]) { found = 1; break; } if (found) { fj = fj - 93; for (int iCCT = 0; iCCT < 31; iCCT++) { imgdata.color.WBCT_Coeffs[iCCT][0] = FujiCCT_K[iCCT]; imgdata.color.WBCT_Coeffs[iCCT][1] = rafdata[iCCT * 3 + 1 + fj]; imgdata.color.WBCT_Coeffs[iCCT][2] = imgdata.color.WBCT_Coeffs[iCCT][4] = rafdata[iCCT * 3 + fj]; imgdata.color.WBCT_Coeffs[iCCT][3] = rafdata[iCCT * 3 + 2 + fj]; } } free(rafdata); break; } } } } FORC4 fwb[c] = get4(); if (fwb[3] < 0x100) { imgdata.color.WB_Coeffs[fwb[3]][0] = fwb[1]; imgdata.color.WB_Coeffs[fwb[3]][1] = imgdata.color.WB_Coeffs[fwb[3]][3] = fwb[0]; imgdata.color.WB_Coeffs[fwb[3]][2] = fwb[2]; } } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50709: stmread(imgdata.color.LocalizedCameraModel, len, ifp); break; #endif case 61450: cblack[4] = cblack[5] = MIN(sqrt((double)len), 64); case 50714: /* BlackLevel */ #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1 && tiff_ifd[ifd].samples == len) // LinearDNG, per-channel black { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; for (i = 0; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_cblack[i] = cblack[i] = getreal(type) + 0.5; tiff_ifd[ifd].dng_levels.dng_black = black = 0; } else #endif if ((cblack[4] * cblack[5] < 2) && len == 1) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; tiff_ifd[ifd].dng_levels.dng_black = #endif black = getreal(type); } else if (cblack[4] * cblack[5] <= len) { FORC(cblack[4] * cblack[5]) cblack[6 + c] = getreal(type); black = 0; FORC4 cblack[c] = 0; #ifdef LIBRAW_LIBRARY_BUILD if (tag == 50714) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; FORC(cblack[4] * cblack[5]) tiff_ifd[ifd].dng_levels.dng_cblack[6 + c] = cblack[6 + c]; tiff_ifd[ifd].dng_levels.dng_black = 0; FORC4 tiff_ifd[ifd].dng_levels.dng_cblack[c] = 0; } #endif } break; case 50715: /* BlackLevelDeltaH */ case 50716: /* BlackLevelDeltaV */ for (num = i = 0; i < len && i < 65536; i++) num += getreal(type); black += num / len + 0.5; #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.dng_black += num / len + 0.5; tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_BLACK; #endif break; case 50717: /* WhiteLevel */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_WHITE; tiff_ifd[ifd].dng_levels.dng_whitelevel[0] = #endif maximum = getint(type); #ifdef LIBRAW_LIBRARY_BUILD if (tiff_ifd[ifd].samples > 1) // Linear DNG case for (i = 1; i < colors && i < 4 && i < len; i++) tiff_ifd[ifd].dng_levels.dng_whitelevel[i] = getint(type); #endif break; case 50718: /* DefaultScale */ pixel_aspect = getreal(type); pixel_aspect /= getreal(type); if (pixel_aspect > 0.995 && pixel_aspect < 1.005) pixel_aspect = 1.0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50719: /* DefaultCropOrigin */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPORIGIN; tiff_ifd[ifd].dng_levels.default_crop[0] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[1] = getreal(type); } break; case 50720: /* DefaultCropSize */ if (len == 2) { tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_CROPSIZE; tiff_ifd[ifd].dng_levels.default_crop[2] = getreal(type); tiff_ifd[ifd].dng_levels.default_crop[3] = getreal(type); } break; #endif #ifdef LIBRAW_LIBRARY_BUILD case 50778: tiff_ifd[ifd].dng_color[0].illuminant = get2(); tiff_ifd[ifd].dng_color[0].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; case 50779: tiff_ifd[ifd].dng_color[1].illuminant = get2(); tiff_ifd[ifd].dng_color[1].parsedfields |= LIBRAW_DNGFM_ILLUMINANT; break; #endif case 50721: /* ColorMatrix1 */ case 50722: /* ColorMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 50721 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_COLORMATRIX; #endif FORCC for (j = 0; j < 3; j++) { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].colormatrix[c][j] = #endif cm[c][j] = getreal(type); } use_cm = 1; break; case 0xc714: /* ForwardMatrix1 */ case 0xc715: /* ForwardMatrix2 */ #ifdef LIBRAW_LIBRARY_BUILD i = tag == 0xc714 ? 0 : 1; tiff_ifd[ifd].dng_color[i].parsedfields |= LIBRAW_DNGFM_FORWARDMATRIX; #endif for (j = 0; j < 3; j++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[i].forwardmatrix[j][c] = #endif fm[j][c] = getreal(type); } break; case 50723: /* CameraCalibration1 */ case 50724: /* CameraCalibration2 */ #ifdef LIBRAW_LIBRARY_BUILD j = tag == 50723 ? 0 : 1; tiff_ifd[ifd].dng_color[j].parsedfields |= LIBRAW_DNGFM_CALIBRATION; #endif for (i = 0; i < colors; i++) FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_color[j].calibration[i][c] = #endif cc[i][c] = getreal(type); } break; case 50727: /* AnalogBalance */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_ANALOGBALANCE; #endif FORCC { #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.analogbalance[c] = #endif ab[c] = getreal(type); } break; case 50728: /* AsShotNeutral */ FORCC asn[c] = getreal(type); break; case 50729: /* AsShotWhiteXY */ xyz[0] = getreal(type); xyz[1] = getreal(type); xyz[2] = 1 - xyz[0] - xyz[1]; FORC3 xyz[c] /= d65_white[c]; break; #ifdef LIBRAW_LIBRARY_BUILD case 50730: /* DNG: Baseline Exposure */ baseline_exposure = getreal(type); break; #endif // IB start case 50740: /* tag 0xc634 : DNG Adobe, DNG Pentax, Sony SR2, DNG Private */ #ifdef LIBRAW_LIBRARY_BUILD { char mbuf[64]; unsigned short makernote_found = 0; INT64 curr_pos, start_pos = ftell(ifp); unsigned MakN_order, m_sorder = order; unsigned MakN_length; unsigned pos_in_original_raw; fread(mbuf, 1, 6, ifp); if (!strcmp(mbuf, "Adobe")) { order = 0x4d4d; // Adobe header is always in "MM" / big endian curr_pos = start_pos + 6; while (curr_pos + 8 - start_pos <= len) { fread(mbuf, 1, 4, ifp); curr_pos += 8; if (!strncmp(mbuf, "MakN", 4)) { makernote_found = 1; MakN_length = get4(); MakN_order = get2(); pos_in_original_raw = get4(); order = MakN_order; parse_makernote_0xc634(curr_pos + 6 - pos_in_original_raw, 0, AdobeDNG); break; } } } else { fread(mbuf + 6, 1, 2, ifp); if (!strcmp(mbuf, "PENTAX ") || !strcmp(mbuf, "SAMSUNG")) { makernote_found = 1; fseek(ifp, start_pos, SEEK_SET); parse_makernote_0xc634(base, 0, CameraDNG); } } fseek(ifp, start_pos, SEEK_SET); order = m_sorder; } // IB end #endif if (dng_version) break; parse_minolta(j = get4() + base); fseek(ifp, j, SEEK_SET); parse_tiff_ifd(base); break; case 50752: read_shorts(cr2_slice, 3); break; case 50829: /* ActiveArea */ top_margin = getint(type); left_margin = getint(type); height = getint(type) - top_margin; width = getint(type) - left_margin; break; case 50830: /* MaskedAreas */ for (i = 0; i < len && i < 32; i++) ((int *)mask)[i] = getint(type); black = 0; break; #ifdef LIBRAW_LIBRARY_BUILD case 50970: /* PreviewColorSpace */ tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_PREVIEWCS; tiff_ifd[ifd].dng_levels.preview_colorspace = getint(type); break; #endif case 51009: /* OpcodeList2 */ #ifdef LIBRAW_LIBRARY_BUILD tiff_ifd[ifd].dng_levels.parsedfields |= LIBRAW_DNGFM_OPCODE2; tiff_ifd[ifd].opcode2_offset = #endif meta_offset = ftell(ifp); break; case 64772: /* Kodak P-series */ if (len < 13) break; fseek(ifp, 16, SEEK_CUR); data_offset = get4(); fseek(ifp, 28, SEEK_CUR); data_offset += get4(); load_raw = &CLASS packed_load_raw; break; case 65026: if (type == 2) fgets(model2, 64, ifp); } fseek(ifp, save, SEEK_SET); } if (sony_length && sony_length < 10240000 && (buf = (unsigned *)malloc(sony_length))) { fseek(ifp, sony_offset, SEEK_SET); fread(buf, sony_length, 1, ifp); sony_decrypt(buf, sony_length / 4, 1, sony_key); #ifndef LIBRAW_LIBRARY_BUILD sfp = ifp; if ((ifp = tmpfile())) { fwrite(buf, sony_length, 1, ifp); fseek(ifp, 0, SEEK_SET); parse_tiff_ifd(-sony_offset); fclose(ifp); } ifp = sfp; #else if (!ifp->tempbuffer_open(buf, sony_length)) { parse_tiff_ifd(-sony_offset); ifp->tempbuffer_close(); } #endif free(buf); } for (i = 0; i < colors; i++) FORCC cc[i][c] *= ab[i]; if (use_cm) { FORCC for (i = 0; i < 3; i++) for (cam_xyz[c][i] = j = 0; j < colors; j++) cam_xyz[c][i] += cc[c][j] * cm[j][i] * xyz[i]; cam_xyz_coeff(cmatrix, cam_xyz); } if (asn[0]) { cam_mul[3] = 0; FORCC cam_mul[c] = 1 / asn[c]; } if (!use_cm) FORCC pre_mul[c] /= cc[c][c]; return 0; } int CLASS parse_tiff(int base) { int doff; fseek(ifp, base, SEEK_SET); order = get2(); if (order != 0x4949 && order != 0x4d4d) return 0; get2(); while ((doff = get4())) { fseek(ifp, doff + base, SEEK_SET); if (parse_tiff_ifd(base)) break; } return 1; } void CLASS apply_tiff() { int max_samp = 0, ties = 0, raw = -1, thm = -1, i; unsigned long long ns, os; struct jhead jh; thumb_misc = 16; if (thumb_offset) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { if ((unsigned)jh.bits < 17 && (unsigned)jh.wide < 0x10000 && (unsigned)jh.high < 0x10000) { thumb_misc = jh.bits; thumb_width = jh.wide; thumb_height = jh.high; } } } for (i = tiff_nifds; i--;) { if (tiff_ifd[i].t_shutter) shutter = tiff_ifd[i].t_shutter; tiff_ifd[i].t_shutter = shutter; } for (i = 0; i < tiff_nifds; i++) { if (max_samp < tiff_ifd[i].samples) max_samp = tiff_ifd[i].samples; if (max_samp > 3) max_samp = 3; os = raw_width * raw_height; ns = tiff_ifd[i].t_width * tiff_ifd[i].t_height; if (tiff_bps) { os *= tiff_bps; ns *= tiff_ifd[i].bps; } if ((tiff_ifd[i].comp != 6 || tiff_ifd[i].samples != 3) && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && (unsigned)tiff_ifd[i].bps < 33 && (unsigned)tiff_ifd[i].samples < 13 && ns && ((ns > os && (ties = 1)) || (ns == os && shot_select == ties++))) { raw_width = tiff_ifd[i].t_width; raw_height = tiff_ifd[i].t_height; tiff_bps = tiff_ifd[i].bps; tiff_compress = tiff_ifd[i].comp; data_offset = tiff_ifd[i].offset; #ifdef LIBRAW_LIBRARY_BUILD data_size = tiff_ifd[i].bytes; #endif tiff_flip = tiff_ifd[i].t_flip; tiff_samples = tiff_ifd[i].samples; tile_width = tiff_ifd[i].t_tile_width; tile_length = tiff_ifd[i].t_tile_length; shutter = tiff_ifd[i].t_shutter; raw = i; } } if (is_raw == 1 && ties) is_raw = ties; if (!tile_width) tile_width = INT_MAX; if (!tile_length) tile_length = INT_MAX; for (i = tiff_nifds; i--;) if (tiff_ifd[i].t_flip) tiff_flip = tiff_ifd[i].t_flip; if (raw >= 0 && !load_raw) switch (tiff_compress) { case 32767: if (tiff_ifd[raw].bytes == raw_width * raw_height) { tiff_bps = 12; load_raw = &CLASS sony_arw2_load_raw; break; } if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (tiff_ifd[raw].bytes * 8 != raw_width * raw_height * tiff_bps) { raw_height += 8; load_raw = &CLASS sony_arw_load_raw; break; } load_flags = 79; case 32769: load_flags++; case 32770: case 32773: goto slr; case 0: case 1: #ifdef LIBRAW_LIBRARY_BUILD // Sony 14-bit uncompressed if (!strncasecmp(make, "Sony", 4) && tiff_ifd[raw].bytes == raw_width * raw_height * 2) { tiff_bps = 14; load_raw = &CLASS unpacked_load_raw; break; } if (!strncasecmp(make, "Nikon", 5) && !strncmp(software, "Nikon Scan", 10)) { load_raw = &CLASS nikon_coolscan_load_raw; raw_color = 1; filters = 0; break; } #endif if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 2 == raw_width * raw_height * 3) load_flags = 24; if (tiff_ifd[raw].bytes * 5 == raw_width * raw_height * 8) { load_flags = 81; tiff_bps = 12; } slr: switch (tiff_bps) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 12: if (tiff_ifd[raw].phint == 2) load_flags = 6; load_raw = &CLASS packed_load_raw; break; case 14: load_flags = 0; case 16: load_raw = &CLASS unpacked_load_raw; if (!strncmp(make, "OLYMPUS", 7) && tiff_ifd[raw].bytes * 7 > raw_width * raw_height) load_raw = &CLASS olympus_load_raw; } break; case 6: case 7: case 99: load_raw = &CLASS lossless_jpeg_load_raw; break; case 262: load_raw = &CLASS kodak_262_load_raw; break; case 34713: if ((raw_width + 9) / 10 * 16 * raw_height == tiff_ifd[raw].bytes) { load_raw = &CLASS packed_load_raw; load_flags = 1; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; if (model[0] == 'N') load_flags = 80; } else if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes) { load_raw = &CLASS nikon_yuv_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); memset(cblack, 0, sizeof cblack); filters = 0; } else if (raw_width * raw_height * 2 == tiff_ifd[raw].bytes) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; order = 0x4d4d; } else #ifdef LIBRAW_LIBRARY_BUILD if (raw_width * raw_height * 3 == tiff_ifd[raw].bytes * 2) { load_raw = &CLASS packed_load_raw; load_flags = 80; } else if (tiff_ifd[raw].rows_per_strip && tiff_ifd[raw].strip_offsets_count && tiff_ifd[raw].strip_offsets_count == tiff_ifd[raw].strip_byte_counts_count) { int fit = 1; for (int i = 0; i < tiff_ifd[raw].strip_byte_counts_count - 1; i++) // all but last if (tiff_ifd[raw].strip_byte_counts[i] * 2 != tiff_ifd[raw].rows_per_strip * raw_width * 3) { fit = 0; break; } if (fit) load_raw = &CLASS nikon_load_striped_packed_raw; else load_raw = &CLASS nikon_load_raw; // fallback } else #endif load_raw = &CLASS nikon_load_raw; break; case 65535: load_raw = &CLASS pentax_load_raw; break; case 65000: switch (tiff_ifd[raw].phint) { case 2: load_raw = &CLASS kodak_rgb_load_raw; filters = 0; break; case 6: load_raw = &CLASS kodak_ycbcr_load_raw; filters = 0; break; case 32803: load_raw = &CLASS kodak_65000_load_raw; } case 32867: case 34892: break; #ifdef LIBRAW_LIBRARY_BUILD case 8: break; #endif default: is_raw = 0; } if (!dng_version) if (((tiff_samples == 3 && tiff_ifd[raw].bytes && tiff_bps != 14 && (tiff_compress & -16) != 32768) || (tiff_bps == 8 && strncmp(make, "Phase", 5) && strncmp(make, "Leaf", 4) && !strcasestr(make, "Kodak") && !strstr(model2, "DEBUG RAW"))) && strncmp(software, "Nikon Scan", 10)) is_raw = 0; for (i = 0; i < tiff_nifds; i++) if (i != raw && (tiff_ifd[i].samples == max_samp || (tiff_ifd[i].comp == 7 && tiff_ifd[i].samples == 1)) /* Allow 1-bps JPEGs */ && tiff_ifd[i].bps > 0 && tiff_ifd[i].bps < 33 && tiff_ifd[i].phint != 32803 && tiff_ifd[i].phint != 34892 && unsigned(tiff_ifd[i].t_width | tiff_ifd[i].t_height) < 0x10000 && tiff_ifd[i].t_width * tiff_ifd[i].t_height / (SQR(tiff_ifd[i].bps) + 1) > thumb_width * thumb_height / (SQR(thumb_misc) + 1) && tiff_ifd[i].comp != 34892) { thumb_width = tiff_ifd[i].t_width; thumb_height = tiff_ifd[i].t_height; thumb_offset = tiff_ifd[i].offset; thumb_length = tiff_ifd[i].bytes; thumb_misc = tiff_ifd[i].bps; thm = i; } if (thm >= 0) { thumb_misc |= tiff_ifd[thm].samples << 5; switch (tiff_ifd[thm].comp) { case 0: write_thumb = &CLASS layer_thumb; break; case 1: if (tiff_ifd[thm].bps <= 8) write_thumb = &CLASS ppm_thumb; else if (!strncmp(make, "Imacon", 6)) write_thumb = &CLASS ppm16_thumb; else thumb_load_raw = &CLASS kodak_thumb_load_raw; break; case 65000: thumb_load_raw = tiff_ifd[thm].phint == 6 ? &CLASS kodak_ycbcr_load_raw : &CLASS kodak_rgb_load_raw; } } } void CLASS parse_minolta(int base) { int save, tag, len, offset, high = 0, wide = 0, i, c; short sorder = order; fseek(ifp, base, SEEK_SET); if (fgetc(ifp) || fgetc(ifp) - 'M' || fgetc(ifp) - 'R') return; order = fgetc(ifp) * 0x101; offset = base + get4() + 8; while ((save = ftell(ifp)) < offset) { for (tag = i = 0; i < 4; i++) tag = tag << 8 | fgetc(ifp); len = get4(); switch (tag) { case 0x505244: /* PRD */ fseek(ifp, 8, SEEK_CUR); high = get2(); wide = get2(); break; #ifdef LIBRAW_LIBRARY_BUILD case 0x524946: /* RIF */ if (!strncasecmp(model, "DSLR-A100", 9)) { fseek(ifp, 8, SEEK_CUR); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][2] = get2(); get4(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][0] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][2] = get2(); imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Daylight][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Cloudy][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_W][3] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][1] = imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][3] = 0x100; } break; #endif case 0x574247: /* WBG */ get4(); i = strcmp(model, "DiMAGE A200") ? 0 : 3; FORC4 cam_mul[c ^ (c >> 1) ^ i] = get2(); break; case 0x545457: /* TTW */ parse_tiff(ftell(ifp)); data_offset = offset; } fseek(ifp, save + len + 8, SEEK_SET); } raw_height = high; raw_width = wide; order = sorder; } /* Many cameras have a "debug mode" that writes JPEG and raw at the same time. The raw file has no header, so try to to open the matching JPEG file and read its metadata. */ void CLASS parse_external_jpeg() { const char *file, *ext; char *jname, *jfile, *jext; #ifndef LIBRAW_LIBRARY_BUILD FILE *save = ifp; #else #if defined(_WIN32) && !defined(__MINGW32__) && defined(_MSC_VER) && (_MSC_VER > 1310) if (ifp->wfname()) { std::wstring rawfile(ifp->wfname()); rawfile.replace(rawfile.length() - 3, 3, L"JPG"); if (!ifp->subfile_open(rawfile.c_str())) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif if (!ifp->fname()) { imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; return; } #endif ext = strrchr(ifname, '.'); file = strrchr(ifname, '/'); if (!file) file = strrchr(ifname, '\\'); #ifndef LIBRAW_LIBRARY_BUILD if (!file) file = ifname - 1; #else if (!file) file = (char *)ifname - 1; #endif file++; if (!ext || strlen(ext) != 4 || ext - file != 8) return; jname = (char *)malloc(strlen(ifname) + 1); merror(jname, "parse_external_jpeg()"); strcpy(jname, ifname); jfile = file - ifname + jname; jext = ext - ifname + jname; if (strcasecmp(ext, ".jpg")) { strcpy(jext, isupper(ext[1]) ? ".JPG" : ".jpg"); if (isdigit(*file)) { memcpy(jfile, file + 4, 4); memcpy(jfile + 4, file, 4); } } else while (isdigit(*--jext)) { if (*jext != '9') { (*jext)++; break; } *jext = '0'; } #ifndef LIBRAW_LIBRARY_BUILD if (strcmp(jname, ifname)) { if ((ifp = fopen(jname, "rb"))) { #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Reading metadata from %s ...\n"), jname); #endif parse_tiff(12); thumb_offset = 0; is_raw = 1; fclose(ifp); } } #else if (strcmp(jname, ifname)) { if (!ifp->subfile_open(jname)) { parse_tiff(12); thumb_offset = 0; is_raw = 1; ifp->subfile_close(); } else imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; } #endif if (!timestamp) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_METADATA; #endif #ifdef DCRAW_VERBOSE fprintf(stderr, _("Failed to read metadata from %s\n"), jname); #endif } free(jname); #ifndef LIBRAW_LIBRARY_BUILD ifp = save; #endif } /* CIFF block 0x1030 contains an 8x8 white sample. Load this into white[][] for use in scale_colors(). */ void CLASS ciff_block_1030() { static const ushort key[] = {0x410, 0x45f3}; int i, bpp, row, col, vbits = 0; unsigned long bitbuf = 0; if ((get2(), get4()) != 0x80008 || !get4()) return; bpp = get2(); if (bpp != 10 && bpp != 12) return; for (i = row = 0; row < 8; row++) for (col = 0; col < 8; col++) { if (vbits < bpp) { bitbuf = bitbuf << 16 | (get2() ^ key[i++ & 1]); vbits += 16; } white[row][col] = bitbuf >> (vbits -= bpp) & ~(-1 << bpp); } } /* Parse a CIFF file, better known as Canon CRW format. */ void CLASS parse_ciff(int offset, int length, int depth) { int tboff, nrecs, c, type, len, save, wbi = -1; ushort key[] = {0x410, 0x45f3}; fseek(ifp, offset + length - 4, SEEK_SET); tboff = get4() + offset; fseek(ifp, tboff, SEEK_SET); nrecs = get2(); if ((nrecs | depth) > 127) return; while (nrecs--) { type = get2(); len = get4(); save = ftell(ifp) + 4; fseek(ifp, offset + get4(), SEEK_SET); if ((((type >> 8) + 8) | 8) == 0x38) { parse_ciff(ftell(ifp), len, depth + 1); /* Parse a sub-table */ } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x3004) parse_ciff(ftell(ifp), len, depth + 1); #endif if (type == 0x0810) fread(artist, 64, 1, ifp); if (type == 0x080a) { fread(make, 64, 1, ifp); fseek(ifp, strbuflen(make) - 63, SEEK_CUR); fread(model, 64, 1, ifp); } if (type == 0x1810) { width = get4(); height = get4(); pixel_aspect = int_to_float(get4()); flip = get4(); } if (type == 0x1835) /* Get the decoder table */ tiff_compress = get4(); if (type == 0x2007) { thumb_offset = ftell(ifp); thumb_length = len; } if (type == 0x1818) { shutter = powf64(2.0f, -int_to_float((get4(), get4()))); aperture = powf64(2.0f, int_to_float(get4()) / 2); #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurAp = aperture; #endif } if (type == 0x102a) { // iso_speed = pow (2.0, (get4(),get2())/32.0 - 4) * 50; iso_speed = powf64(2.0f, ((get2(), get2()) + get2()) / 32.0f - 5.0f) * 100.0f; #ifdef LIBRAW_LIBRARY_BUILD aperture = _CanonConvertAperture((get2(), get2())); imgdata.lens.makernotes.CurAp = aperture; #else aperture = powf64(2.0, (get2(), (short)get2()) / 64.0); #endif shutter = powf64(2.0, -((short)get2()) / 32.0); wbi = (get2(), get2()); if (wbi > 17) wbi = 0; fseek(ifp, 32, SEEK_CUR); if (shutter > 1e6) shutter = get2() / 10.0; } if (type == 0x102c) { if (get2() > 512) { /* Pro90, G1 */ fseek(ifp, 118, SEEK_CUR); FORC4 cam_mul[c ^ 2] = get2(); } else { /* G2, S30, S40 */ fseek(ifp, 98, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2(); } } #ifdef LIBRAW_LIBRARY_BUILD if (type == 0x10a9) { INT64 o = ftell(ifp); fseek(ifp, (0x1 << 1), SEEK_CUR); FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ (c >> 1)] = get2(); Canon_WBpresets(0, 0); fseek(ifp, o, SEEK_SET); } if (type == 0x102d) { INT64 o = ftell(ifp); Canon_CameraSettings(); fseek(ifp, o, SEEK_SET); } if (type == 0x580b) { if (strcmp(model, "Canon EOS D30")) sprintf(imgdata.shootinginfo.BodySerial, "%d", len); else sprintf(imgdata.shootinginfo.BodySerial, "%0x-%05d", len >> 16, len & 0xffff); } #endif if (type == 0x0032) { if (len == 768) { /* EOS D30 */ fseek(ifp, 72, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = 1024.0 / get2(); if (!wbi) cam_mul[0] = -1; /* use my auto white balance */ } else if (!cam_mul[0]) { if (get2() == key[0]) /* Pro1, G6, S60, S70 */ c = (strstr(model, "Pro1") ? "012346000000000000" : "01345:000000006008")[LIM(0, wbi, 17)] - '0' + 2; else { /* G3, G5, S45, S50 */ c = "023457000000006000"[LIM(0, wbi, 17)] - '0'; key[0] = key[1] = 0; } fseek(ifp, 78 + c * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1) ^ 1] = get2() ^ key[c & 1]; if (!wbi) cam_mul[0] = -1; } } if (type == 0x10a9) { /* D60, 10D, 300D, and clones */ if (len > 66) wbi = "0134567028"[LIM(0, wbi, 9)] - '0'; fseek(ifp, 2 + wbi * 8, SEEK_CUR); FORC4 cam_mul[c ^ (c >> 1)] = get2(); } if (type == 0x1030 && wbi >= 0 && (0x18040 >> wbi & 1)) ciff_block_1030(); /* all that don't have 0x10a9 */ if (type == 0x1031) { raw_width = (get2(), get2()); raw_height = get2(); } if (type == 0x501c) { iso_speed = len & 0xffff; } if (type == 0x5029) { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CurFocal = len >> 16; imgdata.lens.makernotes.FocalType = len & 0xffff; if (imgdata.lens.makernotes.FocalType == 2) { imgdata.lens.makernotes.CanonFocalUnits = 32; if (imgdata.lens.makernotes.CanonFocalUnits > 1) imgdata.lens.makernotes.CurFocal /= (float)imgdata.lens.makernotes.CanonFocalUnits; } focal_len = imgdata.lens.makernotes.CurFocal; #else focal_len = len >> 16; if ((len & 0xffff) == 2) focal_len /= 32; #endif } if (type == 0x5813) flash_used = int_to_float(len); if (type == 0x5814) canon_ev = int_to_float(len); if (type == 0x5817) shot_order = len; if (type == 0x5834) { unique_id = len; #ifdef LIBRAW_LIBRARY_BUILD unique_id = setCanonBodyFeatures(unique_id); #endif } if (type == 0x580e) timestamp = len; if (type == 0x180e) timestamp = get4(); #ifdef LOCALTIME if ((type | 0x4000) == 0x580e) timestamp = mktime(gmtime(&timestamp)); #endif fseek(ifp, save, SEEK_SET); } } void CLASS parse_rollei() { char line[128], *val; struct tm t; fseek(ifp, 0, SEEK_SET); memset(&t, 0, sizeof t); do { fgets(line, 128, ifp); if ((val = strchr(line, '='))) *val++ = 0; else val = line + strbuflen(line); if (!strcmp(line, "DAT")) sscanf(val, "%d.%d.%d", &t.tm_mday, &t.tm_mon, &t.tm_year); if (!strcmp(line, "TIM")) sscanf(val, "%d:%d:%d", &t.tm_hour, &t.tm_min, &t.tm_sec); if (!strcmp(line, "HDR")) thumb_offset = atoi(val); if (!strcmp(line, "X ")) raw_width = atoi(val); if (!strcmp(line, "Y ")) raw_height = atoi(val); if (!strcmp(line, "TX ")) thumb_width = atoi(val); if (!strcmp(line, "TY ")) thumb_height = atoi(val); } while (strncmp(line, "EOHD", 4)); data_offset = thumb_offset + thumb_width * thumb_height * 2; t.tm_year -= 1900; t.tm_mon -= 1; if (mktime(&t) > 0) timestamp = mktime(&t); strcpy(make, "Rollei"); strcpy(model, "d530flex"); write_thumb = &CLASS rollei_thumb; } void CLASS parse_sinar_ia() { int entries, off; char str[8], *cp; order = 0x4949; fseek(ifp, 4, SEEK_SET); entries = get4(); fseek(ifp, get4(), SEEK_SET); while (entries--) { off = get4(); get4(); fread(str, 8, 1, ifp); if (!strcmp(str, "META")) meta_offset = off; if (!strcmp(str, "THUMB")) thumb_offset = off; if (!strcmp(str, "RAW0")) data_offset = off; } fseek(ifp, meta_offset + 20, SEEK_SET); fread(make, 64, 1, ifp); make[63] = 0; if ((cp = strchr(make, ' '))) { strcpy(model, cp + 1); *cp = 0; } raw_width = get2(); raw_height = get2(); load_raw = &CLASS unpacked_load_raw; thumb_width = (get4(), get2()); thumb_height = get2(); write_thumb = &CLASS ppm_thumb; maximum = 0x3fff; } void CLASS parse_phase_one(int base) { unsigned entries, tag, type, len, data, save, i, c; float romm_cam[3][3]; char *cp; memset(&ph1, 0, sizeof ph1); fseek(ifp, base, SEEK_SET); order = get4() & 0xffff; if (get4() >> 8 != 0x526177) return; /* "Raw" */ fseek(ifp, get4() + base, SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); type = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, base + data, SEEK_SET); switch (tag) { #ifdef LIBRAW_LIBRARY_BUILD case 0x0102: stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); break; case 0x0211: imgdata.other.SensorTemperature2 = int_to_float(data); break; case 0x0401: if (type == 4) imgdata.lens.makernotes.CurAp = powf64(2.0f, (int_to_float(data) / 2.0f)); else imgdata.lens.makernotes.CurAp = powf64(2.0f, (getreal(type) / 2.0f)); break; case 0x0403: if (type == 4) imgdata.lens.makernotes.CurFocal = int_to_float(data); else imgdata.lens.makernotes.CurFocal = getreal(type); break; case 0x0410: stmread(imgdata.lens.makernotes.body, len, ifp); break; case 0x0412: stmread(imgdata.lens.makernotes.Lens, len, ifp); break; case 0x0414: if (type == 4) { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0415: if (type == 4) { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (int_to_float(data) / 2.0f)); } else { imgdata.lens.makernotes.MinAp4CurFocal = powf64(2.0f, (getreal(type) / 2.0f)); } break; case 0x0416: if (type == 4) { imgdata.lens.makernotes.MinFocal = int_to_float(data); } else { imgdata.lens.makernotes.MinFocal = getreal(type); } if (imgdata.lens.makernotes.MinFocal > 1000.0f) { imgdata.lens.makernotes.MinFocal = 0.0f; } break; case 0x0417: if (type == 4) { imgdata.lens.makernotes.MaxFocal = int_to_float(data); } else { imgdata.lens.makernotes.MaxFocal = getreal(type); } break; #endif case 0x100: flip = "0653"[data & 3] - '0'; break; case 0x106: for (i = 0; i < 9; i++) #ifdef LIBRAW_LIBRARY_BUILD imgdata.color.P1_color[0].romm_cam[i] = #endif ((float *)romm_cam)[i] = getreal(11); romm_coeff(romm_cam); break; case 0x107: FORC3 cam_mul[c] = getreal(11); break; case 0x108: raw_width = data; break; case 0x109: raw_height = data; break; case 0x10a: left_margin = data; break; case 0x10b: top_margin = data; break; case 0x10c: width = data; break; case 0x10d: height = data; break; case 0x10e: ph1.format = data; break; case 0x10f: data_offset = data + base; break; case 0x110: meta_offset = data + base; meta_length = len; break; case 0x112: ph1.key_off = save - 4; break; case 0x210: ph1.tag_210 = int_to_float(data); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.SensorTemperature = ph1.tag_210; #endif break; case 0x21a: ph1.tag_21a = data; break; case 0x21c: strip_offset = data + base; break; case 0x21d: ph1.t_black = data; break; case 0x222: ph1.split_col = data; break; case 0x223: ph1.black_col = data + base; break; case 0x224: ph1.split_row = data; break; case 0x225: ph1.black_row = data + base; break; #ifdef LIBRAW_LIBRARY_BUILD case 0x226: for (i = 0; i < 9; i++) imgdata.color.P1_color[1].romm_cam[i] = getreal(11); break; #endif case 0x301: model[63] = 0; fread(model, 1, 63, ifp); if ((cp = strstr(model, " camera"))) *cp = 0; } fseek(ifp, save, SEEK_SET); } #ifdef LIBRAW_LIBRARY_BUILD if (!imgdata.lens.makernotes.body[0] && !imgdata.shootinginfo.BodySerial[0]) { fseek(ifp, meta_offset, SEEK_SET); order = get2(); fseek(ifp, 6, SEEK_CUR); fseek(ifp, meta_offset + get4(), SEEK_SET); entries = get4(); get4(); while (entries--) { tag = get4(); len = get4(); data = get4(); save = ftell(ifp); fseek(ifp, meta_offset + data, SEEK_SET); if (tag == 0x0407) { stmread(imgdata.shootinginfo.BodySerial, len, ifp); if ((imgdata.shootinginfo.BodySerial[0] == 0x4c) && (imgdata.shootinginfo.BodySerial[1] == 0x49)) { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[2] & 0x3f)) - 0x41; } else { unique_id = (((imgdata.shootinginfo.BodySerial[0] & 0x3f) << 5) | (imgdata.shootinginfo.BodySerial[1] & 0x3f)) - 0x41; } setPhaseOneFeatures(unique_id); } fseek(ifp, save, SEEK_SET); } } #endif load_raw = ph1.format < 3 ? &CLASS phase_one_load_raw : &CLASS phase_one_load_raw_c; maximum = 0xffff; strcpy(make, "Phase One"); if (model[0]) return; switch (raw_height) { case 2060: strcpy(model, "LightPhase"); break; case 2682: strcpy(model, "H 10"); break; case 4128: strcpy(model, "H 20"); break; case 5488: strcpy(model, "H 25"); break; } } void CLASS parse_fuji(int offset) { unsigned entries, tag, len, save, c; fseek(ifp, offset, SEEK_SET); entries = get4(); if (entries > 255) return; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_PARSEFUJI_PROCESSED; #endif while (entries--) { tag = get2(); len = get2(); save = ftell(ifp); if (tag == 0x100) { raw_height = get2(); raw_width = get2(); } else if (tag == 0x121) { height = get2(); if ((width = get2()) == 4284) width += 3; } else if (tag == 0x130) { fuji_layout = fgetc(ifp) >> 7; fuji_width = !(fgetc(ifp) & 8); } else if (tag == 0x131) { filters = 9; FORC(36) { int q = fgetc(ifp); xtrans_abs[0][35 - c] = MAX(0,MIN(q,2)); /* & 3;*/ } } else if (tag == 0x2ff0) { FORC4 cam_mul[c ^ 1] = get2(); // IB start #ifdef LIBRAW_LIBRARY_BUILD } else if (tag == 0x9650) { short a = (short)get2(); float b = fMAX(1.0f, get2()); imgdata.makernotes.fuji.FujiExpoMidPointShift = a / b; } else if (tag == 0x2f00) { int nWBs = get4(); nWBs = MIN(nWBs, 6); for (int wb_ind = 0; wb_ind < nWBs; wb_ind++) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Custom1 + wb_ind][c ^ 1] = get2(); fseek(ifp, 8, SEEK_CUR); } } else if (tag == 0x2000) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Auto][c ^ 1] = get2(); } else if (tag == 0x2100) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FineWeather][c ^ 1] = get2(); } else if (tag == 0x2200) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Shade][c ^ 1] = get2(); } else if (tag == 0x2300) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_D][c ^ 1] = get2(); } else if (tag == 0x2301) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_N][c ^ 1] = get2(); } else if (tag == 0x2302) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_WW][c ^ 1] = get2(); } else if (tag == 0x2310) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_FL_L][c ^ 1] = get2(); } else if (tag == 0x2400) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Tungsten][c ^ 1] = get2(); } else if (tag == 0x2410) { FORC4 imgdata.color.WB_Coeffs[LIBRAW_WBI_Flash][c ^ 1] = get2(); #endif // IB end } else if (tag == 0xc000) /* 0xc000 tag versions, second ushort; valid if the first ushort is 0 X100F 0x0259 X100T 0x0153 X-E2 0x014f 0x024f depends on firmware X-A1 0x014e XQ2 0x0150 XQ1 0x0150 X100S 0x0149 0x0249 depends on firmware X30 0x0152 X20 0x0146 X-T10 0x0154 X-T2 0x0258 X-M1 0x014d X-E2s 0x0355 X-A2 0x014e X-T20 0x025b GFX 50S 0x025a X-T1 0x0151 0x0251 0x0351 depends on firmware X70 0x0155 X-Pro2 0x0255 */ { c = order; order = 0x4949; if ((tag = get4()) > 10000) tag = get4(); if (tag > 10000) tag = get4(); width = tag; height = get4(); #ifdef LIBRAW_LIBRARY_BUILD if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { int wb[4]; int nWB, tWB, pWB; int iCCT = 0; int cnt; fseek(ifp, save + 0x200, SEEK_SET); for (int wb_ind = 0; wb_ind < 42; wb_ind++) { nWB = get4(); tWB = get4(); wb[0] = get4() << 1; wb[1] = get4(); wb[3] = get4(); wb[2] = get4() << 1; if (tWB && (iCCT < 255)) { imgdata.color.WBCT_Coeffs[iCCT][0] = tWB; for (cnt = 0; cnt < 4; cnt++) imgdata.color.WBCT_Coeffs[iCCT][cnt + 1] = wb[cnt]; iCCT++; } if (nWB != 70) { for (pWB = 1; pWB < nFuji_wb_list2; pWB += 2) { if (Fuji_wb_list2[pWB] == nWB) { for (cnt = 0; cnt < 4; cnt++) imgdata.color.WB_Coeffs[Fuji_wb_list2[pWB - 1]][cnt] = wb[cnt]; break; } } } } } else { libraw_internal_data.unpacker_data.posRAFData = save; libraw_internal_data.unpacker_data.lenRAFData = (len >> 1); } #endif order = c; } fseek(ifp, save + len, SEEK_SET); } height <<= fuji_layout; width >>= fuji_layout; } int CLASS parse_jpeg(int offset) { int len, save, hlen, mark; fseek(ifp, offset, SEEK_SET); if (fgetc(ifp) != 0xff || fgetc(ifp) != 0xd8) return 0; while (fgetc(ifp) == 0xff && (mark = fgetc(ifp)) != 0xda) { order = 0x4d4d; len = get2() - 2; save = ftell(ifp); if (mark == 0xc0 || mark == 0xc3 || mark == 0xc9) { fgetc(ifp); raw_height = get2(); raw_width = get2(); } order = get2(); hlen = get4(); if (get4() == 0x48454150 #ifdef LIBRAW_LIBRARY_BUILD && (save + hlen) >= 0 && (save + hlen) <= ifp->size() #endif ) /* "HEAP" */ { #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(save + hlen, len - hlen, 0); } if (parse_tiff(save + 6)) apply_tiff(); fseek(ifp, save + len, SEEK_SET); } return 1; } void CLASS parse_riff() { unsigned i, size, end; char tag[4], date[64], month[64]; static const char mon[12][4] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; struct tm t; order = 0x4949; fread(tag, 4, 1, ifp); size = get4(); end = ftell(ifp) + size; if (!memcmp(tag, "RIFF", 4) || !memcmp(tag, "LIST", 4)) { int maxloop = 1000; get4(); while (ftell(ifp) + 7 < end && !feof(ifp) && maxloop--) parse_riff(); } else if (!memcmp(tag, "nctg", 4)) { while (ftell(ifp) + 7 < end) { i = get2(); size = get2(); if ((i + 1) >> 1 == 10 && size == 20) get_timestamp(0); else fseek(ifp, size, SEEK_CUR); } } else if (!memcmp(tag, "IDIT", 4) && size < 64) { fread(date, 64, 1, ifp); date[size] = 0; memset(&t, 0, sizeof t); if (sscanf(date, "%*s %s %d %d:%d:%d %d", month, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec, &t.tm_year) == 6) { for (i = 0; i < 12 && strcasecmp(mon[i], month); i++) ; t.tm_mon = i; t.tm_year -= 1900; if (mktime(&t) > 0) timestamp = mktime(&t); } } else fseek(ifp, size, SEEK_CUR); } void CLASS parse_qt(int end) { unsigned save, size; char tag[4]; order = 0x4d4d; while (ftell(ifp) + 7 < end) { save = ftell(ifp); if ((size = get4()) < 8) return; fread(tag, 4, 1, ifp); if (!memcmp(tag, "moov", 4) || !memcmp(tag, "udta", 4) || !memcmp(tag, "CNTH", 4)) parse_qt(save + size); if (!memcmp(tag, "CNDA", 4)) parse_jpeg(ftell(ifp)); fseek(ifp, save + size, SEEK_SET); } } void CLASS parse_smal(int offset, int fsize) { int ver; fseek(ifp, offset + 2, SEEK_SET); order = 0x4949; ver = fgetc(ifp); if (ver == 6) fseek(ifp, 5, SEEK_CUR); if (get4() != fsize) return; if (ver > 6) data_offset = get4(); raw_height = height = get2(); raw_width = width = get2(); strcpy(make, "SMaL"); sprintf(model, "v%d %dx%d", ver, width, height); if (ver == 6) load_raw = &CLASS smal_v6_load_raw; if (ver == 9) load_raw = &CLASS smal_v9_load_raw; } void CLASS parse_cine() { unsigned off_head, off_setup, off_image, i; order = 0x4949; fseek(ifp, 4, SEEK_SET); is_raw = get2() == 2; fseek(ifp, 14, SEEK_CUR); is_raw *= get4(); off_head = get4(); off_setup = get4(); off_image = get4(); timestamp = get4(); if ((i = get4())) timestamp = i; fseek(ifp, off_head + 4, SEEK_SET); raw_width = get4(); raw_height = get4(); switch (get2(), get2()) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 16: load_raw = &CLASS unpacked_load_raw; } fseek(ifp, off_setup + 792, SEEK_SET); strcpy(make, "CINE"); sprintf(model, "%d", get4()); fseek(ifp, 12, SEEK_CUR); switch ((i = get4()) & 0xffffff) { case 3: filters = 0x94949494; break; case 4: filters = 0x49494949; break; default: is_raw = 0; } fseek(ifp, 72, SEEK_CUR); switch ((get4() + 3600) % 360) { case 270: flip = 4; break; case 180: flip = 1; break; case 90: flip = 7; break; case 0: flip = 2; } cam_mul[0] = getreal(11); cam_mul[2] = getreal(11); maximum = ~((~0u) << get4()); fseek(ifp, 668, SEEK_CUR); shutter = get4() / 1000000000.0; fseek(ifp, off_image, SEEK_SET); if (shot_select < is_raw) fseek(ifp, shot_select * 8, SEEK_CUR); data_offset = (INT64)get4() + 8; data_offset += (INT64)get4() << 32; } void CLASS parse_redcine() { unsigned i, len, rdvo; order = 0x4d4d; is_raw = 0; fseek(ifp, 52, SEEK_SET); width = get4(); height = get4(); fseek(ifp, 0, SEEK_END); fseek(ifp, -(i = ftello(ifp) & 511), SEEK_CUR); if (get4() != i || get4() != 0x52454f42) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: Tail is missing, parsing from head...\n"), ifname); #endif fseek(ifp, 0, SEEK_SET); while ((len = get4()) != EOF) { if (get4() == 0x52454456) if (is_raw++ == shot_select) data_offset = ftello(ifp) - 8; fseek(ifp, len - 8, SEEK_CUR); } } else { rdvo = get4(); fseek(ifp, 12, SEEK_CUR); is_raw = get4(); fseeko(ifp, rdvo + 8 + shot_select * 4, SEEK_SET); data_offset = get4(); } } /* All matrices are from Adobe DNG Converter unless otherwise noted. */ void CLASS adobe_coeff(const char *t_make, const char *t_model #ifdef LIBRAW_LIBRARY_BUILD , int internal_only #endif ) { // clang-format off static const struct { const char *prefix; int t_black, t_maximum, trans[12]; } table[] = { { "AgfaPhoto DC-833m", 0, 0, /* DJC */ { 11438,-3762,-1115,-2409,9914,2497,-1227,2295,5300 } }, { "Apple QuickTake", 0, 0, /* DJC */ { 21392,-5653,-3353,2406,8010,-415,7166,1427,2078 } }, {"Broadcom RPi IMX219", 66, 0x3ff, { 5302,1083,-728,-5320,14112,1699,-863,2371,5136 } }, /* LibRaw */ { "Broadcom RPi OV5647", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Canon EOS D2000", 0, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Canon EOS D6000", 0, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Canon EOS D30", 0, 0, /* updated */ { 9900,-2771,-1324,-7072,14229,3140,-2790,3344,8861 } }, { "Canon EOS D60", 0, 0xfa0, /* updated */ { 6211,-1358,-896,-8557,15766,3012,-3001,3507,8567 } }, { "Canon EOS 5DS", 0, 0x3c96, { 6250,-711,-808,-5153,12794,2636,-1249,2198,5610 } }, { "Canon EOS 5D Mark IV", 0, 0, { 6446,-366,-864,-4436,12204,2513,-952,2496,6348 } }, { "Canon EOS 5D Mark III", 0, 0x3c80, { 6722,-635,-963,-4287,12460,2028,-908,2162,5668 } }, { "Canon EOS 5D Mark II", 0, 0x3cf0, { 4716,603,-830,-7798,15474,2480,-1496,1937,6651 } }, { "Canon EOS 5D", 0, 0xe6c, { 6347,-479,-972,-8297,15954,2480,-1968,2131,7649 } }, { "Canon EOS 6D Mark II", 0, 0x38de, /* updated */ { 6875,-970,-932,-4691,12459,2501,-874,1953,5809 } }, { "Canon EOS 6D", 0, 0x3c82, /* skipped update */ { 8621,-2197,-787,-3150,11358,912,-1161,2400,4836 } }, { "Canon EOS 77D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 7D Mark II", 0, 0x3510, { 7268,-1082,-969,-4186,11839,2663,-825,2029,5839 } }, { "Canon EOS 7D", 0, 0x3510, { 6844,-996,-856,-3876,11761,2396,-593,1772,6198 } }, { "Canon EOS 800D", 0, 0, { 6970,-512,-968,-4425,12161,2553,-739,1982,5601 } }, { "Canon EOS 80D", 0, 0, { 7457,-671,-937,-4849,12495,2643,-1213,2354,5492 } }, { "Canon EOS 10D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 200D", 0, 0, { 7377,-742,-998,-4235,11981,2549,-673,1918,5538 } }, { "Canon EOS 20Da", 0, 0, { 14155,-5065,-1382,-6550,14633,2039,-1623,1824,6561 } }, { "Canon EOS 20D", 0, 0xfff, { 6599,-537,-891,-8071,15783,2424,-1983,2234,7462 } }, { "Canon EOS 30D", 0, 0, { 6257,-303,-1000,-7880,15621,2396,-1714,1904,7046 } }, { "Canon EOS 40D", 0, 0x3f60, { 6071,-747,-856,-7653,15365,2441,-2025,2553,7315 } }, { "Canon EOS 50D", 0, 0x3d93, { 4920,616,-593,-6493,13964,2784,-1774,3178,7005 } }, { "Canon EOS 60Da", 0, 0x2ff7, /* added */ { 17492,-7240,-2023,-1791,10323,1701,-186,1329,5406 } }, { "Canon EOS 60D", 0, 0x2ff7, { 6719,-994,-925,-4408,12426,2211,-887,2129,6051 } }, { "Canon EOS 70D", 0, 0x3bc7, { 7034,-804,-1014,-4420,12564,2058,-851,1994,5758 } }, { "Canon EOS 100D", 0, 0x350f, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 300D", 0, 0xfa0, /* updated */ { 8250,-2044,-1127,-8092,15606,2664,-2893,3453,8348 } }, { "Canon EOS 350D", 0, 0xfff, { 6018,-617,-965,-8645,15881,2975,-1530,1719,7642 } }, { "Canon EOS 400D", 0, 0xe8e, { 7054,-1501,-990,-8156,15544,2812,-1278,1414,7796 } }, { "Canon EOS 450D", 0, 0x390d, { 5784,-262,-821,-7539,15064,2672,-1982,2681,7427 } }, { "Canon EOS 500D", 0, 0x3479, { 4763,712,-646,-6821,14399,2640,-1921,3276,6561 } }, { "Canon EOS 550D", 0, 0x3dd7, { 6941,-1164,-857,-3825,11597,2534,-416,1540,6039 } }, { "Canon EOS 600D", 0, 0x3510, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 650D", 0, 0x354d, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 750D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 760D", 0, 0x3c00, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS 700D", 0, 0x3c00, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS 1000D", 0, 0xe43, { 6771,-1139,-977,-7818,15123,2928,-1244,1437,7533 } }, { "Canon EOS 1100D", 0, 0x3510, { 6444,-904,-893,-4563,12308,2535,-903,2016,6728 } }, { "Canon EOS 1200D", 0, 0x37c2, { 6461,-907,-882,-4300,12184,2378,-819,1944,5931 } }, { "Canon EOS 1300D", 0, 0x37c2, { 6939,-1016,-866,-4428,12473,2177,-1175,2178,6162 } }, { "Canon EOS M6", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M5", 0, 0, { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M3", 0, 0, { 6362,-823,-847,-4426,12109,2616,-743,1857,5635 } }, { "Canon EOS M2", 0, 0, /* added */ { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M100", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon EOS M10", 0, 0, { 6400,-480,-888,-5294,13416,2047,-1296,2203,6137 } }, { "Canon EOS M", 0, 0, { 6602,-841,-939,-4472,12458,2247,-975,2039,6148 } }, { "Canon EOS-1Ds Mark III", 0, 0x3bb0, { 5859,-211,-930,-8255,16017,2353,-1732,1887,7448 } }, { "Canon EOS-1Ds Mark II", 0, 0xe80, { 6517,-602,-867,-8180,15926,2378,-1618,1771,7633 } }, { "Canon EOS-1D Mark IV", 0, 0x3bb0, { 6014,-220,-795,-4109,12014,2361,-561,1824,5787 } }, { "Canon EOS-1D Mark III", 0, 0x3bb0, { 6291,-540,-976,-8350,16145,2311,-1714,1858,7326 } }, { "Canon EOS-1D Mark II N", 0, 0xe80, { 6240,-466,-822,-8180,15825,2500,-1801,1938,8042 } }, { "Canon EOS-1D Mark II", 0, 0xe80, { 6264,-582,-724,-8312,15948,2504,-1744,1919,8664 } }, { "Canon EOS-1DS", 0, 0xe20, /* updated */ { 3925,4060,-1739,-8973,16552,2545,-3287,3945,8243 } }, { "Canon EOS-1D C", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D X Mark II", 0, 0x3c4e, /* updated */ { 7596,-978,-967,-4808,12571,2503,-1398,2567,5752 } }, { "Canon EOS-1D X", 0, 0x3c4e, { 6847,-614,-1014,-4669,12737,2139,-1197,2488,6846 } }, { "Canon EOS-1D", 0, 0xe20, { 6806,-179,-1020,-8097,16415,1687,-3267,4236,7690 } }, { "Canon EOS C500", 853, 0, /* DJC */ { 17851,-10604,922,-7425,16662,763,-3660,3636,22278 } }, {"Canon PowerShot 600", 0, 0, /* added */ { -3822,10019,1311,4085,-157,3386,-5341,10829,4812,-1969,10969,1126 } }, { "Canon PowerShot A530", 0, 0, { 0 } }, /* don't want the A5 matrix */ { "Canon PowerShot A50", 0, 0, { -5300,9846,1776,3436,684,3939,-5540,9879,6200,-1404,11175,217 } }, { "Canon PowerShot A5", 0, 0, { -4801,9475,1952,2926,1611,4094,-5259,10164,5947,-1554,10883,547 } }, { "Canon PowerShot G10", 0, 0, { 11093,-3906,-1028,-5047,12492,2879,-1003,1750,5561 } }, { "Canon PowerShot G11", 0, 0, { 12177,-4817,-1069,-1612,9864,2049,-98,850,4471 } }, { "Canon PowerShot G12", 0, 0, { 13244,-5501,-1248,-1508,9858,1935,-270,1083,4366 } }, { "Canon PowerShot G15", 0, 0, { 7474,-2301,-567,-4056,11456,2975,-222,716,4181 } }, { "Canon PowerShot G16", 0, 0, /* updated */ { 8020,-2687,-682,-3704,11879,2052,-965,1921,5556 } }, { "Canon PowerShot G1 X Mark III", 0, 0, /* temp */ { 8532,-701,-1167,-4095,11879,2508,-797,2424,7010 } }, { "Canon PowerShot G1 X Mark II", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1 X", 0, 0, { 7378,-1255,-1043,-4088,12251,2048,-876,1946,5805 } }, { "Canon PowerShot G1", 0, 0, /* updated */ { -5686,10300,2223,4725,-1157,4383,-6128,10783,6163,-2688,12093,604 } }, { "Canon PowerShot G2", 0, 0, /* updated */ { 9194,-2787,-1059,-8098,15657,2608,-2610,3064,7867 } }, { "Canon PowerShot G3 X", 0, 0, { 9701,-3857,-921,-3149,11537,1817,-786,1817,5147 } }, { "Canon PowerShot G3", 0, 0, /* updated */ { 9326,-2882,-1084,-7940,15447,2677,-2620,3090,7740 } }, { "Canon PowerShot G5 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G5", 0, 0, /* updated */ { 9869,-2972,-942,-7314,15098,2369,-1898,2536,7282 } }, { "Canon PowerShot G6", 0, 0, { 9877,-3775,-871,-7613,14807,3072,-1448,1305,7485 } }, { "Canon PowerShot G7 X Mark II", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G7 X", 0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9 X Mark II", 0, 0, { 10056,-4131,-944,-2576,11143,1625,-238,1294,5179 } }, { "Canon PowerShot G9 X",0, 0, { 9602,-3823,-937,-2984,11495,1675,-407,1415,5049 } }, { "Canon PowerShot G9", 0, 0, { 7368,-2141,-598,-5621,13254,2625,-1418,1696,5743 } }, { "Canon PowerShot Pro1", 0, 0, { 10062,-3522,-999,-7643,15117,2730,-765,817,7323 } }, { "Canon PowerShot Pro70", 34, 0, /* updated */ { -5106,10695,1576,3820,53,4566,-6497,10736,6701,-3336,11887,1394 } }, { "Canon PowerShot Pro90", 0, 0, /* updated */ { -5912,10768,2288,4612,-989,4333,-6153,10897,5944,-2907,12288,624 } }, { "Canon PowerShot S30", 0, 0, /* updated */ { 10744,-3813,-1142,-7962,15966,2075,-2492,2805,7744 } }, { "Canon PowerShot S40", 0, 0, /* updated */ { 8606,-2573,-949,-8237,15489,2974,-2649,3076,9100 } }, { "Canon PowerShot S45", 0, 0, /* updated */ { 8251,-2410,-964,-8047,15430,2823,-2380,2824,8119 } }, { "Canon PowerShot S50", 0, 0, /* updated */ { 8979,-2658,-871,-7721,15500,2357,-1773,2366,6634 } }, { "Canon PowerShot S60", 0, 0, { 8795,-2482,-797,-7804,15403,2573,-1422,1996,7082 } }, { "Canon PowerShot S70", 0, 0, { 9976,-3810,-832,-7115,14463,2906,-901,989,7889 } }, { "Canon PowerShot S90", 0, 0, { 12374,-5016,-1049,-1677,9902,2078,-83,852,4683 } }, { "Canon PowerShot S95", 0, 0, { 13440,-5896,-1279,-1236,9598,1931,-180,1001,4651 } }, { "Canon PowerShot S120", 0, 0, { 6961,-1685,-695,-4625,12945,1836,-1114,2152,5518 } }, { "Canon PowerShot S110", 0, 0, { 8039,-2643,-654,-3783,11230,2930,-206,690,4194 } }, { "Canon PowerShot S100", 0, 0, { 7968,-2565,-636,-2873,10697,2513,180,667,4211 } }, { "Canon PowerShot SX1 IS", 0, 0, { 6578,-259,-502,-5974,13030,3309,-308,1058,4970 } }, { "Canon PowerShot SX50 HS", 0, 0, { 12432,-4753,-1247,-2110,10691,1629,-412,1623,4926 } }, { "Canon PowerShot SX60 HS", 0, 0, { 13161,-5451,-1344,-1989,10654,1531,-47,1271,4955 } }, { "Canon PowerShot A3300", 0, 0, /* DJC */ { 10826,-3654,-1023,-3215,11310,1906,0,999,4960 } }, { "Canon PowerShot A470", 0, 0, /* DJC */ { 12513,-4407,-1242,-2680,10276,2405,-878,2215,4734 } }, { "Canon PowerShot A610", 0, 0, /* DJC */ { 15591,-6402,-1592,-5365,13198,2168,-1300,1824,5075 } }, { "Canon PowerShot A620", 0, 0, /* DJC */ { 15265,-6193,-1558,-4125,12116,2010,-888,1639,5220 } }, { "Canon PowerShot A630", 0, 0, /* DJC */ { 14201,-5308,-1757,-6087,14472,1617,-2191,3105,5348 } }, { "Canon PowerShot A640", 0, 0, /* DJC */ { 13124,-5329,-1390,-3602,11658,1944,-1612,2863,4885 } }, { "Canon PowerShot A650", 0, 0, /* DJC */ { 9427,-3036,-959,-2581,10671,1911,-1039,1982,4430 } }, { "Canon PowerShot A720", 0, 0, /* DJC */ { 14573,-5482,-1546,-1266,9799,1468,-1040,1912,3810 } }, { "Canon PowerShot D10", 127, 0, /* DJC */ { 14052,-5229,-1156,-1325,9420,2252,-498,1957,4116 } }, { "Canon PowerShot S3 IS", 0, 0, /* DJC */ { 14062,-5199,-1446,-4712,12470,2243,-1286,2028,4836 } }, { "Canon PowerShot SX110 IS", 0, 0, /* DJC */ { 14134,-5576,-1527,-1991,10719,1273,-1158,1929,3581 } }, { "Canon PowerShot SX220", 0, 0, /* DJC */ { 13898,-5076,-1447,-1405,10109,1297,-244,1860,3687 } }, { "Canon IXUS 160", 0, 0, /* DJC */ { 11657,-3781,-1136,-3544,11262,2283,-160,1219,4700 } }, { "Casio EX-F1", 0, 0, /* added */ { 9084,-2016,-848,-6711,14351,2570,-1059,1725,6135 } }, { "Casio EX-FH100", 0, 0, /* added */ { 12771,-4179,-1558,-2149,10938,1375,-453,1751,4494 } }, { "Casio EX-S20", 0, 0, /* DJC */ { 11634,-3924,-1128,-4968,12954,2015,-1588,2648,7206 } }, { "Casio EX-Z750", 0, 0, /* DJC */ { 10819,-3873,-1099,-4903,13730,1175,-1755,3751,4632 } }, { "Casio EX-Z10", 128, 0xfff, /* DJC */ { 9790,-3338,-603,-2321,10222,2099,-344,1273,4799 } }, { "CINE 650", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE 660", 0, 0, { 3390,480,-500,-800,3610,340,-550,2336,1192 } }, { "CINE", 0, 0, { 20183,-4295,-423,-3940,15330,3985,-280,4870,9800 } }, { "Contax N Digital", 0, 0xf1e, { 7777,1285,-1053,-9280,16543,2916,-3677,5679,7060 } }, { "DXO ONE", 0, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Epson R-D1", 0, 0, { 6827,-1878,-732,-8429,16012,2564,-704,592,7145 } }, { "Fujifilm E550", 0, 0, /* updated */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm E900", 0, 0, { 9183,-2526,-1078,-7461,15071,2574,-2022,2440,8639 } }, { "Fujifilm F5", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F6", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F77", 0, 0xfe9, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm F7", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm F810", 0, 0, /* added */ { 11044,-3888,-1120,-7248,15167,2208,-1531,2276,8069 } }, { "Fujifilm F8", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm S100FS", 514, 0, { 11521,-4355,-1065,-6524,13767,3058,-1466,1984,6045 } }, { "Fujifilm S1", 0, 0, { 12297,-4882,-1202,-2106,10691,1623,-88,1312,4790 } }, { "Fujifilm S20Pro", 0, 0, { 10004,-3219,-1201,-7036,15047,2107,-1863,2565,7736 } }, { "Fujifilm S20", 512, 0x3fff, { 11401,-4498,-1312,-5088,12751,2613,-838,1568,5941 } }, { "Fujifilm S2Pro", 128, 0, /* updated */ { 12741,-4916,-1420,-8510,16791,1715,-1767,2302,7771 } }, { "Fujifilm S3Pro", 0, 0, { 11807,-4612,-1294,-8927,16968,1988,-2120,2741,8006 } }, { "Fujifilm S5Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm S5000", 0, 0, { 8754,-2732,-1019,-7204,15069,2276,-1702,2334,6982 } }, { "Fujifilm S5100", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5500", 0, 0, { 11940,-4431,-1255,-6766,14428,2542,-993,1165,7421 } }, { "Fujifilm S5200", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S5600", 0, 0, { 9636,-2804,-988,-7442,15040,2589,-1803,2311,8621 } }, { "Fujifilm S6", 0, 0, { 12628,-4887,-1401,-6861,14996,1962,-2198,2782,7091 } }, { "Fujifilm S7000", 0, 0, { 10190,-3506,-1312,-7153,15051,2238,-2003,2399,7505 } }, { "Fujifilm S9000", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9500", 0, 0, { 10491,-3423,-1145,-7385,15027,2538,-1809,2275,8692 } }, { "Fujifilm S9100", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm S9600", 0, 0, { 12343,-4515,-1285,-7165,14899,2435,-1895,2496,8800 } }, { "Fujifilm SL1000", 0, 0, { 11705,-4262,-1107,-2282,10791,1709,-555,1713,4945 } }, { "Fujifilm IS-1", 0, 0, { 21461,-10807,-1441,-2332,10599,1999,289,875,7703 } }, { "Fujifilm IS Pro", 0, 0, { 12300,-5110,-1304,-9117,17143,1998,-1947,2448,8100 } }, { "Fujifilm HS10 HS11", 0, 0xf68, { 12440,-3954,-1183,-1123,9674,1708,-83,1614,4086 } }, { "Fujifilm HS2", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS3", 0, 0, { 13690,-5358,-1474,-3369,11600,1998,-132,1554,4395 } }, { "Fujifilm HS50EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm F900EXR", 0, 0, { 12085,-4727,-953,-3257,11489,2002,-511,2046,4592 } }, { "Fujifilm X100S", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100F", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X100T", 0, 0, { 10592,-4262,-1008,-3514,11355,2465,-870,2025,6386 } }, { "Fujifilm X100", 0, 0, { 12161,-4457,-1069,-5034,12874,2400,-795,1724,6904 } }, { "Fujifilm X10", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X20", 0, 0, { 11768,-4971,-1133,-4904,12927,2183,-480,1723,4605 } }, { "Fujifilm X30", 0, 0, { 12328,-5256,-1144,-4469,12927,1675,-87,1291,4351 } }, { "Fujifilm X70", 0, 0, { 10450,-4329,-878,-3217,11105,2421,-752,1758,6519 } }, { "Fujifilm X-Pro1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-Pro2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-A10", 0, 0, { 11540,-4999,-991,-2949,10963,2278,-382,1049,5605} }, { "Fujifilm X-A1", 0, 0, { 11086,-4555,-839,-3512,11310,2517,-815,1341,5940 } }, { "Fujifilm X-A2", 0, 0, { 10763,-4560,-917,-3346,11311,2322,-475,1135,5843 } }, { "Fujifilm X-A3", 0, 0, { 12407,-5222,-1086,-2971,11116,2120,-294,1029,5284 } }, { "Fujifilm X-E1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-E2S", 0, 0, { 11562,-5118,-961,-3022,11007,2311,-525,1569,6097 } }, { "Fujifilm X-E2", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-E3", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm XF1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-M1", 0, 0, { 10413,-3996,-993,-3721,11640,2361,-733,1540,6011 } }, { "Fujifilm X-S1", 0, 0, { 13509,-6199,-1254,-4430,12733,1865,-331,1441,5022 } }, { "Fujifilm X-T20", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T2", 0, 0, { 11434,-4948,-1210,-3746,12042,1903,-666,1479,5235 } }, { "Fujifilm X-T10", 0, 0, /* updated */ { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm X-T1", 0, 0, { 8458,-2451,-855,-4597,12447,2407,-1475,2482,6526 } }, { "Fujifilm XQ1", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm XQ2", 0, 0, { 9252,-2704,-1064,-5893,14265,1717,-1101,2341,4349 } }, { "Fujifilm GFX 50S", 0, 0, { 11756,-4754,-874,-3056,11045,2305,-381,1457,6006 } }, { "GITUP GIT2P", 4160, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "GITUP GIT2", 3200, 0, { 8489, -2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Hasselblad HV", 0, 0, /* added */ { 6344,-1612,-461,-4862,12476,2680,-864,1785,6898 } }, { "Hasselblad Lunar", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Hasselblad Lusso", 0, 0, /* added */ { 4912,-540,-201,-6129,13513,2906,-1563,2151,7182 } }, { "Hasselblad Stellar", -800, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, { "Hasselblad 500 mech.", 0, 0, /* added */ { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad CFV", 0, 0, { 8519,-3260,-280,-5081,13459,1738,-1449,2960,7809 } }, { "Hasselblad H-16MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-22MP", 0, 0, /* LibRaw */ { 17765,-5322,-1734,-6168,13354,2135,-264,2524,7440 } }, { "Hasselblad H-31MP",0, 0, /* LibRaw */ { 14480,-5448,-1686,-3534,13123,2260,384,2952,7232 } }, { "Hasselblad 39-Coated", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H-39MP",0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H2D-39", 0, 0, /* added */ { 3894,-110,287,-4672,12610,2295,-2092,4100,6196 } }, { "Hasselblad H3D-50", 0, 0, { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H3D", 0, 0, /* added */ { 3857,452,-46,-6008,14477,1596,-2627,4481,5718 } }, { "Hasselblad H4D-40",0, 0, /* LibRaw */ { 6325,-860,-957,-6559,15945,266,167,770,5936 } }, { "Hasselblad H4D-50",0, 0, /* LibRaw */ { 15283,-6272,-465,-2030,16031,478,-2379,390,7965 } }, { "Hasselblad H4D-60",0, 0, { 9662,-684,-279,-4903,12293,2950,-344,1669,6024 } }, { "Hasselblad H5D-50c",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "Hasselblad H5D-50",0, 0, { 5656,-659,-346,-3923,12306,1791,-1602,3509,5442 } }, { "Hasselblad H6D-100c",0, 0, { 5110,-1357,-308,-5573,12835,3077,-1279,2025,7010 } }, { "Hasselblad X1D",0, 0, { 4932,-835,141,-4878,11868,3437,-1138,1961,7067 } }, { "HTC One A9", 64, 1023, /* this is CM1 transposed */ { 101, -20, -2, -11, 145, 41, -24, 1, 56 } }, { "Imacon Ixpress", 0, 0, /* DJC */ { 7025,-1415,-704,-5188,13765,1424,-1248,2742,6038 } }, { "Kodak NC2000", 0, 0, { 13891,-6055,-803,-465,9919,642,2121,82,1291 } }, { "Kodak DCS315C", -8, 0, { 17523,-4827,-2510,756,8546,-137,6113,1649,2250 } }, { "Kodak DCS330C", -8, 0, { 20620,-7572,-2801,-103,10073,-396,3551,-233,2220 } }, { "Kodak DCS420", 0, 0, { 10868,-1852,-644,-1537,11083,484,2343,628,2216 } }, { "Kodak DCS460", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS1", 0, 0, { 10592,-2206,-967,-1944,11685,230,2206,670,1273 } }, { "Kodak EOSDCS3B", 0, 0, { 9898,-2700,-940,-2478,12219,206,1985,634,1031 } }, { "Kodak DCS520C", -178, 0, { 24542,-10860,-3401,-1490,11370,-297,2858,-605,3225 } }, { "Kodak DCS560C", -177, 0, { 20482,-7172,-3125,-1033,10410,-285,2542,226,3136 } }, { "Kodak DCS620C", -177, 0, { 23617,-10175,-3149,-2054,11749,-272,2586,-489,3453 } }, { "Kodak DCS620X", -176, 0, { 13095,-6231,154,12221,-21,-2137,895,4602,2258 } }, { "Kodak DCS660C", -173, 0, { 18244,-6351,-2739,-791,11193,-521,3711,-129,2802 } }, { "Kodak DCS720X", 0, 0, { 11775,-5884,950,9556,1846,-1286,-1019,6221,2728 } }, { "Kodak DCS760C", 0, 0, { 16623,-6309,-1411,-4344,13923,323,2285,274,2926 } }, { "Kodak DCS Pro SLR", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14nx", 0, 0, { 5494,2393,-232,-6427,13850,2846,-1876,3997,5445 } }, { "Kodak DCS Pro 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Photo Control Camerz ZDS 14", 0, 0, { 7791,3128,-776,-8588,16458,2039,-2455,4006,6198 } }, { "Kodak ProBack645", 0, 0, { 16414,-6060,-1470,-3555,13037,473,2545,122,4948 } }, { "Kodak ProBack", 0, 0, { 21179,-8316,-2918,-915,11019,-165,3477,-180,4210 } }, { "Kodak P712", 0, 0, { 9658,-3314,-823,-5163,12695,2768,-1342,1843,6044 } }, { "Kodak P850", 0, 0xf7c, { 10511,-3836,-1102,-6946,14587,2558,-1481,1792,6246 } }, { "Kodak P880", 0, 0xfff, { 12805,-4662,-1376,-7480,15267,2360,-1626,2194,7904 } }, { "Kodak EasyShare Z980", 0, 0, { 11313,-3559,-1101,-3893,11891,2257,-1214,2398,4908 } }, { "Kodak EasyShare Z981", 0, 0, { 12729,-4717,-1188,-1367,9187,2582,274,860,4411 } }, { "Kodak EasyShare Z990", 0, 0xfed, { 11749,-4048,-1309,-1867,10572,1489,-138,1449,4522 } }, { "Kodak EASYSHARE Z1015", 0, 0xef1, { 11265,-4286,-992,-4694,12343,2647,-1090,1523,5447 } }, { "Leaf C-Most", 0, 0, /* updated */ { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Valeo 6", 0, 0, { 3952,2189,449,-6701,14585,2275,-4536,7349,6536 } }, { "Leaf Aptus 54S", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leaf Aptus-II 8", 0, 0, /* added */ { 7361,1257,-163,-6929,14061,3176,-1839,3454,5603 } }, { "Leaf AFi-II 7", 0, 0, /* added */ { 7691,-108,-339,-6185,13627,2833,-2046,3899,5952 } }, { "Leaf Aptus-II 5", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 65", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 65S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Aptus 75", 0, 0, { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf AFi 75S", 0, 0, /* added */ { 7914,1414,-1190,-8777,16582,2280,-2811,4605,5562 } }, { "Leaf Credo 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 50", 0, 0, { 3984,0,0,0,10000,0,0,0,7666 } }, { "Leaf Credo 60", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Leaf Credo 80", 0, 0, { 6294,686,-712,-5435, 13417,2211,-1006,2435,5042 } }, { "Leaf", 0, 0, { 8236,1746,-1314,-8251,15953,2428,-3673,5786,5771 } }, { "Leica M10", 0, 0, /* added */ { 9090,-3342,-740,-4006,13456,493,-569,2266,6871 } }, { "Leica M9", 0, 0, /* added */ { 6687,-1751,-291,-3556,11373,2492,-548,2204,7146 } }, { "Leica M8", 0, 0, /* added */ { 7675,-2196,-305,-5860,14119,1856,-2425,4006,6578 } }, { "Leica M (Typ 240)", 0, 0, /* added */ { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica M (Typ 262)", 0, 0, { 7199,-2140,-712,-4005,13327,649,-810,2521,6673 } }, { "Leica SL (Typ 601)", 0, 0, { 11865,-4523,-1441,-5423,14458,935,-1587,2687,4830} }, { "Leica S2", 0, 0, /* added */ { 5627,-721,-447,-4423,12456,2192,-1048,2948,7379 } }, {"Leica S-E (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, {"Leica S (Typ 006)", 0, 0, /* added */ { 5749,-1072,-382,-4274,12432,2048,-1166,3104,7105 } }, { "Leica S (Typ 007)", 0, 0, { 6063,-2234,-231,-5210,13787,1500,-1043,2866,6997 } }, { "Leica Q (Typ 116)", 0, 0, /* updated */ { 10068,-4043,-1068,-5319,14268,1044,-765,1701,6522 } }, { "Leica T (Typ 701)", 0, 0, /* added */ { 6295 ,-1679 ,-475 ,-5586 ,13046 ,2837 ,-1410 ,1889 ,7075 } }, { "Leica X2", 0, 0, /* added */ { 8336,-2853,-699,-4425,11989,2760,-954,1625,6396 } }, { "Leica X1", 0, 0, /* added */ { 9055,-2611,-666,-4906,12652,2519,-555,1384,7417 } }, { "Leica X", 0, 0, /* X(113), X-U(113), XV, X Vario(107) */ /* updated */ { 9062,-3198,-828,-4065,11772,2603,-761,1468,6458 } }, { "Mamiya M31", 0, 0, /* added */ { 4516 ,-244 ,-36 ,-7020 ,14976 ,2174 ,-3206 ,4670 ,7087 } }, { "Mamiya M22", 0, 0, /* added */ { 2905 ,732 ,-237 ,-8135 ,16626 ,1476 ,-3038 ,4253 ,7517 } }, { "Mamiya M18", 0, 0, /* added */ { 6516 ,-2050 ,-507 ,-8217 ,16703 ,1479 ,-3492 ,4741 ,8489 } }, { "Mamiya ZD", 0, 0, { 7645,2579,-1363,-8689,16717,2015,-3712,5941,5961 } }, { "Micron 2010", 110, 0, /* DJC */ { 16695,-3761,-2151,155,9682,163,3433,951,4904 } }, { "Minolta DiMAGE 5", 0, 0xf7d, /* updated */ { 9117,-3063,-973,-7949,15763,2306,-2752,3136,8093 } }, { "Minolta DiMAGE 7Hi", 0, 0xf7d, /* updated */ { 11555,-4064,-1256,-7903,15633,2409,-2811,3320,7358 } }, { "Minolta DiMAGE 7i", 0, 0xf7d, /* added */ { 11050,-3791,-1199,-7875,15585,2434,-2797,3359,7560 } }, { "Minolta DiMAGE 7", 0, 0xf7d, /* updated */ { 9258,-2879,-1008,-8076,15847,2351,-2806,3280,7821 } }, { "Minolta DiMAGE A1", 0, 0xf8b, /* updated */ { 9274,-2548,-1167,-8220,16324,1943,-2273,2721,8340 } }, { "Minolta DiMAGE A200", 0, 0, { 8560,-2487,-986,-8112,15535,2771,-1209,1324,7743 } }, { "Minolta DiMAGE A2", 0, 0xf8f, { 9097,-2726,-1053,-8073,15506,2762,-966,981,7763 } }, { "Minolta DiMAGE Z2", 0, 0, /* DJC */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Minolta DYNAX 5", 0, 0xffb, { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta Maxxum 5D", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA-5 DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta ALPHA SWEET DIGITAL", 0, 0xffb, /* added */ { 10284,-3283,-1086,-7957,15762,2316,-829,882,6644 } }, { "Minolta DYNAX 7", 0, 0xffb, { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta Maxxum 7D", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Minolta ALPHA-7 DIGITAL", 0, 0xffb, /* added */ { 10239,-3104,-1099,-8037,15727,2451,-927,925,6871 } }, { "Motorola PIXL", 0, 0, /* DJC */ { 8898,-989,-1033,-3292,11619,1674,-661,3178,5216 } }, { "Nikon D100", 0, 0, { 5902,-933,-782,-8983,16719,2354,-1402,1455,6464 } }, { "Nikon D1H", 0, 0, /* updated */ { 7659,-2238,-935,-8942,16969,2004,-2701,3051,8690 } }, { "Nikon D1X", 0, 0, { 7702,-2245,-975,-9114,17242,1875,-2679,3055,8521 } }, { "Nikon D1", 0, 0, /* multiplied by 2.218750, 1.0, 1.148438 */ { 16772,-4726,-2141,-7611,15713,1972,-2846,3494,9521 } }, { "Nikon D200", 0, 0xfbc, { 8367,-2248,-763,-8758,16447,2422,-1527,1550,8053 } }, { "Nikon D2H", 0, 0, { 5733,-911,-629,-7967,15987,2055,-3050,4013,7048 } }, { "Nikon D2X", 0, 0, /* updated */ { 10231,-2768,-1254,-8302,15900,2551,-797,681,7148 } }, { "Nikon D3000", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D3100", 0, 0, { 7911,-2167,-813,-5327,13150,2408,-1288,2483,7968 } }, { "Nikon D3200", 0, 0xfb9, { 7013,-1408,-635,-5268,12902,2640,-1470,2801,7379 } }, { "Nikon D3300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D3400", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D300", 0, 0, { 9030,-1992,-715,-8465,16302,2255,-2689,3217,8069 } }, { "Nikon D3X", 0, 0, { 7171,-1986,-648,-8085,15555,2718,-2170,2512,7457 } }, { "Nikon D3S", 0, 0, { 8828,-2406,-694,-4874,12603,2541,-660,1509,7587 } }, { "Nikon D3", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D40X", 0, 0, { 8819,-2543,-911,-9025,16928,2151,-1329,1213,8449 } }, { "Nikon D40", 0, 0, { 6992,-1668,-806,-8138,15748,2543,-874,850,7897 } }, { "Nikon D4S", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D4", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon Df", 0, 0, { 8598,-2848,-857,-5618,13606,2195,-1002,1773,7137 } }, { "Nikon D5000", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2433,2826,8064 } }, { "Nikon D5100", 0, 0x3de6, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D5200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D5300", 0, 0, { 6988,-1384,-714,-5631,13410,2447,-1485,2204,7318 } }, { "Nikon D5500", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D5600", 0, 0, { 8821,-2938,-785,-4178,12142,2287,-824,1651,6860 } }, { "Nikon D500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D50", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D5", 0, 0, { 9200,-3522,-992,-5755,13803,2117,-753,1486,6338 } }, { "Nikon D600", 0, 0x3e07, { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D610",0, 0, /* updated */ { 8178,-2245,-609,-4857,12394,2776,-1207,2086,7298 } }, { "Nikon D60", 0, 0, { 8736,-2458,-935,-9075,16894,2251,-1354,1242,8263 } }, { "Nikon D7000", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon D7100", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7200", 0, 0, { 8322,-3112,-1047,-6367,14342,2179,-988,1638,6394 } }, { "Nikon D7500", 0, 0, { 8813,-3210,-1036,-4703,12868,2021,-1054,1940,6129 } }, { "Nikon D750", -600, 0, { 9020,-2890,-715,-4535,12436,2348,-934,1919,7086 } }, { "Nikon D700", 0, 0, { 8139,-2171,-663,-8747,16541,2295,-1925,2008,8093 } }, { "Nikon D70", 0, 0, { 7732,-2422,-789,-8238,15884,2498,-859,783,7330 } }, { "Nikon D850", 0, 0, { 10405,-3755,-1270,-5461,13787,1793,-1040,2015,6785 } }, { "Nikon D810A", 0, 0, { 11973,-5685,-888,-1965,10326,1901,-115,1123,7169 } }, { "Nikon D810", 0, 0, { 9369,-3195,-791,-4488,12430,2301,-893,1796,6872 } }, { "Nikon D800", 0, 0, { 7866,-2108,-555,-4869,12483,2681,-1176,2069,7501 } }, { "Nikon D80", 0, 0, { 8629,-2410,-883,-9055,16940,2171,-1490,1363,8520 } }, { "Nikon D90", 0, 0xf00, { 7309,-1403,-519,-8474,16008,2622,-2434,2826,8064 } }, { "Nikon E700", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E800", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E950", 0, 0x3dd, /* DJC */ { -3746,10611,1665,9621,-1734,2114,-2389,7082,3064,3406,6116,-244 } }, { "Nikon E995", 0, 0, /* copied from E5000 */ { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E2100", 0, 0, /* copied from Z2, new white balance */ { 13142,-4152,-1596,-4655,12374,2282,-1769,2696,6711 } }, { "Nikon E2500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E3200", 0, 0, /* DJC */ { 9846,-2085,-1019,-3278,11109,2170,-774,2134,5745 } }, { "Nikon E4300", 0, 0, /* copied from Minolta DiMAGE Z2 */ { 11280,-3564,-1370,-4655,12374,2282,-1423,2168,5396 } }, { "Nikon E4500", 0, 0, { -5547,11762,2189,5814,-558,3342,-4924,9840,5949,688,9083,96 } }, { "Nikon E5000", 0, 0, /* updated */ { -6678,12805,2248,5725,-499,3375,-5903,10713,6034,-270,9976,134 } }, { "Nikon E5400", 0, 0, /* updated */ { 9349,-2988,-1001,-7918,15766,2266,-2097,2680,6839 } }, { "Nikon E5700", 0, 0, /* updated */ { -6475,12496,2428,5409,-16,3180,-5965,10912,5866,-177,9918,248 } }, { "Nikon E8400", 0, 0, { 7842,-2320,-992,-8154,15718,2599,-1098,1342,7560 } }, { "Nikon E8700", 0, 0, { 8489,-2583,-1036,-8051,15583,2643,-1307,1407,7354 } }, { "Nikon E8800", 0, 0, { 7971,-2314,-913,-8451,15762,2894,-1442,1520,7610 } }, { "Nikon COOLPIX A", 0, 0, { 8198,-2239,-724,-4871,12389,2798,-1043,2050,7181 } }, { "Nikon COOLPIX B700", 0, 0, { 14387,-6014,-1299,-1357,9975,1616,467,1047,4744 } }, { "Nikon COOLPIX P330", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P340", -200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Kalon", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX Deneb", 0, 0, /* added */ { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P6000", 0, 0, { 9698,-3367,-914,-4706,12584,2368,-837,968,5801 } }, { "Nikon COOLPIX P7000", 0, 0, { 11432,-3679,-1111,-3169,11239,2202,-791,1380,4455 } }, { "Nikon COOLPIX P7100", 0, 0, { 11053,-4269,-1024,-1976,10182,2088,-526,1263,4469 } }, { "Nikon COOLPIX P7700", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon COOLPIX P7800", -3200, 0, { 10321,-3920,-931,-2750,11146,1824,-442,1545,5539 } }, { "Nikon 1 V3", -200, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J4", 0, 0, { 5958,-1559,-571,-4021,11453,2939,-634,1548,5087 } }, { "Nikon 1 J5", 0, 0, { 7520,-2518,-645,-3844,12102,1945,-913,2249,6835 } }, { "Nikon 1 S2", -200, 0, { 6612,-1342,-618,-3338,11055,2623,-174,1792,5075 } }, { "Nikon 1 V2", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 J3", 0, 0, /* updated */ { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 AW1", 0, 0, { 6588,-1305,-693,-3277,10987,2634,-355,2016,5106 } }, { "Nikon 1 ", 0, 0, /* J1, J2, S1, V1 */ { 8994,-2667,-865,-4594,12324,2552,-699,1786,6260 } }, { "Olympus AIR-A01", 0, 0xfe1, { 8992,-3093,-639,-2563,10721,2122,-437,1270,5473 } }, { "Olympus C5050", 0, 0, /* updated */ { 10633,-3234,-1285,-7460,15570,1967,-1917,2510,6299 } }, { "Olympus C5060", 0, 0, { 10445,-3362,-1307,-7662,15690,2058,-1135,1176,7602 } }, { "Olympus C7070", 0, 0, { 10252,-3531,-1095,-7114,14850,2436,-1451,1723,6365 } }, { "Olympus C70", 0, 0, { 10793,-3791,-1146,-7498,15177,2488,-1390,1577,7321 } }, { "Olympus C80", 0, 0, { 8606,-2509,-1014,-8238,15714,2703,-942,979,7760 } }, { "Olympus E-10", 0, 0xffc, /* updated */ { 12970,-4703,-1433,-7466,15843,1644,-2191,2451,6668 } }, { "Olympus E-1", 0, 0, { 11846,-4767,-945,-7027,15878,1089,-2699,4122,8311 } }, { "Olympus E-20", 0, 0xffc, /* updated */ { 13414,-4950,-1517,-7166,15293,1960,-2325,2664,7212 } }, { "Olympus E-300", 0, 0, { 7828,-1761,-348,-5788,14071,1830,-2853,4518,6557 } }, { "Olympus E-330", 0, 0, { 8961,-2473,-1084,-7979,15990,2067,-2319,3035,8249 } }, { "Olympus E-30", 0, 0xfbc, { 8144,-1861,-1111,-7763,15894,1929,-1865,2542,7607 } }, { "Olympus E-3", 0, 0xf99, { 9487,-2875,-1115,-7533,15606,2010,-1618,2100,7389 } }, { "Olympus E-400", 0, 0, { 6169,-1483,-21,-7107,14761,2536,-2904,3580,8568 } }, { "Olympus E-410", 0, 0xf6a, { 8856,-2582,-1026,-7761,15766,2082,-2009,2575,7469 } }, { "Olympus E-420", 0, 0xfd7, { 8746,-2425,-1095,-7594,15612,2073,-1780,2309,7416 } }, { "Olympus E-450", 0, 0xfd2, { 8745,-2425,-1095,-7594,15613,2073,-1780,2309,7416 } }, { "Olympus E-500", 0, 0, { 8136,-1968,-299,-5481,13742,1871,-2556,4205,6630 } }, { "Olympus E-510", 0, 0xf6a, { 8785,-2529,-1033,-7639,15624,2112,-1783,2300,7817 } }, { "Olympus E-520", 0, 0xfd2, { 8344,-2322,-1020,-7596,15635,2048,-1748,2269,7287 } }, { "Olympus E-5", 0, 0xeec, { 11200,-3783,-1325,-4576,12593,2206,-695,1742,7504 } }, { "Olympus E-600", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-620", 0, 0xfaf, { 8453,-2198,-1092,-7609,15681,2008,-1725,2337,7824 } }, { "Olympus E-P1", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P2", 0, 0xffd, { 8343,-2050,-1021,-7715,15705,2103,-1831,2380,8235 } }, { "Olympus E-P3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-P5", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL1s", 0, 0, { 11409,-3872,-1393,-4572,12757,2003,-709,1810,7415 } }, { "Olympus E-PL1", 0, 0, { 11408,-4289,-1215,-4286,12385,2118,-387,1467,7787 } }, { "Olympus E-PL2", 0, 0xcf3, { 15030,-5552,-1806,-3987,12387,1767,-592,1670,7023 } }, { "Olympus E-PL3", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PL5", 0, 0xfcb, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL6", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-PL7", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PL8", 0, 0, { 9197,-3190,-659,-2606,10830,2039,-458,1250,5458 } }, { "Olympus E-PM1", 0, 0, { 7575,-2159,-571,-3722,11341,2725,-1434,2819,6271 } }, { "Olympus E-PM2", 0, 0, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M10", 0, 0, /* Same for E-M10MarkII, E-M10MarkIII */ { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus E-M1MarkII", 0, 0, { 9383,-3170,-763,-2457,10702,2020,-384,1236,5552 } }, { "Olympus E-M1", 0, 0, { 7687,-1984,-606,-4327,11928,2721,-1381,2339,6452 } }, { "Olympus E-M5MarkII", 0, 0, { 9422,-3258,-711,-2655,10898,2015,-512,1354,5512 } }, { "Olympus E-M5", 0, 0xfe1, { 8380,-2630,-639,-2887,10725,2496,-627,1427,5438 } }, { "Olympus PEN-F",0, 0, { 9476,-3182,-765,-2613,10958,1893,-449,1315,5268 } }, { "Olympus SP350", 0, 0, { 12078,-4836,-1069,-6671,14306,2578,-786,939,7418 } }, { "Olympus SP3", 0, 0, { 11766,-4445,-1067,-6901,14421,2707,-1029,1217,7572 } }, { "Olympus SP500UZ", 0, 0xfff, { 9493,-3415,-666,-5211,12334,3260,-1548,2262,6482 } }, { "Olympus SP510UZ", 0, 0xffe, { 10593,-3607,-1010,-5881,13127,3084,-1200,1805,6721 } }, { "Olympus SP550UZ", 0, 0xffe, { 11597,-4006,-1049,-5432,12799,2957,-1029,1750,6516 } }, { "Olympus SP560UZ", 0, 0xff9, { 10915,-3677,-982,-5587,12986,2911,-1168,1968,6223 } }, { "Olympus SP565UZ", 0, 0, /* added */ { 11856,-4469,-1159,-4814,12368,2756,-993,1779,5589 } }, { "Olympus SP570UZ", 0, 0, { 11522,-4044,-1146,-4736,12172,2904,-988,1829,6039 } }, { "Olympus SH-2", 0, 0, { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus SH-3", 0, 0, /* Alias of SH-2 */ { 10156,-3425,-1077,-2611,11177,1624,-385,1592,5080 } }, { "Olympus STYLUS1",0, 0, /* updated */ { 8360,-2420,-880,-3928,12353,1739,-1381,2416,5173 } }, { "Olympus TG-4", 0, 0, { 11426,-4159,-1126,-2066,10678,1593,-120,1327,4998 } }, { "Olympus TG-5", 0, 0, { 10899,-3833,-1082,-2112,10736,1575,-267,1452,5269 } }, { "Olympus XZ-10", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "Olympus XZ-1", 0, 0, { 10901,-4095,-1074,-1141,9208,2293,-62,1417,5158 } }, { "Olympus XZ-2", 0, 0, { 9777,-3483,-925,-2886,11297,1800,-602,1663,5134 } }, { "OmniVision", 16, 0x3ff, { 12782,-4059,-379,-478,9066,1413,1340,1513,5176 } }, /* DJC */ { "Pentax *ist DL2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DL", 0, 0, { 10829,-2838,-1115,-8339,15817,2696,-837,680,11939 } }, { "Pentax *ist DS2", 0, 0, { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Pentax *ist DS", 0, 0, { 10371,-2333,-1206,-8688,16231,2602,-1230,1116,11282 } }, { "Pentax *ist D", 0, 0, { 9651,-2059,-1189,-8881,16512,2487,-1460,1345,10687 } }, { "Pentax GR", 0, 0, /* added */ { 5329,-1459,-390,-5407,12930,2768,-1119,1772,6046 } }, { "Pentax K-01", 0, 0, /* added */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K10D", 0, 0, /* updated */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Pentax K1", 0, 0, { 11095,-3157,-1324,-8377,15834,2720,-1108,947,11688 } }, { "Pentax K20D", 0, 0, { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Pentax K200D", 0, 0, { 9186,-2678,-907,-8693,16517,2260,-1129,1094,8524 } }, { "Pentax K2000", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax K-m", 0, 0, /* updated */ { 9730,-2989,-970,-8527,16258,2381,-1060,970,8362 } }, { "Pentax KP", 0, 0, { 7825,-2160,-1403,-4841,13555,1349,-1559,2449,5814 } }, { "Pentax K-x", 0, 0, { 8843,-2837,-625,-5025,12644,2668,-411,1234,7410 } }, { "Pentax K-r", 0, 0, { 9895,-3077,-850,-5304,13035,2521,-883,1768,6936 } }, { "Pentax K-1", 0, 0, /* updated */ { 8596,-2981,-639,-4202,12046,2431,-685,1424,6122 } }, { "Pentax K-30", 0, 0, /* updated */ { 8134,-2728,-645,-4365,11987,2694,-838,1509,6498 } }, { "Pentax K-3 II", 0, 0, /* updated */ { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-3", 0, 0, { 7415,-2052,-721,-5186,12788,2682,-1446,2157,6773 } }, { "Pentax K-5 II", 0, 0, { 8170,-2725,-639,-4440,12017,2744,-771,1465,6599 } }, { "Pentax K-500", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-50", 0, 0, /* added */ { 8109,-2740,-608,-4593,12175,2731,-1006,1515,6545 } }, { "Pentax K-5", 0, 0, { 8713,-2833,-743,-4342,11900,2772,-722,1543,6247 } }, { "Pentax K-70", 0, 0, { 8766,-3149,-747,-3976,11943,2292,-517,1259,5552 } }, { "Pentax K-7", 0, 0, { 9142,-2947,-678,-8648,16967,1663,-2224,2898,8615 } }, { "Pentax KP", 0, 0, /* temp */ { 8626,-2607,-1155,-3995,12301,1881,-1039,1822,6925 } }, { "Pentax K-S1", 0, 0, { 8512,-3211,-787,-4167,11966,2487,-638,1288,6054 } }, { "Pentax K-S2", 0, 0, { 8662,-3280,-798,-3928,11771,2444,-586,1232,6054 } }, { "Pentax Q-S1", 0, 0, { 12995,-5593,-1107,-1879,10139,2027,-64,1233,4919 } }, { "Pentax Q7", 0, 0, /* added */ { 10901,-3938,-1025,-2743,11210,1738,-823,1805,5344 } }, { "Pentax Q10", 0, 0, /* updated */ { 11562,-4183,-1172,-2357,10919,1641,-582,1726,5112 } }, { "Pentax Q", 0, 0, /* added */ { 11731,-4169,-1267,-2015,10727,1473,-217,1492,4870 } }, { "Pentax MX-1", 0, 0, /* updated */ { 9296,-3146,-888,-2860,11287,1783,-618,1698,5151 } }, { "Pentax 645D", 0, 0x3e00, { 10646,-3593,-1158,-3329,11699,1831,-667,2874,6287 } }, { "Pentax 645Z", 0, 0, /* updated */ { 9519,-3591,-664,-4074,11725,2671,-624,1501,6653 } }, { "Panasonic DMC-CM10", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DMC-CM1", -15, 0, { 8770,-3194,-820,-2871,11281,1803,-513,1552,4434 } }, { "Panasonic DC-FZ82", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-FZ80", -15, 0, /* markets: FZ80 FZ82 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DMC-FZ8", 0, 0xf7f, { 8986,-2755,-802,-6341,13575,3077,-1476,2144,6379 } }, { "Panasonic DMC-FZ18", 0, 0, { 9932,-3060,-935,-5809,13331,2753,-1267,2155,5575 } }, { "Panasonic DMC-FZ28", -15, 0xf96, { 10109,-3488,-993,-5412,12812,2916,-1305,2140,5543 } }, { "Panasonic DMC-FZ300", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ330", -15, 0xfff, { 8378,-2798,-769,-3068,11410,1877,-538,1792,4623 } }, { "Panasonic DMC-FZ30", 0, 0xf94, { 10976,-4029,-1141,-7918,15491,2600,-1670,2071,8246 } }, { "Panasonic DMC-FZ3", -15, 0, { 9938,-2780,-890,-4604,12393,2480,-1117,2304,4620 } }, { "Panasonic DMC-FZ4", -15, 0, /* 40,42,45 */ { 13639,-5535,-1371,-1698,9633,2430,316,1152,4108 } }, { "Panasonic DMC-FZ50", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-FZ7", -15, 0, { 11532,-4324,-1066,-2375,10847,1749,-564,1699,4351 } }, { "Leica V-LUX1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Leica V-LUX 1", 0, 0, { 7906,-2709,-594,-6231,13351,3220,-1922,2631,6537 } }, { "Panasonic DMC-L10", -15, 0xf96, { 8025,-1942,-1050,-7920,15904,2100,-2456,3005,7039 } }, { "Panasonic DMC-L1", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX3", 0, 0xf7f, /* added */ { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Leica DIGILUX 3", 0, 0xf7f, { 8054,-1885,-1025,-8349,16367,2040,-2805,3542,7629 } }, { "Panasonic DMC-LC1", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX2", 0, 0, /* added */ { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Leica DIGILUX 2", 0, 0, { 11340,-4069,-1275,-7555,15266,2448,-2960,3426,7685 } }, { "Panasonic DMC-LX100", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX (Typ 109)", -15, 0, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Panasonic DMC-LF1", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Leica C (Typ 112)", -15, 0, { 9379,-3267,-816,-3227,11560,1881,-926,1928,5340 } }, { "Panasonic DMC-LX9", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX10", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX15", -15, 0, /* markets: LX9 LX10 LX15 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-LX1", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-Lux (Typ 109)", 0, 0xf7f, { 8844,-3538,-768,-3709,11762,2200,-698,1792,5220 } }, { "Leica D-LUX2", 0, 0xf7f, { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Leica D-LUX 2", 0, 0xf7f, /* added */ { 10704,-4187,-1230,-8314,15952,2501,-920,945,8927 } }, { "Panasonic DMC-LX2", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX3", 0, 0, { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Leica D-LUX 3", 0, 0, /* added */ { 8048,-2810,-623,-6450,13519,3272,-1700,2146,7049 } }, { "Panasonic DMC-LX3", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Leica D-LUX 4", -15, 0, { 8128,-2668,-655,-6134,13307,3161,-1782,2568,6083 } }, { "Panasonic DMC-LX5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Leica D-LUX 5", -15, 0, { 10909,-4295,-948,-1333,9306,2399,22,1738,4582 } }, { "Panasonic DMC-LX7", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Leica D-LUX 6", -15, 0, { 10148,-3743,-991,-2837,11366,1659,-701,1893,4899 } }, { "Panasonic DMC-FZ1000", -15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Leica V-LUX (Typ 114)", 15, 0, { 7830,-2696,-763,-3325,11667,1866,-641,1712,4824 } }, { "Panasonic DMC-FZ100", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Leica V-LUX 2", -15, 0xfff, { 16197,-6146,-1761,-2393,10765,1869,366,2238,5248 } }, { "Panasonic DMC-FZ150", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Leica V-LUX 3", -15, 0xfff, { 11904,-4541,-1189,-2355,10899,1662,-296,1586,4289 } }, { "Panasonic DMC-FZ2000", -15, 0, /* markets: DMC-FZ2000, DMC-FZ2500 ,FZH1 */ { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ2500", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZH1", -15, 0, { 7386,-2443,-743,-3437,11864,1757,-608,1660,4766 } }, { "Panasonic DMC-FZ200", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Leica V-LUX 4", -15, 0xfff, { 8112,-2563,-740,-3730,11784,2197,-941,2075,4933 } }, { "Panasonic DMC-FX150", -15, 0xfff, { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-FX180", -15, 0xfff, /* added */ { 9082,-2907,-925,-6119,13377,3058,-1797,2641,5609 } }, { "Panasonic DMC-G10", 0, 0, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G1", -15, 0xf94, { 8199,-2065,-1056,-8124,16156,2033,-2458,3022,7220 } }, { "Panasonic DMC-G2", -15, 0xf3c, { 10113,-3400,-1114,-4765,12683,2317,-377,1437,6710 } }, { "Panasonic DMC-G3", -15, 0xfff, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DMC-G5", -15, 0xfff, { 7798,-2562,-740,-3879,11584,2613,-1055,2248,5434 } }, { "Panasonic DMC-G6", -15, 0xfff, { 8294,-2891,-651,-3869,11590,2595,-1183,2267,5352 } }, { "Panasonic DMC-G7", -15, 0xfff, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-G8", -15, 0xfff, /* markets: DMC-G8, DMC-G80, DMC-G81, DMC-G85 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-G9", -15, 0, /* temp */ { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Panasonic DMC-GF1", -15, 0xf92, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF2", -15, 0xfff, { 7888,-1902,-1011,-8106,16085,2099,-2353,2866,7330 } }, { "Panasonic DMC-GF3", -15, 0xfff, { 9051,-2468,-1204,-5212,13276,2121,-1197,2510,6890 } }, { "Panasonic DMC-GF5", -15, 0xfff, { 8228,-2945,-660,-3938,11792,2430,-1094,2278,5793 } }, { "Panasonic DMC-GF6", -15, 0, { 8130,-2801,-946,-3520,11289,2552,-1314,2511,5791 } }, { "Panasonic DMC-GF7", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GF8", -15, 0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GH1", -15, 0xf92, { 6299,-1466,-532,-6535,13852,2969,-2331,3112,5984 } }, { "Panasonic DMC-GH2", -15, 0xf95, { 7780,-2410,-806,-3913,11724,2484,-1018,2390,5298 } }, { "Panasonic DMC-GH3", -15, 0, { 6559,-1752,-491,-3672,11407,2586,-962,1875,5130 } }, { "Panasonic DMC-GH4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic AG-GH4", -15, 0, /* added */ { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DC-GH5", -15, 0, { 7641,-2336,-605,-3218,11299,2187,-485,1338,5121 } }, { "Yuneec CGO4", -15, 0, { 7122,-2108,-512,-3155,11201,2231,-541,1423,5045 } }, { "Panasonic DMC-GM1", -15, 0, { 6770,-1895,-744,-5232,13145,2303,-1664,2691,5703 } }, { "Panasonic DMC-GM5", -15, 0, { 8238,-3244,-679,-3921,11814,2384,-836,2022,5852 } }, { "Panasonic DMC-GX1", -15, 0, { 6763,-1919,-863,-3868,11515,2684,-1216,2387,5879 } }, { "Panasonic DC-GX850", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GX800", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DC-GF9", -15, 0, /* markets: GX850 GX800 GF9 */ { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX85", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX80", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7MK2", -15, 0, /* markets: GX85 GX80 GX7MK2 */ { 7771,-3020,-629,-4029,11950,2345,-821,1977,6119 } }, { "Panasonic DMC-GX7", -15,0, { 7610,-2780,-576,-4614,12195,2733,-1375,2393,6490 } }, { "Panasonic DMC-GX8", -15,0, { 7564,-2263,-606,-3148,11239,2177,-540,1435,4853 } }, { "Panasonic DMC-TZ6", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ8", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ82 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-TZ90", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ91", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-TZ92", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DC-T93", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS4", -15, 0, /* markets: ZS40 TZ60 TZ61 */ { 8607,-2822,-808,-3755,11930,2049,-820,2060,5224 } }, { "Panasonic DMC-TZ7", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS5", -15, 0, /* markets: ZS50 TZ70 TZ71 */ { 8802,-3135,-789,-3151,11468,1904,-550,1745,4810 } }, { "Panasonic DMC-ZS6", -15, 0, /* markets: ZS60 TZ80 TZ81 TZ85 */ { 8550,-2908,-842,-3195,11529,1881,-338,1603,4631 } }, { "Panasonic DC-ZS70", -15, 0, /* markets: ZS70 TZ90 TZ91 TZ92 T93 */ { 9052,-3117,-883,-3045,11346,1927,-205,1520,4730 } }, { "Panasonic DMC-ZS100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-ZS110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ100", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ101", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TZ110", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Panasonic DMC-TX1", -15, 0, /* markets: ZS100 ZS110 TZ100 TZ101 TZ110 TX1 */ { 7790,-2736,-755,-3452,11870,1769,-628,1647,4898 } }, { "Phase One H 20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H20", 0, 0, /* DJC */ { 1313,1855,-109,-6715,15908,808,-327,1840,6020 } }, { "Phase One H 25", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One H25", 0, 0, /* added */ { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ280", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ260", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ250",0, 0, // {3984,0,0,0,10000,0,0,0,7666}}, {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* emb */ { "Phase One IQ180", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ160", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ150", 0, 0, /* added */ {10325,845,-604,-4113,13385,481,-1791,4163,6924}}, /* temp */ /* emb */ // { 3984,0,0,0,10000,0,0,0,7666 } }, { "Phase One IQ140", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 65", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P 45", 0, 0, /* added */ { 5053,-24,-117,-5685,14077,1703,-2619,4491,5850 } }, { "Phase One P40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P 40", 0, 0, { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One P30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P 30", 0, 0, /* added */ { 4516,-244,-36,-7020,14976,2174,-3206,4670,7087 } }, { "Phase One P25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 25", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P 21", 0, 0, /* added */ { 6516,-2050,-507,-8217,16703,1479,-3492,4741,8489 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P20", 0, 0, /* added */ { 2905,732,-237,-8135,16626,1476,-3038,4253,7517 } }, { "Phase One P 2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One P2", 0, 0, { 2905,732,-237,-8134,16626,1476,-3038,4253,7517 } }, { "Phase One IQ3 100MP", 0, 0, /* added */ // {2423,0,0,0,9901,0,0,0,7989}}, { 10999,354,-742,-4590,13342,937,-1060,2166,8120} }, /* emb */ { "Phase One IQ3 80MP", 0, 0, /* added */ { 6294,686,-712,-5435,13417,2211,-1006,2435,5042 } }, { "Phase One IQ3 60MP", 0, 0, /* added */ { 8035,435,-962,-6001,13872,2320,-1159,3065,5434 } }, { "Phase One IQ3 50MP", 0, 0, /* added */ // { 3984,0,0,0,10000,0,0,0,7666 } }, {10058,1079,-587,-4135,12903,944,-916,2726,7480}}, /* emb */ { "Photron BC2-HD", 0, 0, /* DJC */ { 14603,-4122,-528,-1810,9794,2017,-297,2763,5936 } }, { "Polaroid x530", 0, 0, { 13458,-2556,-510,-5444,15081,205,0,0,12120 } }, { "Red One", 704, 0xffff, /* DJC */ { 21014,-7891,-2613,-3056,12201,856,-2203,5125,8042 } }, { "Ricoh S10 24-72mm F2.5-4.4 VC", 0, 0, /* added */ { 10531,-4043,-878,-2038,10270,2052,-107,895,4577 } }, { "Ricoh GR A12 50mm F2.5 MACRO", 0, 0, /* added */ { 8849,-2560,-689,-5092,12831,2520,-507,1280,7104 } }, { "Ricoh GR DIGITAL 3", 0, 0, /* added */ { 8170,-2496,-655,-5147,13056,2312,-1367,1859,5265 } }, { "Ricoh GR DIGITAL 4", 0, 0, /* added */ { 8771,-3151,-837,-3097,11015,2389,-703,1343,4924 } }, { "Ricoh GR II", 0, 0, { 4630,-834,-423,-4977,12805,2417,-638,1467,6115 } }, { "Ricoh GR", 0, 0, { 3708,-543,-160,-5381,12254,3556,-1471,1929,8234 } }, { "Ricoh GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh RICOH GX200", 0, 0, /* added */ { 8040,-2368,-626,-4659,12543,2363,-1125,1581,5660 } }, { "Ricoh GXR MOUNT A12", 0, 0, /* added */ { 7834,-2182,-739,-5453,13409,2241,-952,2005,6620 } }, { "Ricoh GXR A16", 0, 0, /* added */ { 7837,-2538,-730,-4370,12184,2461,-868,1648,5830 } }, { "Ricoh GXR A12", 0, 0, /* added */ { 10228,-3159,-933,-5304,13158,2371,-943,1873,6685 } }, { "Samsung EK-GN100", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN110", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-GN120", 0, 0, /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EK-KN120", 0, 0, /* added */ /* Galaxy NX */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung EX1", 0, 0x3e00, { 8898,-2498,-994,-3144,11328,2066,-760,1381,4576 } }, { "Samsung EX2F", 0, 0x7ff, { 10648,-3897,-1055,-2022,10573,1668,-492,1611,4742 } }, { "Samsung Galaxy S7 Edge", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy S7", 0, 0, /* added */ { 9927,-3704,-1024,-3935,12758,1257,-389,1512,4993 } }, { "Samsung Galaxy NX", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX U", 0, 0, /* added */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX mini", 0, 0, { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung NX3300", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX3000", 0, 0, { 8060,-2933,-761,-4504,12890,1762,-630,1489,5227 } }, { "Samsung NX30", 0, 0, /* used for NX30/NX300/NX300M */ { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2000", 0, 0, { 7557,-2522,-739,-4679,12949,1894,-840,1777,5311 } }, { "Samsung NX2", 0, 0xfff, /* used for NX20/NX200/NX210 */ { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1000", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX1100", 0, 0, { 6933,-2268,-753,-4921,13387,1647,-803,1641,6096 } }, { "Samsung NX11", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX10", 0, 0, /* used for NX10/NX100 */ { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX500", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NX5", 0, 0, { 10332,-3234,-1168,-6111,14639,1520,-1352,2647,8331 } }, { "Samsung NX1", 0, 0, { 10686,-4042,-1052,-3595,13238,276,-464,1259,5931 } }, { "Samsung NXF1", 0, 0, /* added */ { 5222,-1196,-550,-6540,14649,2009,-1666,2819,5657 } }, { "Samsung WB2000", 0, 0xfff, { 12093,-3557,-1155,-1000,9534,1733,-22,1787,4576 } }, { "Samsung GX10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-10", 0, 0, /* added */ /* Pentax K10D */ { 9679,-2965,-811,-8622,16514,2182,-975,883,9793 } }, { "Samsung GX-1", 0, 0, /* used for GX-1L/GX-1S */ { 10504,-2438,-1189,-8603,16207,2531,-1022,863,12242 } }, { "Samsung GX20", 0, 0, /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung GX-20", 0, 0, /* added */ /* copied from Pentax K20D */ { 9427,-2714,-868,-7493,16092,1373,-2199,3264,7180 } }, { "Samsung S85", 0, 0, /* DJC */ { 11885,-3968,-1473,-4214,12299,1916,-835,1655,5549 } }, // Foveon: LibRaw color data { "Sigma dp0 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp1 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp2 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma dp3 Quattro", 2047, 0, { 13801,-3390,-1016,5535,3802,877,1848,4245,3730 } }, { "Sigma sd Quattro H", 256, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma sd Quattro", 2047, 0, { 1295,108,-311, 256,828,-65,-28,750,254 } }, /* temp */ { "Sigma SD9", 15, 4095, /* updated */ { 13564,-2537,-751,-5465,15154,194,-67,116,10425 } }, { "Sigma SD10", 15, 16383, /* updated */ { 6787,-1682,575,-3091,8357,160,217,-369,12314 } }, { "Sigma SD14", 15, 16383, /* updated */ { 13589,-2509,-739,-5440,15104,193,-61,105,10554 } }, { "Sigma SD15", 15, 4095, /* updated */ { 13556,-2537,-730,-5462,15144,195,-61,106,10577 } }, // Merills + SD1 { "Sigma SD1", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP1 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP2 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, { "Sigma DP3 Merrill", 31, 4095, /* LibRaw */ { 5133,-1895,-353,4978,744,144,3837,3069,2777 } }, // Sigma DP (non-Merill Versions) { "Sigma DP1X", 0, 4095, /* updated */ { 13704,-2452,-857,-5413,15073,186,-89,151,9820 } }, { "Sigma DP1", 0, 4095, /* updated */ { 12774,-2591,-394,-5333,14676,207,15,-21,12127 } }, { "Sigma DP", 0, 4095, /* LibRaw */ // { 7401,-1169,-567,2059,3769,1510,664,3367,5328 } }, { 13100,-3638,-847,6855,2369,580,2723,3218,3251 } }, { "Sinar", 0, 0, /* DJC */ { 16442,-2956,-2422,-2877,12128,750,-1136,6066,4559 } }, { "Sony DSC-F828", 0, 0, { 7924,-1910,-777,-8226,15459,2998,-1517,2199,6818,-7242,11401,3481 } }, { "Sony DSC-R1", 0, 0, { 8512,-2641,-694,-8042,15670,2526,-1821,2117,7414 } }, { "Sony DSC-V3", 0, 0, { 7511,-2571,-692,-7894,15088,3060,-948,1111,8128 } }, {"Sony DSC-RX100M5", -800, 0, { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100M", -800, 0, /* used for M2/M3/M4 */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX100", 0, 0, { 8651,-2754,-1057,-3464,12207,1373,-568,1398,4434 } }, {"Sony DSC-RX10M4", -800, 0, /* prelim */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony DSC-RX10",0, 0, /* same for M2/M3 */ { 6679,-1825,-745,-5047,13256,1953,-1580,2422,5183 } }, { "Sony DSC-RX1RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony DSC-RX1R", 0, 0, /* updated */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony DSC-RX1", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, {"Sony DSC-RX0", -800, 0, /* temp */ { 9396,-3507,-843,-2497,11111,1572,-343,1355,5089 } }, { "Sony DSLR-A100", 0, 0xfeb, { 9437,-2811,-774,-8405,16215,2290,-710,596,7181 } }, { "Sony DSLR-A290", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A2", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A300", 0, 0, { 9847,-3091,-928,-8485,16345,2225,-715,595,7103 } }, { "Sony DSLR-A330", 0, 0, { 9847,-3091,-929,-8485,16346,2225,-714,595,7103 } }, { "Sony DSLR-A350", 0, 0xffc, { 6038,-1484,-578,-9146,16746,2513,-875,746,7217 } }, { "Sony DSLR-A380", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A390", 0, 0, { 6038,-1484,-579,-9145,16746,2512,-875,746,7218 } }, { "Sony DSLR-A450", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A580", 0, 0xfeb, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony DSLR-A500", 0, 0xfeb, { 6046,-1127,-278,-5574,13076,2786,-691,1419,7625 } }, { "Sony DSLR-A5", 0, 0xfeb, { 4950,-580,-103,-5228,12542,3029,-709,1435,7371 } }, { "Sony DSLR-A700", 0, 0, { 5775,-805,-359,-8574,16295,2391,-1943,2341,7249 } }, { "Sony DSLR-A850", 0, 0, { 5413,-1162,-365,-5665,13098,2866,-608,1179,8440 } }, { "Sony DSLR-A900", 0, 0, { 5209,-1072,-397,-8845,16120,2919,-1618,1803,8654 } }, { "Sony ILCA-68", 0, 0, { 6435,-1903,-536,-4722,12449,2550,-663,1363,6517 } }, { "Sony ILCA-77M2", 0, 0, { 5991,-1732,-443,-4100,11989,2381,-704,1467,5992 } }, { "Sony ILCA-99M2", 0, 0, { 6660,-1918,-471,-4613,12398,2485,-649,1433,6447 } }, { "Sony ILCE-9", 0, 0, { 6389,-1703,-378,-4562,12265,2587,-670,1489,6550 } }, { "Sony ILCE-7M2", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-7SM2", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7S", 0, 0, { 5838,-1430,-246,-3497,11477,2297,-748,1885,5778 } }, { "Sony ILCE-7RM3", 0, 0, /* temp */ { 6596,-2079,-562,-4782,13016,1933,-970,1581,5181 } }, { "Sony ILCE-7RM2", 0, 0, { 6629,-1900,-483,-4618,12349,2550,-622,1381,6514 } }, { "Sony ILCE-7R", 0, 0, { 4913,-541,-202,-6130,13513,2906,-1564,2151,7183 } }, { "Sony ILCE-7", 0, 0, { 5271,-712,-347,-6153,13653,2763,-1601,2366,7242 } }, { "Sony ILCE-6300", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE-6500", 0, 0, { 5973,-1695,-419,-3826,11797,2293,-639,1398,5789 } }, { "Sony ILCE", 0, 0, /* 3000, 5000, 5100, 6000, and QX1 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony MODEL-NAME", 0, 0, /* added */ { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-5N", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony NEX-5R", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-5T", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3N", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-3", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-5", 0, 0, { 6549,-1550,-436,-4880,12435,2753,-854,1868,6976 } }, { "Sony NEX-6", 0, 0, { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-7", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony NEX-VG30", 0, 0, /* added */ { 6129,-1545,-418,-4930,12490,2743,-977,1693,6615 } }, { "Sony NEX-VG900", 0, 0, /* added */ { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, { "Sony NEX", 0, 0, /* NEX-C3, NEX-F3, NEX-VG20 */ { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A33", 0, 0, { 6069,-1221,-366,-5221,12779,2734,-1024,2066,6834 } }, { "Sony SLT-A35", 0, 0, { 5986,-1618,-415,-4557,11820,3120,-681,1404,6971 } }, { "Sony SLT-A37", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A55", 0, 0, { 5932,-1492,-411,-4813,12285,2856,-741,1524,6739 } }, { "Sony SLT-A57", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A58", 0, 0, { 5991,-1456,-455,-4764,12135,2980,-707,1425,6701 } }, { "Sony SLT-A65", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A77", 0, 0, { 5491,-1192,-363,-4951,12342,2948,-911,1722,7192 } }, { "Sony SLT-A99", 0, 0, { 6344,-1612,-462,-4863,12477,2681,-865,1786,6899 } }, }; // clang-format on double cam_xyz[4][3]; char name[130]; int i, j; if (colors > 4 || colors < 1) return; int bl4 = (cblack[0] + cblack[1] + cblack[2] + cblack[3]) / 4, bl64 = 0; if (cblack[4] * cblack[5] > 0) { for (unsigned c = 0; c < 4096 && c < cblack[4] * cblack[5]; c++) bl64 += cblack[c + 6]; bl64 /= cblack[4] * cblack[5]; } int rblack = black + bl4 + bl64; sprintf(name, "%s %s", t_make, t_model); for (i = 0; i < sizeof table / sizeof *table; i++) if (!strncasecmp(name, table[i].prefix, strlen(table[i].prefix))) { if (!dng_version) { if (table[i].t_black > 0) { black = (ushort)table[i].t_black; memset(cblack, 0, sizeof(cblack)); } else if (table[i].t_black < 0 && rblack == 0) { black = (ushort)(-table[i].t_black); memset(cblack, 0, sizeof(cblack)); } if (table[i].t_maximum) maximum = (ushort)table[i].t_maximum; } if (table[i].trans[0]) { for (raw_color = j = 0; j < 12; j++) #ifdef LIBRAW_LIBRARY_BUILD if (internal_only) imgdata.color.cam_xyz[0][j] = table[i].trans[j] / 10000.0; else imgdata.color.cam_xyz[0][j] = #endif ((double *)cam_xyz)[j] = table[i].trans[j] / 10000.0; #ifdef LIBRAW_LIBRARY_BUILD if (!internal_only) #endif cam_xyz_coeff(rgb_cam, cam_xyz); } break; } } void CLASS simple_coeff(int index) { static const float table[][12] = {/* index 0 -- all Foveon cameras */ {1.4032, -0.2231, -0.1016, -0.5263, 1.4816, 0.017, -0.0112, 0.0183, 0.9113}, /* index 1 -- Kodak DC20 and DC25 */ {2.25, 0.75, -1.75, -0.25, -0.25, 0.75, 0.75, -0.25, -0.25, -1.75, 0.75, 2.25}, /* index 2 -- Logitech Fotoman Pixtura */ {1.893, -0.418, -0.476, -0.495, 1.773, -0.278, -1.017, -0.655, 2.672}, /* index 3 -- Nikon E880, E900, and E990 */ {-1.936280, 1.800443, -1.448486, 2.584324, 1.405365, -0.524955, -0.289090, 0.408680, -1.204965, 1.082304, 2.941367, -1.818705}}; int i, c; for (raw_color = i = 0; i < 3; i++) FORCC rgb_cam[i][c] = table[index][i * colors + c]; } short CLASS guess_byte_order(int words) { uchar test[4][2]; int t = 2, msb; double diff, sum[2] = {0, 0}; fread(test[0], 2, 2, ifp); for (words -= 2; words--;) { fread(test[t], 2, 1, ifp); for (msb = 0; msb < 2; msb++) { diff = (test[t ^ 2][msb] << 8 | test[t ^ 2][!msb]) - (test[t][msb] << 8 | test[t][!msb]); sum[msb] += diff * diff; } t = (t + 1) & 3; } return sum[0] < sum[1] ? 0x4d4d : 0x4949; } float CLASS find_green(int bps, int bite, int off0, int off1) { UINT64 bitbuf = 0; int vbits, col, i, c; ushort img[2][2064]; double sum[] = {0, 0}; FORC(2) { fseek(ifp, c ? off1 : off0, SEEK_SET); for (vbits = col = 0; col < width; col++) { for (vbits -= bps; vbits < 0; vbits += bite) { bitbuf <<= bite; for (i = 0; i < bite; i += 8) bitbuf |= (unsigned)(fgetc(ifp) << i); } img[c][col] = bitbuf << (64 - bps - vbits) >> (64 - bps); } } FORC(width - 1) { sum[c & 1] += ABS(img[0][c] - img[1][c + 1]); sum[~c & 1] += ABS(img[1][c] - img[0][c + 1]); } return 100 * log(sum[0] / sum[1]); } #ifdef LIBRAW_LIBRARY_BUILD static void remove_trailing_spaces(char *string, size_t len) { if (len < 1) return; // not needed, b/c sizeof of make/model is 64 string[len - 1] = 0; if (len < 3) return; // also not needed len = strnlen(string, len - 1); for (int i = len - 1; i >= 0; i--) { if (isspace(string[i])) string[i] = 0; else break; } } void CLASS initdata() { tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); for (int i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } for (int i = 0; i < 0x10000; i++) curve[i] = i; memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; } #endif /* Identify which camera created this file, and set global variables accordingly. */ void CLASS identify() { static const short pana[][6] = { {3130, 1743, 4, 0, -6, 0}, {3130, 2055, 4, 0, -6, 0}, {3130, 2319, 4, 0, -6, 0}, {3170, 2103, 18, 0, -42, 20}, {3170, 2367, 18, 13, -42, -21}, {3177, 2367, 0, 0, -1, 0}, {3304, 2458, 0, 0, -1, 0}, {3330, 2463, 9, 0, -5, 0}, {3330, 2479, 9, 0, -17, 4}, {3370, 1899, 15, 0, -44, 20}, {3370, 2235, 15, 0, -44, 20}, {3370, 2511, 15, 10, -44, -21}, {3690, 2751, 3, 0, -8, -3}, {3710, 2751, 0, 0, -3, 0}, {3724, 2450, 0, 0, 0, -2}, {3770, 2487, 17, 0, -44, 19}, {3770, 2799, 17, 15, -44, -19}, {3880, 2170, 6, 0, -6, 0}, {4060, 3018, 0, 0, 0, -2}, {4290, 2391, 3, 0, -8, -1}, {4330, 2439, 17, 15, -44, -19}, {4508, 2962, 0, 0, -3, -4}, {4508, 3330, 0, 0, -3, -6}, }; static const ushort canon[][11] = { {1944, 1416, 0, 0, 48, 0}, {2144, 1560, 4, 8, 52, 2, 0, 0, 0, 25}, {2224, 1456, 48, 6, 0, 2}, {2376, 1728, 12, 6, 52, 2}, {2672, 1968, 12, 6, 44, 2}, {3152, 2068, 64, 12, 0, 0, 16}, {3160, 2344, 44, 12, 4, 4}, {3344, 2484, 4, 6, 52, 6}, {3516, 2328, 42, 14, 0, 0}, {3596, 2360, 74, 12, 0, 0}, {3744, 2784, 52, 12, 8, 12}, {3944, 2622, 30, 18, 6, 2}, {3948, 2622, 42, 18, 0, 2}, {3984, 2622, 76, 20, 0, 2, 14}, {4104, 3048, 48, 12, 24, 12}, {4116, 2178, 4, 2, 0, 0}, {4152, 2772, 192, 12, 0, 0}, {4160, 3124, 104, 11, 8, 65}, {4176, 3062, 96, 17, 8, 0, 0, 16, 0, 7, 0x49}, {4192, 3062, 96, 17, 24, 0, 0, 16, 0, 0, 0x49}, {4312, 2876, 22, 18, 0, 2}, {4352, 2874, 62, 18, 0, 0}, {4476, 2954, 90, 34, 0, 0}, {4480, 3348, 12, 10, 36, 12, 0, 0, 0, 18, 0x49}, {4480, 3366, 80, 50, 0, 0}, {4496, 3366, 80, 50, 12, 0}, {4768, 3516, 96, 16, 0, 0, 0, 16}, {4832, 3204, 62, 26, 0, 0}, {4832, 3228, 62, 51, 0, 0}, {5108, 3349, 98, 13, 0, 0}, {5120, 3318, 142, 45, 62, 0}, {5280, 3528, 72, 52, 0, 0}, /* EOS M */ {5344, 3516, 142, 51, 0, 0}, {5344, 3584, 126, 100, 0, 2}, {5360, 3516, 158, 51, 0, 0}, {5568, 3708, 72, 38, 0, 0}, {5632, 3710, 96, 17, 0, 0, 0, 16, 0, 0, 0x49}, {5712, 3774, 62, 20, 10, 2}, {5792, 3804, 158, 51, 0, 0}, {5920, 3950, 122, 80, 2, 0}, {6096, 4056, 72, 34, 0, 0}, /* EOS M3 */ {6288, 4056, 266, 36, 0, 0}, /* EOS 80D */ {6384, 4224, 120, 44, 0, 0}, /* 6D II */ {6880, 4544, 136, 42, 0, 0}, /* EOS 5D4 */ {8896, 5920, 160, 64, 0, 0}, }; static const struct { ushort id; char t_model[20]; } unique[] = { {0x001, "EOS-1D"}, {0x167, "EOS-1DS"}, {0x168, "EOS 10D"}, {0x169, "EOS-1D Mark III"}, {0x170, "EOS 300D"}, {0x174, "EOS-1D Mark II"}, {0x175, "EOS 20D"}, {0x176, "EOS 450D"}, {0x188, "EOS-1Ds Mark II"}, {0x189, "EOS 350D"}, {0x190, "EOS 40D"}, {0x213, "EOS 5D"}, {0x215, "EOS-1Ds Mark III"}, {0x218, "EOS 5D Mark II"}, {0x232, "EOS-1D Mark II N"}, {0x234, "EOS 30D"}, {0x236, "EOS 400D"}, {0x250, "EOS 7D"}, {0x252, "EOS 500D"}, {0x254, "EOS 1000D"}, {0x261, "EOS 50D"}, {0x269, "EOS-1D X"}, {0x270, "EOS 550D"}, {0x281, "EOS-1D Mark IV"}, {0x285, "EOS 5D Mark III"}, {0x286, "EOS 600D"}, {0x287, "EOS 60D"}, {0x288, "EOS 1100D"}, {0x289, "EOS 7D Mark II"}, {0x301, "EOS 650D"}, {0x302, "EOS 6D"}, {0x324, "EOS-1D C"}, {0x325, "EOS 70D"}, {0x326, "EOS 700D"}, {0x327, "EOS 1200D"}, {0x328, "EOS-1D X Mark II"}, {0x331, "EOS M"}, {0x335, "EOS M2"}, {0x374, "EOS M3"}, /* temp */ {0x384, "EOS M10"}, /* temp */ {0x394, "EOS M5"}, /* temp */ {0x398, "EOS M100"}, /* temp */ {0x346, "EOS 100D"}, {0x347, "EOS 760D"}, {0x349, "EOS 5D Mark IV"}, {0x350, "EOS 80D"}, {0x382, "EOS 5DS"}, {0x393, "EOS 750D"}, {0x401, "EOS 5DS R"}, {0x404, "EOS 1300D"}, {0x405, "EOS 800D"}, {0x406, "EOS 6D Mark II"}, {0x407, "EOS M6"}, {0x408, "EOS 77D"}, {0x417, "EOS 200D"}, }, sonique[] = { {0x002, "DSC-R1"}, {0x100, "DSLR-A100"}, {0x101, "DSLR-A900"}, {0x102, "DSLR-A700"}, {0x103, "DSLR-A200"}, {0x104, "DSLR-A350"}, {0x105, "DSLR-A300"}, {0x106, "DSLR-A900"}, {0x107, "DSLR-A380"}, {0x108, "DSLR-A330"}, {0x109, "DSLR-A230"}, {0x10a, "DSLR-A290"}, {0x10d, "DSLR-A850"}, {0x10e, "DSLR-A850"}, {0x111, "DSLR-A550"}, {0x112, "DSLR-A500"}, {0x113, "DSLR-A450"}, {0x116, "NEX-5"}, {0x117, "NEX-3"}, {0x118, "SLT-A33"}, {0x119, "SLT-A55V"}, {0x11a, "DSLR-A560"}, {0x11b, "DSLR-A580"}, {0x11c, "NEX-C3"}, {0x11d, "SLT-A35"}, {0x11e, "SLT-A65V"}, {0x11f, "SLT-A77V"}, {0x120, "NEX-5N"}, {0x121, "NEX-7"}, {0x122, "NEX-VG20E"}, {0x123, "SLT-A37"}, {0x124, "SLT-A57"}, {0x125, "NEX-F3"}, {0x126, "SLT-A99V"}, {0x127, "NEX-6"}, {0x128, "NEX-5R"}, {0x129, "DSC-RX100"}, {0x12a, "DSC-RX1"}, {0x12b, "NEX-VG900"}, {0x12c, "NEX-VG30E"}, {0x12e, "ILCE-3000"}, {0x12f, "SLT-A58"}, {0x131, "NEX-3N"}, {0x132, "ILCE-7"}, {0x133, "NEX-5T"}, {0x134, "DSC-RX100M2"}, {0x135, "DSC-RX10"}, {0x136, "DSC-RX1R"}, {0x137, "ILCE-7R"}, {0x138, "ILCE-6000"}, {0x139, "ILCE-5000"}, {0x13d, "DSC-RX100M3"}, {0x13e, "ILCE-7S"}, {0x13f, "ILCA-77M2"}, {0x153, "ILCE-5100"}, {0x154, "ILCE-7M2"}, {0x155, "DSC-RX100M4"}, {0x156, "DSC-RX10M2"}, {0x158, "DSC-RX1RM2"}, {0x15a, "ILCE-QX1"}, {0x15b, "ILCE-7RM2"}, {0x15e, "ILCE-7SM2"}, {0x161, "ILCA-68"}, {0x162, "ILCA-99M2"}, {0x163, "DSC-RX10M3"}, {0x164, "DSC-RX100M5"}, {0x165, "ILCE-6300"}, {0x166, "ILCE-9"}, {0x168, "ILCE-6500"}, {0x16a, "ILCE-7RM3"}, {0x16c, "DSC-RX0"}, {0x16d, "DSC-RX10M4"}, }; #ifdef LIBRAW_LIBRARY_BUILD static const libraw_custom_camera_t const_table[] #else static const struct { unsigned fsize; ushort rw, rh; uchar lm, tm, rm, bm, lf, cf, max, flags; char t_make[10], t_model[20]; ushort offset; } table[] #endif = { {786432, 1024, 768, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-080C"}, {1447680, 1392, 1040, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-145C"}, {1920000, 1600, 1200, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-201C"}, {5067304, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C"}, {5067316, 2588, 1958, 0, 0, 0, 0, 0, 0x94, 0, 0, "AVT", "F-510C", 12}, {10134608, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C"}, {10134620, 2588, 1958, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-510C", 12}, {16157136, 3272, 2469, 0, 0, 0, 0, 9, 0x94, 0, 0, "AVT", "F-810C"}, {15980544, 3264, 2448, 0, 0, 0, 0, 8, 0x61, 0, 1, "AgfaPhoto", "DC-833m"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Alcatel", "5035D"}, {31850496, 4608, 3456, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 4:3"}, {23887872, 4608, 2592, 0, 0, 0, 0, 0, 0x94, 0, 0, "GITUP", "GIT2 16:9"}, {32257024, 4624, 3488, 8, 2, 16, 2, 0, 0x94, 0, 0, "GITUP", "GIT2P 4:3"}, // Android Raw dumps id start // File Size in bytes Horizontal Res Vertical Flag then bayer order eg 0x16 bbgr 0x94 rggb {1540857, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "Samsung", "S3"}, {2658304, 1212, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontMipi"}, {2842624, 1296, 1096, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3FrontQCOM"}, {2969600, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wMipi"}, {3170304, 1976, 1200, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "MI3wQCOM"}, {3763584, 1584, 1184, 0, 0, 0, 0, 96, 0x61, 0, 0, "I_Mobile", "I_StyleQ6"}, {5107712, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel1"}, {5382640, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "UltraPixel2"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5664912, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {5364240, 2688, 1520, 0, 0, 0, 0, 1, 0x61, 0, 0, "OmniVisi", "4688"}, {6299648, 2592, 1944, 0, 0, 0, 0, 1, 0x16, 0, 0, "OmniVisi", "OV5648"}, {6721536, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "OmniVisi", "OV56482"}, {6746112, 2592, 1944, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "OneSV"}, {9631728, 2532, 1902, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "5mp"}, {9830400, 2560, 1920, 0, 0, 0, 0, 96, 0x61, 0, 0, "NGM", "ForwardArt"}, {10186752, 3264, 2448, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX219-mipi 8mp"}, {10223360, 2608, 1944, 0, 0, 0, 0, 96, 0x16, 0, 0, "Sony", "IMX"}, {10782464, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "HTC", "MyTouch4GSlide"}, {10788864, 3282, 2448, 0, 0, 0, 0, 0, 0x16, 0, 0, "Xperia", "L"}, {15967488, 3264, 2446, 0, 0, 0, 0, 96, 0x16, 0, 0, "OmniVison", "OV8850"}, {16224256, 4208, 3082, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3MipiL"}, {16424960, 4208, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "IMX135", "MipiL"}, {17326080, 4164, 3120, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G3LQCom"}, {17522688, 4212, 3120, 0, 0, 0, 0, 0, 0x16, 0, 0, "Sony", "IMX135-QCOM"}, {19906560, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7mipi"}, {19976192, 5312, 2988, 0, 0, 0, 0, 1, 0x16, 0, 0, "LG", "G4"}, {20389888, 4632, 3480, 0, 0, 0, 0, 1, 0x16, 0, 0, "Xiaomi", "RedmiNote3Pro"}, {20500480, 4656, 3496, 0, 0, 0, 0, 1, 0x94, 0, 0, "Sony", "IMX298-mipi 16mp"}, {21233664, 4608, 3456, 0, 0, 0, 0, 1, 0x16, 0, 0, "Gione", "E7qcom"}, {26023936, 4192, 3104, 0, 0, 0, 0, 96, 0x94, 0, 0, "THL", "5000"}, {26257920, 4208, 3120, 0, 0, 0, 0, 96, 0x94, 0, 0, "Sony", "IMX214"}, {26357760, 4224, 3120, 0, 0, 0, 0, 96, 0x61, 0, 0, "OV", "13860"}, {41312256, 5248, 3936, 0, 0, 0, 0, 96, 0x61, 0, 0, "Meizu", "MX4"}, {42923008, 5344, 4016, 0, 0, 0, 0, 96, 0x61, 0, 0, "Sony", "IMX230"}, // Android Raw dumps id end {20137344, 3664, 2748, 0, 0, 0, 0, 0x40, 0x49, 0, 0, "Aptina", "MT9J003", 0xffff}, {2868726, 1384, 1036, 0, 0, 0, 0, 64, 0x49, 0, 8, "Baumer", "TXG14", 1078}, {5298000, 2400, 1766, 12, 12, 44, 2, 40, 0x94, 0, 2, "Canon", "PowerShot SD300"}, {6553440, 2664, 1968, 4, 4, 44, 4, 40, 0x94, 0, 2, "Canon", "PowerShot A460"}, {6573120, 2672, 1968, 12, 8, 44, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A610"}, {6653280, 2672, 1992, 10, 6, 42, 2, 40, 0x94, 0, 2, "Canon", "PowerShot A530"}, {7710960, 2888, 2136, 44, 8, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot S3 IS"}, {9219600, 3152, 2340, 36, 12, 4, 0, 40, 0x94, 0, 2, "Canon", "PowerShot A620"}, {9243240, 3152, 2346, 12, 7, 44, 13, 40, 0x49, 0, 2, "Canon", "PowerShot A470"}, {10341600, 3336, 2480, 6, 5, 32, 3, 40, 0x94, 0, 2, "Canon", "PowerShot A720 IS"}, {10383120, 3344, 2484, 12, 6, 44, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A630"}, {12945240, 3736, 2772, 12, 6, 52, 6, 40, 0x94, 0, 2, "Canon", "PowerShot A640"}, {15636240, 4104, 3048, 48, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot A650"}, {15467760, 3720, 2772, 6, 12, 30, 0, 40, 0x94, 0, 2, "Canon", "PowerShot SX110 IS"}, {15534576, 3728, 2778, 12, 9, 44, 9, 40, 0x94, 0, 2, "Canon", "PowerShot SX120 IS"}, {18653760, 4080, 3048, 24, 12, 24, 12, 40, 0x94, 0, 2, "Canon", "PowerShot SX20 IS"}, {18763488, 4104, 3048, 10, 22, 82, 22, 8, 0x49, 0, 0, "Canon", "PowerShot D10"}, {19131120, 4168, 3060, 92, 16, 4, 1, 40, 0x94, 0, 2, "Canon", "PowerShot SX220 HS"}, {21936096, 4464, 3276, 25, 10, 73, 12, 40, 0x16, 0, 2, "Canon", "PowerShot SX30 IS"}, {24724224, 4704, 3504, 8, 16, 56, 8, 40, 0x49, 0, 2, "Canon", "PowerShot A3300 IS"}, {30858240, 5248, 3920, 8, 16, 56, 16, 40, 0x94, 0, 2, "Canon", "IXUS 160"}, {1976352, 1632, 1211, 0, 2, 0, 1, 0, 0x94, 0, 1, "Casio", "QV-2000UX"}, {3217760, 2080, 1547, 0, 0, 10, 1, 0, 0x94, 0, 1, "Casio", "QV-3*00EX"}, {6218368, 2585, 1924, 0, 0, 9, 0, 0, 0x94, 0, 1, "Casio", "QV-5700"}, {7816704, 2867, 2181, 0, 0, 34, 36, 0, 0x16, 0, 1, "Casio", "EX-Z60"}, {2937856, 1621, 1208, 0, 0, 1, 0, 0, 0x94, 7, 13, "Casio", "EX-S20"}, {4948608, 2090, 1578, 0, 0, 32, 34, 0, 0x94, 7, 1, "Casio", "EX-S100"}, {6054400, 2346, 1720, 2, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "QV-R41"}, {7426656, 2568, 1928, 0, 0, 0, 0, 0, 0x94, 0, 1, "Casio", "EX-P505"}, {7530816, 2602, 1929, 0, 0, 22, 0, 0, 0x94, 7, 1, "Casio", "QV-R51"}, {7542528, 2602, 1932, 0, 0, 32, 0, 0, 0x94, 7, 1, "Casio", "EX-Z50"}, {7562048, 2602, 1937, 0, 0, 25, 0, 0, 0x16, 7, 1, "Casio", "EX-Z500"}, {7753344, 2602, 1986, 0, 0, 32, 26, 0, 0x94, 7, 1, "Casio", "EX-Z55"}, {9313536, 2858, 2172, 0, 0, 14, 30, 0, 0x94, 7, 1, "Casio", "EX-P600"}, {10834368, 3114, 2319, 0, 0, 27, 0, 0, 0x94, 0, 1, "Casio", "EX-Z750"}, {10843712, 3114, 2321, 0, 0, 25, 0, 0, 0x94, 0, 1, "Casio", "EX-Z75"}, {10979200, 3114, 2350, 0, 0, 32, 32, 0, 0x94, 7, 1, "Casio", "EX-P700"}, {12310144, 3285, 2498, 0, 0, 6, 30, 0, 0x94, 0, 1, "Casio", "EX-Z850"}, {12489984, 3328, 2502, 0, 0, 47, 35, 0, 0x94, 0, 1, "Casio", "EX-Z8"}, {15499264, 3754, 2752, 0, 0, 82, 0, 0, 0x94, 0, 1, "Casio", "EX-Z1050"}, {18702336, 4096, 3044, 0, 0, 24, 0, 80, 0x94, 7, 1, "Casio", "EX-ZR100"}, {7684000, 2260, 1700, 0, 0, 0, 0, 13, 0x94, 0, 1, "Casio", "QV-4000"}, {787456, 1024, 769, 0, 1, 0, 0, 0, 0x49, 0, 0, "Creative", "PC-CAM 600"}, {28829184, 4384, 3288, 0, 0, 0, 0, 36, 0x61, 0, 0, "DJI"}, {15151104, 4608, 3288, 0, 0, 0, 0, 0, 0x94, 0, 0, "Matrix"}, {3840000, 1600, 1200, 0, 0, 0, 0, 65, 0x49, 0, 0, "Foculus", "531C"}, {307200, 640, 480, 0, 0, 0, 0, 0, 0x94, 0, 0, "Generic"}, {62464, 256, 244, 1, 1, 6, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {124928, 512, 244, 1, 1, 10, 1, 0, 0x8d, 0, 0, "Kodak", "DC20"}, {1652736, 1536, 1076, 0, 52, 0, 0, 0, 0x61, 0, 0, "Kodak", "DCS200"}, {4159302, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330"}, {4162462, 2338, 1779, 1, 33, 1, 2, 0, 0x94, 0, 0, "Kodak", "C330", 3160}, {2247168, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {3370752, 1232, 912, 0, 0, 16, 0, 0, 0x00, 0, 0, "Kodak", "C330"}, {6163328, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603"}, {6166488, 2864, 2152, 0, 0, 0, 0, 0, 0x94, 0, 0, "Kodak", "C603", 3160}, {460800, 640, 480, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {9116448, 2848, 2134, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "C603"}, {12241200, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP"}, {12272756, 4040, 3030, 2, 0, 0, 13, 0, 0x49, 0, 0, "Kodak", "12MP", 31556}, {18000000, 4000, 3000, 0, 0, 0, 0, 0, 0x00, 0, 0, "Kodak", "12MP"}, {614400, 640, 480, 0, 3, 0, 0, 64, 0x94, 0, 0, "Kodak", "KAI-0340"}, {15360000, 3200, 2400, 0, 0, 0, 0, 96, 0x16, 0, 0, "Lenovo", "A820"}, {3884928, 1608, 1207, 0, 0, 0, 0, 96, 0x16, 0, 0, "Micron", "2010", 3212}, {1138688, 1534, 986, 0, 0, 0, 0, 0, 0x61, 0, 0, "Minolta", "RD175", 513}, {1581060, 1305, 969, 0, 0, 18, 6, 6, 0x1e, 4, 1, "Nikon", "E900"}, {2465792, 1638, 1204, 0, 0, 22, 1, 6, 0x4b, 5, 1, "Nikon", "E950"}, {2940928, 1616, 1213, 0, 0, 0, 7, 30, 0x94, 0, 1, "Nikon", "E2100"}, {4771840, 2064, 1541, 0, 0, 0, 1, 6, 0xe1, 0, 1, "Nikon", "E990"}, {4775936, 2064, 1542, 0, 0, 0, 0, 30, 0x94, 0, 1, "Nikon", "E3700"}, {5865472, 2288, 1709, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E4500"}, {5869568, 2288, 1710, 0, 0, 0, 0, 6, 0x16, 0, 1, "Nikon", "E4300"}, {7438336, 2576, 1925, 0, 0, 0, 1, 6, 0xb4, 0, 1, "Nikon", "E5000"}, {8998912, 2832, 2118, 0, 0, 0, 0, 30, 0x94, 7, 1, "Nikon", "COOLPIX S6"}, {5939200, 2304, 1718, 0, 0, 0, 0, 30, 0x16, 0, 0, "Olympus", "C770UZ"}, {3178560, 2064, 1540, 0, 0, 0, 0, 0, 0x94, 0, 1, "Pentax", "Optio S"}, {4841984, 2090, 1544, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S"}, {6114240, 2346, 1737, 0, 0, 22, 0, 0, 0x94, 7, 1, "Pentax", "Optio S4"}, {10702848, 3072, 2322, 0, 0, 0, 21, 30, 0x94, 0, 1, "Pentax", "Optio 750Z"}, {4147200, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD"}, {4151666, 1920, 1080, 0, 0, 0, 0, 0, 0x49, 0, 0, "Photron", "BC2-HD", 8}, {13248000, 2208, 3000, 0, 0, 0, 0, 13, 0x61, 0, 0, "Pixelink", "A782"}, {6291456, 2048, 1536, 0, 0, 0, 0, 96, 0x61, 0, 0, "RoverShot", "3320AF"}, {311696, 644, 484, 0, 0, 0, 0, 0, 0x16, 0, 8, "ST Micro", "STV680 VGA"}, {16098048, 3288, 2448, 0, 0, 24, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {16215552, 3312, 2448, 0, 0, 48, 0, 9, 0x94, 0, 1, "Samsung", "S85"}, {20487168, 3648, 2808, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {24000000, 4000, 3000, 0, 0, 0, 0, 13, 0x94, 5, 1, "Samsung", "WB550"}, {12582980, 3072, 2048, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {33292868, 4080, 4080, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {44390468, 4080, 5440, 0, 0, 0, 0, 33, 0x61, 0, 0, "Sinar", "", 68}, {1409024, 1376, 1024, 0, 0, 1, 0, 0, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, {2818048, 1376, 1024, 0, 0, 1, 0, 97, 0x49, 0, 0, "Sony", "XCD-SX910CR"}, }; #ifdef LIBRAW_LIBRARY_BUILD libraw_custom_camera_t table[64 + sizeof(const_table) / sizeof(const_table[0])]; #endif static const char *corp[] = {"AgfaPhoto", "Canon", "Casio", "Epson", "Fujifilm", "Mamiya", "Minolta", "Motorola", "Kodak", "Konica", "Leica", "Nikon", "Nokia", "Olympus", "Pentax", "Phase One", "Ricoh", "Samsung", "Sigma", "Sinar", "Sony"}; #ifdef LIBRAW_LIBRARY_BUILD char head[64], *cp; #else char head[32], *cp; #endif int hlen, flen, fsize, zero_fsize = 1, i, c; struct jhead jh; #ifdef LIBRAW_LIBRARY_BUILD unsigned camera_count = parse_custom_cameras(64, table, imgdata.params.custom_camera_strings); for (int q = 0; q < sizeof(const_table) / sizeof(const_table[0]); q++) memmove(&table[q + camera_count], &const_table[q], sizeof(const_table[0])); camera_count += sizeof(const_table) / sizeof(const_table[0]); #endif tiff_flip = flip = filters = UINT_MAX; /* unknown */ raw_height = raw_width = fuji_width = fuji_layout = cr2_slice[0] = 0; maximum = height = width = top_margin = left_margin = 0; cdesc[0] = desc[0] = artist[0] = make[0] = model[0] = model2[0] = 0; iso_speed = shutter = aperture = focal_len = unique_id = 0; tiff_nifds = 0; memset(tiff_ifd, 0, sizeof tiff_ifd); #ifdef LIBRAW_LIBRARY_BUILD imgdata.other.CameraTemperature = imgdata.other.SensorTemperature = imgdata.other.SensorTemperature2 = imgdata.other.LensTemperature = imgdata.other.AmbientTemperature = imgdata.other.BatteryTemperature = imgdata.other.exifAmbientTemperature = -1000.0f; for (i = 0; i < LIBRAW_IFD_MAXCOUNT; i++) { tiff_ifd[i].dng_color[0].illuminant = tiff_ifd[i].dng_color[1].illuminant = 0xffff; for (int c = 0; c < 4; c++) tiff_ifd[i].dng_levels.analogbalance[c] = 1.0f; } #endif memset(gpsdata, 0, sizeof gpsdata); memset(cblack, 0, sizeof cblack); memset(white, 0, sizeof white); memset(mask, 0, sizeof mask); thumb_offset = thumb_length = thumb_width = thumb_height = 0; load_raw = thumb_load_raw = 0; write_thumb = &CLASS jpeg_thumb; data_offset = meta_offset = meta_length = tiff_bps = tiff_compress = 0; kodak_cbpp = zero_after_ff = dng_version = load_flags = 0; timestamp = shot_order = tiff_samples = black = is_foveon = 0; mix_green = profile_length = data_error = zero_is_bad = 0; pixel_aspect = is_raw = raw_color = 1; tile_width = tile_length = 0; for (i = 0; i < 4; i++) { cam_mul[i] = i == 1; pre_mul[i] = i < 3; FORC3 cmatrix[c][i] = 0; FORC3 rgb_cam[c][i] = c == i; } colors = 3; for (i = 0; i < 0x10000; i++) curve[i] = i; order = get2(); hlen = get4(); fseek(ifp, 0, SEEK_SET); #ifdef LIBRAW_LIBRARY_BUILD fread(head, 1, 64, ifp); libraw_internal_data.unpacker_data.lenRAFData = libraw_internal_data.unpacker_data.posRAFData = 0; #else fread(head, 1, 32, ifp); #endif fseek(ifp, 0, SEEK_END); flen = fsize = ftell(ifp); if ((cp = (char *)memmem(head, 32, (char *)"MMMM", 4)) || (cp = (char *)memmem(head, 32, (char *)"IIII", 4))) { parse_phase_one(cp - head); if (cp - head && parse_tiff(0)) apply_tiff(); } else if (order == 0x4949 || order == 0x4d4d) { if (!memcmp(head + 6, "HEAPCCDR", 8)) { data_offset = hlen; #ifdef LIBRAW_LIBRARY_BUILD imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; #endif parse_ciff(hlen, flen - hlen, 0); load_raw = &CLASS canon_load_raw; } else if (parse_tiff(0)) apply_tiff(); } else if (!memcmp(head, "\xff\xd8\xff\xe1", 4) && !memcmp(head + 6, "Exif", 4)) { fseek(ifp, 4, SEEK_SET); data_offset = 4 + get2(); fseek(ifp, data_offset, SEEK_SET); if (fgetc(ifp) != 0xff) parse_tiff(12); thumb_offset = 0; } else if (!memcmp(head + 25, "ARECOYK", 7)) { strcpy(make, "Contax"); strcpy(model, "N Digital"); fseek(ifp, 33, SEEK_SET); get_timestamp(1); fseek(ifp, 52, SEEK_SET); switch (get4()) { case 7: iso_speed = 25; break; case 8: iso_speed = 32; break; case 9: iso_speed = 40; break; case 10: iso_speed = 50; break; case 11: iso_speed = 64; break; case 12: iso_speed = 80; break; case 13: iso_speed = 100; break; case 14: iso_speed = 125; break; case 15: iso_speed = 160; break; case 16: iso_speed = 200; break; case 17: iso_speed = 250; break; case 18: iso_speed = 320; break; case 19: iso_speed = 400; break; } shutter = powf64(2.0f, (((float)get4()) / 8.0f)) / 16000.0f; FORC4 cam_mul[c ^ (c >> 1)] = get4(); fseek(ifp, 88, SEEK_SET); aperture = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 112, SEEK_SET); focal_len = get4(); #ifdef LIBRAW_LIBRARY_BUILD fseek(ifp, 104, SEEK_SET); imgdata.lens.makernotes.MaxAp4CurFocal = powf64(2.0f, ((float)get4()) / 16.0f); fseek(ifp, 124, SEEK_SET); stmread(imgdata.lens.makernotes.Lens, 32, ifp); imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_Contax_N; if (imgdata.lens.makernotes.Lens[0]) imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_Contax_N; #endif } else if (!strcmp(head, "PXN")) { strcpy(make, "Logitech"); strcpy(model, "Fotoman Pixtura"); } else if (!strcmp(head, "qktk")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 100"); load_raw = &CLASS quicktake_100_load_raw; } else if (!strcmp(head, "qktn")) { strcpy(make, "Apple"); strcpy(model, "QuickTake 150"); load_raw = &CLASS kodak_radc_load_raw; } else if (!memcmp(head, "FUJIFILM", 8)) { #ifdef LIBRAW_LIBRARY_BUILD strcpy(model, head + 0x1c); memcpy(model2, head + 0x3c, 4); model2[4] = 0; #endif fseek(ifp, 84, SEEK_SET); thumb_offset = get4(); thumb_length = get4(); fseek(ifp, 92, SEEK_SET); parse_fuji(get4()); if (thumb_offset > 120) { fseek(ifp, 120, SEEK_SET); is_raw += (i = get4()) ? 1 : 0; if (is_raw == 2 && shot_select) parse_fuji(i); } load_raw = &CLASS unpacked_load_raw; fseek(ifp, 100 + 28 * (shot_select > 0), SEEK_SET); parse_tiff(data_offset = get4()); parse_tiff(thumb_offset + 12); apply_tiff(); } else if (!memcmp(head, "RIFF", 4)) { fseek(ifp, 0, SEEK_SET); parse_riff(); } else if (!memcmp(head + 4, "ftypqt ", 9)) { fseek(ifp, 0, SEEK_SET); parse_qt(fsize); is_raw = 0; } else if (!memcmp(head, "\0\001\0\001\0@", 6)) { fseek(ifp, 6, SEEK_SET); fread(make, 1, 8, ifp); fread(model, 1, 8, ifp); fread(model2, 1, 16, ifp); data_offset = get2(); get2(); raw_width = get2(); raw_height = get2(); load_raw = &CLASS nokia_load_raw; filters = 0x61616161; } else if (!memcmp(head, "NOKIARAW", 8)) { strcpy(make, "NOKIA"); order = 0x4949; fseek(ifp, 300, SEEK_SET); data_offset = get4(); i = get4(); // bytes count width = get2(); height = get2(); #ifdef LIBRAW_LIBRARY_BUILD // Data integrity check if(width < 1 || width > 16000 || height < 1 || height > 16000 || i < (width*height) || i > (2* width*height)) throw LIBRAW_EXCEPTION_IO_CORRUPT; #endif switch (tiff_bps = i * 8 / (width * height)) { case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: load_raw = &CLASS nokia_load_raw; } raw_height = height + (top_margin = i / (width * tiff_bps / 8) - height); mask[0][3] = 1; filters = 0x61616161; } else if (!memcmp(head, "ARRI", 4)) { order = 0x4949; fseek(ifp, 20, SEEK_SET); width = get4(); height = get4(); strcpy(make, "ARRI"); fseek(ifp, 668, SEEK_SET); fread(model, 1, 64, ifp); data_offset = 4096; load_raw = &CLASS packed_load_raw; load_flags = 88; filters = 0x61616161; } else if (!memcmp(head, "XPDS", 4)) { order = 0x4949; fseek(ifp, 0x800, SEEK_SET); fread(make, 1, 41, ifp); raw_height = get2(); raw_width = get2(); fseek(ifp, 56, SEEK_CUR); fread(model, 1, 30, ifp); data_offset = 0x10000; load_raw = &CLASS canon_rmf_load_raw; gamma_curve(0, 12.25, 1, 1023); } else if (!memcmp(head + 4, "RED1", 4)) { strcpy(make, "Red"); strcpy(model, "One"); parse_redcine(); load_raw = &CLASS redcine_load_raw; gamma_curve(1 / 2.4, 12.92, 1, 4095); filters = 0x49494949; } else if (!memcmp(head, "DSC-Image", 9)) parse_rollei(); else if (!memcmp(head, "PWAD", 4)) parse_sinar_ia(); else if (!memcmp(head, "\0MRM", 4)) parse_minolta(0); else if (!memcmp(head, "FOVb", 4)) { #ifdef LIBRAW_LIBRARY_BUILD /* no foveon support for dcraw build from libraw source */ parse_x3f(); #endif } else if (!memcmp(head, "CI", 2)) parse_cine(); if (make[0] == 0) #ifdef LIBRAW_LIBRARY_BUILD for (zero_fsize = i = 0; i < camera_count; i++) #else for (zero_fsize = i = 0; i < sizeof table / sizeof *table; i++) #endif if (fsize == table[i].fsize) { strcpy(make, table[i].t_make); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(make, "Canon", 5)) { imgdata.lens.makernotes.CameraMount = LIBRAW_MOUNT_FixedLens; imgdata.lens.makernotes.LensMount = LIBRAW_MOUNT_FixedLens; } #endif strcpy(model, table[i].t_model); flip = table[i].flags >> 2; zero_is_bad = table[i].flags & 2; if (table[i].flags & 1) parse_external_jpeg(); data_offset = table[i].offset == 0xffff ? 0 : table[i].offset; raw_width = table[i].rw; raw_height = table[i].rh; left_margin = table[i].lm; top_margin = table[i].tm; width = raw_width - left_margin - table[i].rm; height = raw_height - top_margin - table[i].bm; filters = 0x1010101 * table[i].cf; colors = 4 - !((filters & filters >> 1) & 0x5555); load_flags = table[i].lf; switch (tiff_bps = (fsize - data_offset) * 8 / (raw_width * raw_height)) { case 6: load_raw = &CLASS minolta_rd175_load_raw; break; case 8: load_raw = &CLASS eight_bit_load_raw; break; case 10: if ((fsize - data_offset) / raw_height * 3 >= raw_width * 4) { load_raw = &CLASS android_loose_load_raw; break; } else if (load_flags & 1) { load_raw = &CLASS android_tight_load_raw; break; } case 12: load_flags |= 128; load_raw = &CLASS packed_load_raw; break; case 16: order = 0x4949 | 0x404 * (load_flags & 1); tiff_bps -= load_flags >> 4; tiff_bps -= load_flags = load_flags >> 1 & 7; load_raw = table[i].offset == 0xffff ? &CLASS unpacked_load_raw_reversed : &CLASS unpacked_load_raw; } maximum = (1 << tiff_bps) - (1 << table[i].max); break; } if (zero_fsize) fsize = 0; if (make[0] == 0) parse_smal(0, flen); if (make[0] == 0) { parse_jpeg(0); fseek(ifp, 0, SEEK_END); int sz = ftell(ifp); #ifdef LIBRAW_LIBRARY_BUILD if (!strncmp(model, "RP_imx219", 9) && sz >= 0x9cb600 && !fseek(ifp, -0x9cb600, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); strcpy(model, "RPi IMX219"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 66; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x9cb600 - 1; } else if (!(strncmp(model, "ov5647", 6) && strncmp(model, "RP_OV5647", 9)) && sz >= 0x61b800 && !fseek(ifp, -0x61b800, SEEK_END) && fread(head, 1, 0x20, ifp) && !strncmp(head, "BRCM", 4)) { strcpy(make, "Broadcom"); if (!strncmp(model, "ov5647", 6)) strcpy(model, "RPi OV5647 v.1"); else strcpy(model, "RPi OV5647 v.2"); if (raw_height > raw_width) flip = 5; data_offset = ftell(ifp) + 0x8000 - 0x20; parse_broadcom(); black = 16; maximum = 0x3ff; load_raw = &CLASS broadcom_load_raw; thumb_offset = 0; thumb_length = sz - 0x61b800 - 1; #else if (!(strncmp(model, "ov", 2) && strncmp(model, "RP_OV", 5)) && sz >= 6404096 && !fseek(ifp, -6404096, SEEK_END) && fread(head, 1, 32, ifp) && !strcmp(head, "BRCMn")) { strcpy(make, "OmniVision"); data_offset = ftell(ifp) + 0x8000 - 32; width = raw_width; raw_width = 2611; load_raw = &CLASS nokia_load_raw; filters = 0x16161616; #endif } else is_raw = 0; } #ifdef LIBRAW_LIBRARY_BUILD // make sure strings are terminated desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; #endif for (i = 0; i < sizeof corp / sizeof *corp; i++) if (strcasestr(make, corp[i])) /* Simplify company names */ strcpy(make, corp[i]); if ((!strncmp(make, "Kodak", 5) || !strncmp(make, "Leica", 5)) && ((cp = strcasestr(model, " DIGITAL CAMERA")) || (cp = strstr(model, "FILE VERSION")))) *cp = 0; if (!strncasecmp(model, "PENTAX", 6)) strcpy(make, "Pentax"); #ifdef LIBRAW_LIBRARY_BUILD remove_trailing_spaces(make, sizeof(make)); remove_trailing_spaces(model, sizeof(model)); #else cp = make + strlen(make); /* Remove trailing spaces */ while (*--cp == ' ') *cp = 0; cp = model + strlen(model); while (*--cp == ' ') *cp = 0; #endif i = strbuflen(make); /* Remove make from model */ if (!strncasecmp(model, make, i) && model[i++] == ' ') memmove(model, model + i, 64 - i); if (!strncmp(model, "FinePix ", 8)) strcpy(model, model + 8); if (!strncmp(model, "Digital Camera ", 15)) strcpy(model, model + 15); desc[511] = artist[63] = make[63] = model[63] = model2[63] = 0; if (!is_raw) goto notraw; if (!height) height = raw_height; if (!width) width = raw_width; if (height == 2624 && width == 3936) /* Pentax K10D and Samsung GX10 */ { height = 2616; width = 3896; } if (height == 3136 && width == 4864) /* Pentax K20D and Samsung GX20 */ { height = 3124; width = 4688; filters = 0x16161616; } if (width == 4352 && (!strcmp(model, "K-r") || !strcmp(model, "K-x"))) { width = 4309; filters = 0x16161616; } if (width >= 4960 && !strncmp(model, "K-5", 3)) { left_margin = 10; width = 4950; filters = 0x16161616; } if (width == 6080 && !strcmp(model, "K-70")) { height = 4016; top_margin = 32; width = 6020; left_margin = 60; } if (width == 4736 && !strcmp(model, "K-7")) { height = 3122; width = 4684; filters = 0x16161616; top_margin = 2; } if (width == 6080 && !strcmp(model, "K-3 II")) /* moved back */ { left_margin = 4; width = 6040; } if (width == 6112 && !strcmp(model, "KP")) { /* From DNG, maybe too strict */ left_margin = 54; top_margin = 28; width = 6028; height = raw_height - top_margin; } if (width == 6080 && !strcmp(model, "K-3")) { left_margin = 4; width = 6040; } if (width == 7424 && !strcmp(model, "645D")) { height = 5502; width = 7328; filters = 0x61616161; top_margin = 29; left_margin = 48; } if (height == 3014 && width == 4096) /* Ricoh GX200 */ width = 4014; if (dng_version) { if (filters == UINT_MAX) filters = 0; if (filters) is_raw *= tiff_samples; else colors = tiff_samples; switch (tiff_compress) { case 0: /* Compression not set, assuming uncompressed */ case 1: load_raw = &CLASS packed_dng_load_raw; break; case 7: load_raw = &CLASS lossless_dng_load_raw; break; #ifdef LIBRAW_LIBRARY_BUILD case 8: load_raw = &CLASS deflate_dng_load_raw; break; #endif case 34892: load_raw = &CLASS lossy_dng_load_raw; break; default: load_raw = 0; } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { strcpy(model, unique[i].t_model); break; } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { strcpy(model, sonique[i].t_model); break; } } goto dng_skip; } if (!strncmp(make, "Canon", 5) && !fsize && tiff_bps != 15) { if (!load_raw) load_raw = &CLASS lossless_jpeg_load_raw; for (i = 0; i < sizeof canon / sizeof *canon; i++) if (raw_width == canon[i][0] && raw_height == canon[i][1]) { width = raw_width - (left_margin = canon[i][2]); height = raw_height - (top_margin = canon[i][3]); width -= canon[i][4]; height -= canon[i][5]; mask[0][1] = canon[i][6]; mask[0][3] = -canon[i][7]; mask[1][1] = canon[i][8]; mask[1][3] = -canon[i][9]; if (canon[i][10]) filters = canon[i][10] * 0x01010101; } if ((unique_id | 0x20000) == 0x2720000) { left_margin = 8; top_margin = 16; } } if (!strncmp(make, "Canon", 5) && unique_id) { for (i = 0; i < sizeof unique / sizeof *unique; i++) if (unique_id == 0x80000000 + unique[i].id) { adobe_coeff("Canon", unique[i].t_model); strcpy(model, unique[i].t_model); } } if (!strncasecmp(make, "Sony", 4) && unique_id) { for (i = 0; i < sizeof sonique / sizeof *sonique; i++) if (unique_id == sonique[i].id) { adobe_coeff("Sony", sonique[i].t_model); strcpy(model, sonique[i].t_model); } } if (!strncmp(make, "Nikon", 5)) { if (!load_raw) load_raw = &CLASS packed_load_raw; if (model[0] == 'E') load_flags |= !data_offset << 2 | 2; } /* Set parameters based on camera name (for non-DNG files). */ if (!strcmp(model, "KAI-0340") && find_green(16, 16, 3840, 5120) < 25) { height = 480; top_margin = filters = 0; strcpy(model, "C603"); } #ifndef LIBRAW_LIBRARY_BUILD if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = 128 << (tiff_bps - 12); #else /* Always 512 for arw2_load_raw */ if (!strcmp(make, "Sony") && raw_width > 3888 && !black && !cblack[0]) black = (load_raw == &LibRaw::sony_arw2_load_raw) ? 512 : (128 << (tiff_bps - 12)); #endif if (is_foveon) { if (height * 2 < width) pixel_aspect = 0.5; if (height > width) pixel_aspect = 2; filters = 0; } else if (!strncmp(make, "Pentax", 6) && !strncmp(model, "K-1", 3)) { top_margin = 18; height = raw_height - top_margin; if (raw_width == 7392) { left_margin = 6; width = 7376; } } else if (!strncmp(make, "Canon", 5) && tiff_bps == 15) { switch (width) { case 3344: width -= 66; case 3872: width -= 6; } if (height > width) { SWAP(height, width); SWAP(raw_height, raw_width); } if (width == 7200 && height == 3888) { raw_width = width = 6480; raw_height = height = 4320; } filters = 0; tiff_samples = colors = 3; load_raw = &CLASS canon_sraw_load_raw; } else if (!strcmp(model, "PowerShot 600")) { height = 613; width = 854; raw_width = 896; colors = 4; filters = 0xe1e4e1e4; load_raw = &CLASS canon_600_load_raw; } else if (!strcmp(model, "PowerShot A5") || !strcmp(model, "PowerShot A5 Zoom")) { height = 773; width = 960; raw_width = 992; pixel_aspect = 256 / 235.0; filters = 0x1e4e1e4e; goto canon_a5; } else if (!strcmp(model, "PowerShot A50")) { height = 968; width = 1290; raw_width = 1320; filters = 0x1b4e4b1e; goto canon_a5; } else if (!strcmp(model, "PowerShot Pro70")) { height = 1024; width = 1552; filters = 0x1e4b4e1b; canon_a5: colors = 4; tiff_bps = 10; load_raw = &CLASS packed_load_raw; load_flags = 40; } else if (!strcmp(model, "PowerShot Pro90 IS") || !strcmp(model, "PowerShot G1")) { colors = 4; filters = 0xb4b4b4b4; } else if (!strcmp(model, "PowerShot A610")) { if (canon_s2is()) strcpy(model + 10, "S2 IS"); } else if (!strcmp(model, "PowerShot SX220 HS")) { mask[1][3] = -4; top_margin = 16; left_margin = 92; } else if (!strcmp(model, "PowerShot S120")) { raw_width = 4192; raw_height = 3062; width = 4022; height = 3016; mask[0][0] = top_margin = 31; mask[0][2] = top_margin + height; left_margin = 120; mask[0][1] = 23; mask[0][3] = 72; } else if (!strcmp(model, "PowerShot G16")) { mask[0][0] = 0; mask[0][2] = 80; mask[0][1] = 0; mask[0][3] = 16; top_margin = 29; left_margin = 120; width = raw_width - left_margin - 48; height = raw_height - top_margin - 14; } else if (!strcmp(model, "PowerShot SX50 HS")) { top_margin = 17; } else if (!strcmp(model, "EOS D2000C")) { filters = 0x61616161; if (!black) black = curve[200]; } else if (!strcmp(model, "D1")) { cam_mul[0] *= 256 / 527.0; cam_mul[2] *= 256 / 317.0; } else if (!strcmp(model, "D1X")) { width -= 4; pixel_aspect = 0.5; } else if (!strcmp(model, "D40X") || !strcmp(model, "D60") || !strcmp(model, "D80") || !strcmp(model, "D3000")) { height -= 3; width -= 4; } else if (!strcmp(model, "D3") || !strcmp(model, "D3S") || !strcmp(model, "D700")) { width -= 4; left_margin = 2; } else if (!strcmp(model, "D3100")) { width -= 28; left_margin = 6; } else if (!strcmp(model, "D5000") || !strcmp(model, "D90")) { width -= 42; } else if (!strcmp(model, "D5100") || !strcmp(model, "D7000") || !strcmp(model, "COOLPIX A")) { width -= 44; } else if (!strcmp(model, "D3200") || !strncmp(model, "D6", 2) || !strncmp(model, "D800", 4)) { width -= 46; } else if (!strcmp(model, "D4") || !strcmp(model, "Df")) { width -= 52; left_margin = 2; } else if (!strcmp(model, "D500")) { // Empty - to avoid width-1 below } else if (!strncmp(model, "D40", 3) || !strncmp(model, "D50", 3) || !strncmp(model, "D70", 3)) { width--; } else if (!strcmp(model, "D100")) { if (load_flags) raw_width = (width += 3) + 3; } else if (!strcmp(model, "D200")) { left_margin = 1; width -= 4; filters = 0x94949494; } else if (!strncmp(model, "D2H", 3)) { left_margin = 6; width -= 14; } else if (!strncmp(model, "D2X", 3)) { if (width == 3264) width -= 32; else width -= 8; } else if (!strncmp(model, "D300", 4)) { width -= 32; } else if (!strncmp(make, "Nikon", 5) && raw_width == 4032) { if (!strcmp(model, "COOLPIX P7700")) { adobe_coeff("Nikon", "COOLPIX P7700"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P7800")) { adobe_coeff("Nikon", "COOLPIX P7800"); maximum = 65504; load_flags = 0; } else if (!strcmp(model, "COOLPIX P340")) load_flags = 0; } else if (!strncmp(model, "COOLPIX P", 9) && raw_width != 4032) { load_flags = 24; filters = 0x94949494; if (model[9] == '7' && (iso_speed >= 400 || iso_speed == 0) && !strstr(software, "V1.2")) black = 255; } else if (!strncmp(model, "COOLPIX B700", 12)) { load_flags = 24; black = 200; } else if (!strncmp(model, "1 ", 2)) { height -= 2; } else if (fsize == 1581060) { simple_coeff(3); pre_mul[0] = 1.2085; pre_mul[1] = 1.0943; pre_mul[3] = 1.1103; } else if (fsize == 3178560) { cam_mul[0] *= 4; cam_mul[2] *= 4; } else if (fsize == 4771840) { if (!timestamp && nikon_e995()) strcpy(model, "E995"); if (strcmp(model, "E995")) { filters = 0xb4b4b4b4; simple_coeff(3); pre_mul[0] = 1.196; pre_mul[1] = 1.246; pre_mul[2] = 1.018; } } else if (fsize == 2940928) { if (!timestamp && !nikon_e2100()) strcpy(model, "E2500"); if (!strcmp(model, "E2500")) { height -= 2; load_flags = 6; colors = 4; filters = 0x4b4b4b4b; } } else if (fsize == 4775936) { if (!timestamp) nikon_3700(); if (model[0] == 'E' && atoi(model + 1) < 3700) filters = 0x49494949; if (!strcmp(model, "Optio 33WR")) { flip = 1; filters = 0x16161616; } if (make[0] == 'O') { i = find_green(12, 32, 1188864, 3576832); c = find_green(12, 32, 2383920, 2387016); if (abs(i) < abs(c)) { SWAP(i, c); load_flags = 24; } if (i < 0) filters = 0x61616161; } } else if (fsize == 5869568) { if (!timestamp && minolta_z2()) { strcpy(make, "Minolta"); strcpy(model, "DiMAGE Z2"); } load_flags = 6 + 24 * (make[0] == 'M'); } else if (fsize == 6291456) { fseek(ifp, 0x300000, SEEK_SET); if ((order = guess_byte_order(0x10000)) == 0x4d4d) { height -= (top_margin = 16); width -= (left_margin = 28); maximum = 0xf5c0; strcpy(make, "ISG"); model[0] = 0; } } else if (!strncmp(make, "Fujifilm", 8)) { if (!strcmp(model, "X-A3") || !strcmp(model, "X-A10")) { left_margin = 0; top_margin = 0; width = raw_width; height = raw_height; } if (!strcmp(model + 7, "S2Pro")) { strcpy(model, "S2Pro"); height = 2144; width = 2880; flip = 6; } else if (load_raw != &CLASS packed_load_raw && strncmp(model, "X-", 2)) maximum = (is_raw == 2 && shot_select) ? 0x2f00 : 0x3e00; top_margin = (raw_height - height) >> 2 << 1; left_margin = (raw_width - width) >> 2 << 1; if (width == 2848 || width == 3664) filters = 0x16161616; if (width == 4032 || width == 4952) left_margin = 0; if (width == 3328 && (width -= 66)) left_margin = 34; if (width == 4936) left_margin = 4; if (width == 6032) left_margin = 0; if (!strcmp(model, "HS50EXR") || !strcmp(model, "F900EXR")) { width += 2; left_margin = 0; filters = 0x16161616; } if (!strcmp(model, "GFX 50S")) { left_margin = 0; top_margin = 0; } if (!strcmp(model, "S5500")) { height -= (top_margin = 6); } if (fuji_layout) raw_width *= is_raw; if (filters == 9) FORC(36)((char *)xtrans)[c] = xtrans_abs[(c / 6 + top_margin) % 6][(c + left_margin) % 6]; } else if (!strcmp(model, "KD-400Z")) { height = 1712; width = 2312; raw_width = 2336; goto konica_400z; } else if (!strcmp(model, "KD-510Z")) { goto konica_510z; } else if (!strncasecmp(make, "Minolta", 7)) { if (!load_raw && (maximum = 0xfff)) load_raw = &CLASS unpacked_load_raw; if (!strncmp(model, "DiMAGE A", 8)) { if (!strcmp(model, "DiMAGE A200")) filters = 0x49494949; tiff_bps = 12; load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "ALPHA", 5) || !strncmp(model, "DYNAX", 5) || !strncmp(model, "MAXXUM", 6)) { sprintf(model + 20, "DYNAX %-10s", model + 6 + (model[0] == 'M')); adobe_coeff(make, model + 20); load_raw = &CLASS packed_load_raw; } else if (!strncmp(model, "DiMAGE G", 8)) { if (model[8] == '4') { height = 1716; width = 2304; } else if (model[8] == '5') { konica_510z: height = 1956; width = 2607; raw_width = 2624; } else if (model[8] == '6') { height = 2136; width = 2848; } data_offset += 14; filters = 0x61616161; konica_400z: load_raw = &CLASS unpacked_load_raw; maximum = 0x3df; order = 0x4d4d; } } else if (!strcmp(model, "*ist D")) { load_raw = &CLASS unpacked_load_raw; data_error = -1; } else if (!strcmp(model, "*ist DS")) { height -= 2; } else if (!strncmp(make, "Samsung", 7) && raw_width == 4704) { height -= top_margin = 8; width -= 2 * (left_margin = 8); load_flags = 32; } else if (!strncmp(make, "Samsung", 7) && !strcmp(model, "NX3000")) { top_margin = 38; left_margin = 92; width = 5456; height = 3634; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_height == 3714) { height -= top_margin = 18; left_margin = raw_width - (width = 5536); if (raw_width != 5600) left_margin = top_margin = 0; filters = 0x61616161; colors = 3; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5632) { order = 0x4949; height = 3694; top_margin = 2; width = 5574 - (left_margin = 32 + tiff_bps); if (tiff_bps == 12) load_flags = 80; } else if (!strncmp(make, "Samsung", 7) && raw_width == 5664) { height -= top_margin = 17; left_margin = 96; width = 5544; filters = 0x49494949; } else if (!strncmp(make, "Samsung", 7) && raw_width == 6496) { filters = 0x61616161; #ifdef LIBRAW_LIBRARY_BUILD if (!black && !cblack[0] && !cblack[1] && !cblack[2] && !cblack[3]) #endif black = 1 << (tiff_bps - 7); } else if (!strcmp(model, "EX1")) { order = 0x4949; height -= 20; top_margin = 2; if ((width -= 6) > 3682) { height -= 10; width -= 46; top_margin = 8; } } else if (!strcmp(model, "WB2000")) { order = 0x4949; height -= 3; top_margin = 2; if ((width -= 10) > 3718) { height -= 28; width -= 56; top_margin = 8; } } else if (strstr(model, "WB550")) { strcpy(model, "WB550"); } else if (!strcmp(model, "EX2F")) { height = 3030; width = 4040; top_margin = 15; left_margin = 24; order = 0x4949; filters = 0x49494949; load_raw = &CLASS unpacked_load_raw; } else if (!strcmp(model, "STV680 VGA")) { black = 16; } else if (!strcmp(model, "N95")) { height = raw_height - (top_margin = 2); } else if (!strcmp(model, "640x480")) { gamma_curve(0.45, 4.5, 1, 255); } else if (!strncmp(make, "Hasselblad", 10)) { if (load_raw == &CLASS lossless_jpeg_load_raw) load_raw = &CLASS hasselblad_load_raw; if (raw_width == 7262) { height = 5444; width = 7248; top_margin = 4; left_margin = 7; filters = 0x61616161; if (!strncasecmp(model, "H3D", 3)) { adobe_coeff("Hasselblad", "H3DII-39"); strcpy(model, "H3DII-39"); } } else if (raw_width == 12000) // H6D 100c, A6D 100c { left_margin = 64; width = 11608; top_margin = 108; height = raw_height - top_margin; adobe_coeff("Hasselblad", "H6D-100c"); } else if (raw_width == 7410 || raw_width == 8282) { height -= 84; width -= 82; top_margin = 4; left_margin = 41; filters = 0x61616161; adobe_coeff("Hasselblad", "H4D-40"); strcpy(model, "H4D-40"); } else if (raw_width == 8384) // X1D { top_margin = 96; height -= 96; left_margin = 48; width -= 106; adobe_coeff("Hasselblad", "X1D"); maximum = 0xffff; tiff_bps = 16; } else if (raw_width == 9044) { if (black > 500) { top_margin = 12; left_margin = 44; width = 8956; height = 6708; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H4D-60"); strcpy(model, "H4D-60"); black = 512; } else { height = 6716; width = 8964; top_margin = 8; left_margin = 40; black += load_flags = 256; maximum = 0x8101; strcpy(model, "H3DII-60"); } } else if (raw_width == 4090) { strcpy(model, "V96C"); height -= (top_margin = 6); width -= (left_margin = 3) + 7; filters = 0x61616161; } else if (raw_width == 8282 && raw_height == 6240) { if (!strncasecmp(model, "H5D", 3)) { /* H5D 50*/ left_margin = 54; top_margin = 16; width = 8176; height = 6132; black = 256; strcpy(model, "H5D-50"); } else if (!strncasecmp(model, "H3D", 3)) { black = 0; left_margin = 54; top_margin = 16; width = 8176; height = 6132; memset(cblack, 0, sizeof(cblack)); adobe_coeff("Hasselblad", "H3D-50"); strcpy(model, "H3D-50"); } } else if (raw_width == 8374 && raw_height == 6304) { /* H5D 50c*/ left_margin = 52; top_margin = 100; width = 8272; height = 6200; black = 256; strcpy(model, "H5D-50c"); } if (tiff_samples > 1) { is_raw = tiff_samples + 1; if (!shot_select && !half_size) filters = 0; } } else if (!strncmp(make, "Sinar", 5)) { if (!load_raw) load_raw = &CLASS unpacked_load_raw; if (is_raw > 1 && !shot_select && !half_size) filters = 0; maximum = 0x3fff; } else if (!strncmp(make, "Leaf", 4)) { maximum = 0x3fff; fseek(ifp, data_offset, SEEK_SET); if (ljpeg_start(&jh, 1) && jh.bits == 15) maximum = 0x1fff; if (tiff_samples > 1) filters = 0; if (tiff_samples > 1 || tile_length < raw_height) { load_raw = &CLASS leaf_hdr_load_raw; raw_width = tile_width; } if ((width | height) == 2048) { if (tiff_samples == 1) { filters = 1; strcpy(cdesc, "RBTG"); strcpy(model, "CatchLight"); top_margin = 8; left_margin = 18; height = 2032; width = 2016; } else { strcpy(model, "DCB2"); top_margin = 10; left_margin = 16; height = 2028; width = 2022; } } else if (width + height == 3144 + 2060) { if (!model[0]) strcpy(model, "Cantare"); if (width > height) { top_margin = 6; left_margin = 32; height = 2048; width = 3072; filters = 0x61616161; } else { left_margin = 6; top_margin = 32; width = 2048; height = 3072; filters = 0x16161616; } if (!cam_mul[0] || model[0] == 'V') filters = 0; else is_raw = tiff_samples; } else if (width == 2116) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 30); width -= 2 * (left_margin = 55); filters = 0x49494949; } else if (width == 3171) { strcpy(model, "Valeo 6"); height -= 2 * (top_margin = 24); width -= 2 * (left_margin = 24); filters = 0x16161616; } } else if (!strncmp(make, "Leica", 5) || !strncmp(make, "Panasonic", 9) || !strncasecmp(make, "YUNEEC", 6)) { if (raw_width > 0 && ((flen - data_offset) / (raw_width * 8 / 7) == raw_height)) load_raw = &CLASS panasonic_load_raw; if (!load_raw) { load_raw = &CLASS unpacked_load_raw; load_flags = 4; } zero_is_bad = 1; #ifdef LIBRAW_LIBRARY_BUILD float fratio = float(data_size) / (float(raw_height) * float(raw_width)); if(!(raw_width % 10) && !(data_size % 16384) && fratio >= 1.6f && fratio <= 1.6001f) { load_raw = &CLASS panasonic_16x10_load_raw; zero_is_bad = 0; } #endif if ((height += 12) > raw_height) height = raw_height; for (i = 0; i < sizeof pana / sizeof *pana; i++) if (raw_width == pana[i][0] && raw_height == pana[i][1]) { left_margin = pana[i][2]; top_margin = pana[i][3]; width += pana[i][4]; height += pana[i][5]; } filters = 0x01010101 * (uchar) "\x94\x61\x49\x16"[((filters - 1) ^ (left_margin & 1) ^ (top_margin << 1)) & 3]; } else if (!strcmp(model, "C770UZ")) { height = 1718; width = 2304; filters = 0x16161616; load_raw = &CLASS packed_load_raw; load_flags = 30; } else if (!strncmp(make, "Olympus", 7)) { height += height & 1; if (exif_cfa) filters = exif_cfa; if (width == 4100) width -= 4; if (width == 4080) width -= 24; if (width == 9280) { width -= 6; height -= 6; } if (load_raw == &CLASS unpacked_load_raw) load_flags = 4; tiff_bps = 12; if (!strcmp(model, "E-300") || !strcmp(model, "E-500")) { width -= 20; if (load_raw == &CLASS unpacked_load_raw) { maximum = 0xfc3; memset(cblack, 0, sizeof cblack); } } else if (!strcmp(model, "STYLUS1")) { width -= 14; maximum = 0xfff; } else if (!strcmp(model, "E-330")) { width -= 30; if (load_raw == &CLASS unpacked_load_raw) maximum = 0xf79; } else if (!strcmp(model, "SP550UZ")) { thumb_length = flen - (thumb_offset = 0xa39800); thumb_height = 480; thumb_width = 640; } else if (!strcmp(model, "TG-4")) { width -= 16; } else if (!strcmp(model, "TG-5")) { width -= 26; } } else if (!strcmp(model, "N Digital")) { height = 2047; width = 3072; filters = 0x61616161; data_offset = 0x1a00; load_raw = &CLASS packed_load_raw; } else if (!strcmp(model, "DSC-F828")) { width = 3288; left_margin = 5; mask[1][3] = -17; data_offset = 862144; load_raw = &CLASS sony_load_raw; filters = 0x9c9c9c9c; colors = 4; strcpy(cdesc, "RGBE"); } else if (!strcmp(model, "DSC-V3")) { width = 3109; left_margin = 59; mask[0][1] = 9; data_offset = 787392; load_raw = &CLASS sony_load_raw; } else if (!strncmp(make, "Sony", 4) && raw_width == 3984) { width = 3925; order = 0x4d4d; } else if (!strncmp(make, "Sony", 4) && raw_width == 4288) { width -= 32; } else if (!strcmp(make, "Sony") && raw_width == 4600) { if (!strcmp(model, "DSLR-A350")) height -= 4; black = 0; } else if (!strncmp(make, "Sony", 4) && raw_width == 4928) { if (height < 3280) width -= 8; } else if (!strncmp(make, "Sony", 4) && raw_width == 5504) { // ILCE-3000//5000 width -= height > 3664 ? 8 : 32; } else if (!strncmp(make, "Sony", 4) && raw_width == 6048) { width -= 24; if (strstr(model, "RX1") || strstr(model, "A99")) width -= 6; } else if (!strncmp(make, "Sony", 4) && raw_width == 7392) { width -= 30; } else if (!strncmp(make, "Sony", 4) && raw_width == 8000) { width -= 32; } else if (!strcmp(model, "DSLR-A100")) { if (width == 3880) { height--; width = ++raw_width; } else { height -= 4; width -= 4; order = 0x4d4d; load_flags = 2; } filters = 0x61616161; } else if (!strcmp(model, "PIXL")) { height -= top_margin = 4; width -= left_margin = 32; gamma_curve(0, 7, 1, 255); } else if (!strcmp(model, "C603") || !strcmp(model, "C330") || !strcmp(model, "12MP")) { order = 0x4949; if (filters && data_offset) { fseek(ifp, data_offset < 4096 ? 168 : 5252, SEEK_SET); read_shorts(curve, 256); } else gamma_curve(0, 3.875, 1, 255); load_raw = filters ? &CLASS eight_bit_load_raw : strcmp(model, "C330") ? &CLASS kodak_c603_load_raw : &CLASS kodak_c330_load_raw; load_flags = tiff_bps > 16; tiff_bps = 8; } else if (!strncasecmp(model, "EasyShare", 9)) { data_offset = data_offset < 0x15000 ? 0x15000 : 0x17000; load_raw = &CLASS packed_load_raw; } else if (!strncasecmp(make, "Kodak", 5)) { if (filters == UINT_MAX) filters = 0x61616161; if (!strncmp(model, "NC2000", 6) || !strncmp(model, "EOSDCS", 6) || !strncmp(model, "DCS4", 4)) { width -= 4; left_margin = 2; if (model[6] == ' ') model[6] = 0; if (!strcmp(model, "DCS460A")) goto bw; } else if (!strcmp(model, "DCS660M")) { black = 214; goto bw; } else if (!strcmp(model, "DCS760M")) { bw: colors = 1; filters = 0; } if (!strcmp(model + 4, "20X")) strcpy(cdesc, "MYCY"); if (strstr(model, "DC25")) { strcpy(model, "DC25"); data_offset = 15424; } if (!strncmp(model, "DC2", 3)) { raw_height = 2 + (height = 242); if (!strncmp(model, "DC290", 5)) iso_speed = 100; if (!strncmp(model, "DC280", 5)) iso_speed = 70; if (flen < 100000) { raw_width = 256; width = 249; pixel_aspect = (4.0 * height) / (3.0 * width); } else { raw_width = 512; width = 501; pixel_aspect = (493.0 * height) / (373.0 * width); } top_margin = left_margin = 1; colors = 4; filters = 0x8d8d8d8d; simple_coeff(1); pre_mul[1] = 1.179; pre_mul[2] = 1.209; pre_mul[3] = 1.036; load_raw = &CLASS eight_bit_load_raw; } else if (!strcmp(model, "40")) { strcpy(model, "DC40"); height = 512; width = 768; data_offset = 1152; load_raw = &CLASS kodak_radc_load_raw; tiff_bps = 12; } else if (strstr(model, "DC50")) { strcpy(model, "DC50"); height = 512; width = 768; iso_speed = 84; data_offset = 19712; load_raw = &CLASS kodak_radc_load_raw; } else if (strstr(model, "DC120")) { strcpy(model, "DC120"); raw_height = height = 976; raw_width = width = 848; iso_speed = 160; pixel_aspect = height / 0.75 / width; load_raw = tiff_compress == 7 ? &CLASS kodak_jpeg_load_raw : &CLASS kodak_dc120_load_raw; } else if (!strcmp(model, "DCS200")) { thumb_height = 128; thumb_width = 192; thumb_offset = 6144; thumb_misc = 360; iso_speed = 140; write_thumb = &CLASS layer_thumb; black = 17; } } else if (!strcmp(model, "Fotoman Pixtura")) { height = 512; width = 768; data_offset = 3632; load_raw = &CLASS kodak_radc_load_raw; filters = 0x61616161; simple_coeff(2); } else if (!strncmp(model, "QuickTake", 9)) { if (head[5]) strcpy(model + 10, "200"); fseek(ifp, 544, SEEK_SET); height = get2(); width = get2(); data_offset = (get4(), get2()) == 30 ? 738 : 736; if (height > width) { SWAP(height, width); fseek(ifp, data_offset - 6, SEEK_SET); flip = ~get2() & 3 ? 5 : 6; } filters = 0x61616161; } else if (!strncmp(make, "Rollei", 6) && !load_raw) { switch (raw_width) { case 1316: height = 1030; width = 1300; top_margin = 1; left_margin = 6; break; case 2568: height = 1960; width = 2560; top_margin = 2; left_margin = 8; } filters = 0x16161616; load_raw = &CLASS rollei_load_raw; } else if (!strcmp(model, "GRAS-50S5C")) { height = 2048; width = 2440; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x49494949; order = 0x4949; maximum = 0xfffC; } else if (!strcmp(model, "BB-500CL")) { height = 2058; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "BB-500GE")) { height = 2058; width = 2456; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x3fff; } else if (!strcmp(model, "SVS625CL")) { height = 2050; width = 2448; load_raw = &CLASS unpacked_load_raw; data_offset = 0; filters = 0x94949494; order = 0x4949; maximum = 0x0fff; } /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if (!model[0]) sprintf(model, "%dx%d", width, height); if (filters == UINT_MAX) filters = 0x94949494; if (thumb_offset && !thumb_height) { fseek(ifp, thumb_offset, SEEK_SET); if (ljpeg_start(&jh, 1)) { thumb_width = jh.wide; thumb_height = jh.high; } } dng_skip: #ifdef LIBRAW_LIBRARY_BUILD if (dng_version) /* Override black level by DNG tags */ { /* copy DNG data from per-IFD field to color.dng */ int iifd = 0; // Active IFD we'll show to user. for (; iifd < tiff_nifds; iifd++) if (tiff_ifd[iifd].offset == data_offset) // found break; int pifd = -1; for (int ii = 0; ii < tiff_nifds; ii++) if (tiff_ifd[ii].offset == thumb_offset) // found { pifd = ii; break; } #define CFAROUND(value, filters) filters ? (filters >= 1000 ? ((value + 1) / 2) * 2 : ((value + 5) / 6) * 6) : value #define IFDCOLORINDEX(ifd, subset, bit) \ (tiff_ifd[ifd].dng_color[subset].parsedfields & bit) ? ifd \ : ((tiff_ifd[0].dng_color[subset].parsedfields & bit) ? 0 : -1) #define IFDLEVELINDEX(ifd, bit) \ (tiff_ifd[ifd].dng_levels.parsedfields & bit) ? ifd : ((tiff_ifd[0].dng_levels.parsedfields & bit) ? 0 : -1) #define COPYARR(to, from) memmove(&to, &from, sizeof(from)) if (iifd < tiff_nifds) { int sidx; // Per field, not per structure if (imgdata.params.raw_processing_options & LIBRAW_PROCESSING_USE_DNG_DEFAULT_CROP) { sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPORIGIN); int sidx2 = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_CROPSIZE); if (sidx >= 0 && sidx == sidx2) { int lm = tiff_ifd[sidx].dng_levels.default_crop[0]; int lmm = CFAROUND(lm, filters); int tm = tiff_ifd[sidx].dng_levels.default_crop[1]; int tmm = CFAROUND(tm, filters); int ww = tiff_ifd[sidx].dng_levels.default_crop[2]; int hh = tiff_ifd[sidx].dng_levels.default_crop[3]; if (lmm > lm) ww -= (lmm - lm); if (tmm > tm) hh -= (tmm - tm); if (left_margin + lm + ww <= raw_width && top_margin + tm + hh <= raw_height) { left_margin += lmm; top_margin += tmm; width = ww; height = hh; } } } if (!(imgdata.color.dng_color[0].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 0, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[0].forwardmatrix, tiff_ifd[sidx].dng_color[0].forwardmatrix); } if (!(imgdata.color.dng_color[1].parsedfields & LIBRAW_DNGFM_FORWARDMATRIX)) // Not set already (Leica makernotes) { sidx = IFDCOLORINDEX(iifd, 1, LIBRAW_DNGFM_FORWARDMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[1].forwardmatrix, tiff_ifd[sidx].dng_color[1].forwardmatrix); } for (int ss = 0; ss < 2; ss++) { sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_COLORMATRIX); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].colormatrix, tiff_ifd[sidx].dng_color[ss].colormatrix); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_CALIBRATION); if (sidx >= 0) COPYARR(imgdata.color.dng_color[ss].calibration, tiff_ifd[sidx].dng_color[ss].calibration); sidx = IFDCOLORINDEX(iifd, ss, LIBRAW_DNGFM_ILLUMINANT); if (sidx >= 0) imgdata.color.dng_color[ss].illuminant = tiff_ifd[sidx].dng_color[ss].illuminant; } // Levels sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_ANALOGBALANCE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.analogbalance, tiff_ifd[sidx].dng_levels.analogbalance); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_WHITE); if (sidx >= 0) COPYARR(imgdata.color.dng_levels.dng_whitelevel, tiff_ifd[sidx].dng_levels.dng_whitelevel); sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_BLACK); if (sidx >= 0) { imgdata.color.dng_levels.dng_black = tiff_ifd[sidx].dng_levels.dng_black; COPYARR(imgdata.color.dng_levels.dng_cblack, tiff_ifd[sidx].dng_levels.dng_cblack); } if (pifd >= 0) { sidx = IFDLEVELINDEX(pifd, LIBRAW_DNGFM_PREVIEWCS); if (sidx >= 0) imgdata.color.dng_levels.preview_colorspace = tiff_ifd[sidx].dng_levels.preview_colorspace; } sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_OPCODE2); if (sidx >= 0) meta_offset = tiff_ifd[sidx].opcode2_offset; sidx = IFDLEVELINDEX(iifd, LIBRAW_DNGFM_LINTABLE); INT64 linoff = -1; int linlen = 0; if (sidx >= 0) { linoff = tiff_ifd[sidx].lineartable_offset; linlen = tiff_ifd[sidx].lineartable_len; } if (linoff >= 0 && linlen > 0) { INT64 pos = ftell(ifp); fseek(ifp, linoff, SEEK_SET); linear_table(linlen); fseek(ifp, pos, SEEK_SET); } // Need to add curve too } /* Copy DNG black level to LibRaw's */ maximum = imgdata.color.dng_levels.dng_whitelevel[0]; black = imgdata.color.dng_levels.dng_black; int ll = LIM(0, (sizeof(cblack) / sizeof(cblack[0])), (sizeof(imgdata.color.dng_levels.dng_cblack) / sizeof(imgdata.color.dng_levels.dng_cblack[0]))); for (int i = 0; i < ll; i++) cblack[i] = imgdata.color.dng_levels.dng_cblack[i]; } #endif /* Early reject for damaged images */ if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 4 || colors > 4 || colors < 1) { is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif return; } if ((use_camera_matrix & ((use_camera_wb || dng_version) | 0x2)) && cmatrix[0][0] > 0.125) { memcpy(rgb_cam, cmatrix, sizeof cmatrix); raw_color = 0; } if (raw_color) adobe_coeff(make, model); #ifdef LIBRAW_LIBRARY_BUILD else if (imgdata.color.cam_xyz[0][0] < 0.01) adobe_coeff(make, model, 1); #endif if (load_raw == &CLASS kodak_radc_load_raw) if (raw_color) adobe_coeff("Apple", "Quicktake"); #ifdef LIBRAW_LIBRARY_BUILD // Clear erorneus fuji_width if not set through parse_fuji or for DNG if(fuji_width && !dng_version && !(imgdata.process_warnings & LIBRAW_WARN_PARSEFUJI_PROCESSED )) fuji_width = 0; #endif if (fuji_width) { fuji_width = width >> !fuji_layout; filters = fuji_width & 1 ? 0x94949494 : 0x49494949; width = (height >> fuji_layout) + fuji_width; height = width - 1; pixel_aspect = 1; } else { if (raw_height < height) raw_height = height; if (raw_width < width) raw_width = width; } if (!tiff_bps) tiff_bps = 12; if (!maximum) { maximum = (1 << tiff_bps) - 1; if (maximum < 0x10000 && curve[maximum] > 0 && load_raw == &CLASS sony_arw2_load_raw) maximum = curve[maximum]; } if (!load_raw || height < 22 || width < 22 || #ifdef LIBRAW_LIBRARY_BUILD (tiff_bps > 16 && load_raw != &LibRaw::deflate_dng_load_raw) #else tiff_bps > 16 #endif || tiff_samples > 6 || colors > 4) is_raw = 0; if (raw_width < 22 || raw_width > 64000 || raw_height < 22 || raw_height > 64000) is_raw = 0; #ifdef NO_JASPER if (load_raw == &CLASS redcine_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjasper"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JASPER; #endif } #endif #ifdef NO_JPEG if (load_raw == &CLASS kodak_jpeg_load_raw || load_raw == &CLASS lossy_dng_load_raw) { #ifdef DCRAW_VERBOSE fprintf(stderr, _("%s: You must link dcraw with %s!!\n"), ifname, "libjpeg"); #endif is_raw = 0; #ifdef LIBRAW_LIBRARY_BUILD imgdata.process_warnings |= LIBRAW_WARN_NO_JPEGLIB; #endif } #endif if (!cdesc[0]) strcpy(cdesc, colors == 3 ? "RGBG" : "GMCY"); if (!raw_height) raw_height = height; if (!raw_width) raw_width = width; if (filters > 999 && colors == 3) filters |= ((filters >> 2 & 0x22222222) | (filters << 2 & 0x88888888)) & filters << 1; notraw: if (flip == UINT_MAX) flip = tiff_flip; if (flip == UINT_MAX) flip = 0; // Convert from degrees to bit-field if needed if (flip > 89 || flip < -89) { switch ((flip + 3600) % 360) { case 270: flip = 5; break; case 180: flip = 3; break; case 90: flip = 6; break; } } #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_IDENTIFY, 1, 2); #endif } void CLASS convert_to_rgb() { #ifndef LIBRAW_LIBRARY_BUILD int row, col, c; #endif int i, j, k; #ifndef LIBRAW_LIBRARY_BUILD ushort *img; float out[3]; #endif float out_cam[3][4]; double num, inverse[3][3]; static const double xyzd50_srgb[3][3] = { {0.436083, 0.385083, 0.143055}, {0.222507, 0.716888, 0.060608}, {0.013930, 0.097097, 0.714022}}; static const double rgb_rgb[3][3] = {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}}; static const double adobe_rgb[3][3] = { {0.715146, 0.284856, 0.000000}, {0.000000, 1.000000, 0.000000}, {0.000000, 0.041166, 0.958839}}; static const double wide_rgb[3][3] = { {0.593087, 0.404710, 0.002206}, {0.095413, 0.843149, 0.061439}, {0.011621, 0.069091, 0.919288}}; static const double prophoto_rgb[3][3] = { {0.529317, 0.330092, 0.140588}, {0.098368, 0.873465, 0.028169}, {0.016879, 0.117663, 0.865457}}; static const double aces_rgb[3][3] = { {0.432996, 0.375380, 0.189317}, {0.089427, 0.816523, 0.102989}, {0.019165, 0.118150, 0.941914}}; static const double(*out_rgb[])[3] = {rgb_rgb, adobe_rgb, wide_rgb, prophoto_rgb, xyz_rgb, aces_rgb}; static const char *name[] = {"sRGB", "Adobe RGB (1998)", "WideGamut D65", "ProPhoto D65", "XYZ", "ACES"}; static const unsigned phead[] = {1024, 0, 0x2100000, 0x6d6e7472, 0x52474220, 0x58595a20, 0, 0, 0, 0x61637370, 0, 0, 0x6e6f6e65, 0, 0, 0, 0, 0xf6d6, 0x10000, 0xd32d}; unsigned pbody[] = {10, 0x63707274, 0, 36, /* cprt */ 0x64657363, 0, 40, /* desc */ 0x77747074, 0, 20, /* wtpt */ 0x626b7074, 0, 20, /* bkpt */ 0x72545243, 0, 14, /* rTRC */ 0x67545243, 0, 14, /* gTRC */ 0x62545243, 0, 14, /* bTRC */ 0x7258595a, 0, 20, /* rXYZ */ 0x6758595a, 0, 20, /* gXYZ */ 0x6258595a, 0, 20}; /* bXYZ */ static const unsigned pwhite[] = {0xf351, 0x10000, 0x116cc}; unsigned pcurve[] = {0x63757276, 0, 1, 0x1000000}; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 0, 2); #endif gamma_curve(gamm[0], gamm[1], 0, 0); memcpy(out_cam, rgb_cam, sizeof out_cam); #ifndef LIBRAW_LIBRARY_BUILD raw_color |= colors == 1 || document_mode || output_color < 1 || output_color > 6; #else raw_color |= colors == 1 || output_color < 1 || output_color > 6; #endif if (!raw_color) { oprof = (unsigned *)calloc(phead[0], 1); merror(oprof, "convert_to_rgb()"); memcpy(oprof, phead, sizeof phead); if (output_color == 5) oprof[4] = oprof[5]; oprof[0] = 132 + 12 * pbody[0]; for (i = 0; i < pbody[0]; i++) { oprof[oprof[0] / 4] = i ? (i > 1 ? 0x58595a20 : 0x64657363) : 0x74657874; pbody[i * 3 + 2] = oprof[0]; oprof[0] += (pbody[i * 3 + 3] + 3) & -4; } memcpy(oprof + 32, pbody, sizeof pbody); oprof[pbody[5] / 4 + 2] = strlen(name[output_color - 1]) + 1; memcpy((char *)oprof + pbody[8] + 8, pwhite, sizeof pwhite); pcurve[3] = (short)(256 / gamm[5] + 0.5) << 16; for (i = 4; i < 7; i++) memcpy((char *)oprof + pbody[i * 3 + 2], pcurve, sizeof pcurve); pseudoinverse((double(*)[3])out_rgb[output_color - 1], inverse, 3); for (i = 0; i < 3; i++) for (j = 0; j < 3; j++) { for (num = k = 0; k < 3; k++) num += xyzd50_srgb[i][k] * inverse[j][k]; oprof[pbody[j * 3 + 23] / 4 + i + 2] = num * 0x10000 + 0.5; } for (i = 0; i < phead[0] / 4; i++) oprof[i] = htonl(oprof[i]); strcpy((char *)oprof + pbody[2] + 8, "auto-generated by dcraw"); strcpy((char *)oprof + pbody[5] + 12, name[output_color - 1]); for (i = 0; i < 3; i++) for (j = 0; j < colors; j++) for (out_cam[i][j] = k = 0; k < 3; k++) out_cam[i][j] += out_rgb[output_color - 1][i][k] * rgb_cam[k][j]; } #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, raw_color ? _("Building histograms...\n") : _("Converting to %s colorspace...\n"), name[output_color - 1]); #endif #ifdef LIBRAW_LIBRARY_BUILD convert_to_rgb_loop(out_cam); #else memset(histogram, 0, sizeof histogram); for (img = image[0], row = 0; row < height; row++) for (col = 0; col < width; col++, img += 4) { if (!raw_color) { out[0] = out[1] = out[2] = 0; FORCC { out[0] += out_cam[0][c] * img[c]; out[1] += out_cam[1][c] * img[c]; out[2] += out_cam[2][c] * img[c]; } FORC3 img[c] = CLIP((int)out[c]); } else if (document_mode) img[0] = img[fcol(row, col)]; FORCC histogram[c][img[c] >> 3]++; } #endif if (colors == 4 && output_color) colors = 3; #ifndef LIBRAW_LIBRARY_BUILD if (document_mode && filters) colors = 1; #endif #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_CONVERT_RGB, 1, 2); #endif } void CLASS fuji_rotate() { int i, row, col; double step; float r, c, fr, fc; unsigned ur, uc; ushort wide, high, (*img)[4], (*pix)[4]; if (!fuji_width) return; #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Rotating image 45 degrees...\n")); #endif fuji_width = (fuji_width - 1 + shrink) >> shrink; step = sqrt(0.5); wide = fuji_width / step; high = (height - fuji_width) / step; img = (ushort(*)[4])calloc(high, wide * sizeof *img); merror(img, "fuji_rotate()"); #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 0, 2); #endif for (row = 0; row < high; row++) for (col = 0; col < wide; col++) { ur = r = fuji_width + (row - col) * step; uc = c = (row + col) * step; if (ur > height - 2 || uc > width - 2) continue; fr = r - ur; fc = c - uc; pix = image + ur * width + uc; for (i = 0; i < colors; i++) img[row * wide + col][i] = (pix[0][i] * (1 - fc) + pix[1][i] * fc) * (1 - fr) + (pix[width][i] * (1 - fc) + pix[width + 1][i] * fc) * fr; } free(image); width = wide; height = high; image = img; fuji_width = 0; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_FUJI_ROTATE, 1, 2); #endif } void CLASS stretch() { ushort newdim, (*img)[4], *pix0, *pix1; int row, col, c; double rc, frac; if (pixel_aspect == 1) return; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 0, 2); #endif #ifdef DCRAW_VERBOSE if (verbose) fprintf(stderr, _("Stretching the image...\n")); #endif if (pixel_aspect < 1) { newdim = height / pixel_aspect + 0.5; img = (ushort(*)[4])calloc(width, newdim * sizeof *img); merror(img, "stretch()"); for (rc = row = 0; row < newdim; row++, rc += pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c * width]; if (c + 1 < height) pix1 += width * 4; for (col = 0; col < width; col++, pix0 += 4, pix1 += 4) FORCC img[row * width + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } height = newdim; } else { newdim = width * pixel_aspect + 0.5; img = (ushort(*)[4])calloc(height, newdim * sizeof *img); merror(img, "stretch()"); for (rc = col = 0; col < newdim; col++, rc += 1 / pixel_aspect) { frac = rc - (c = rc); pix0 = pix1 = image[c]; if (c + 1 < width) pix1 += 4; for (row = 0; row < height; row++, pix0 += width * 4, pix1 += width * 4) FORCC img[row * newdim + col][c] = pix0[c] * (1 - frac) + pix1[c] * frac + 0.5; } width = newdim; } free(image); image = img; #ifdef LIBRAW_LIBRARY_BUILD RUN_CALLBACK(LIBRAW_PROGRESS_STRETCH, 1, 2); #endif } int CLASS flip_index(int row, int col) { if (flip & 4) SWAP(row, col); if (flip & 2) row = iheight - 1 - row; if (flip & 1) col = iwidth - 1 - col; return row * iwidth + col; } void CLASS tiff_set(struct tiff_hdr *th, ushort *ntag, ushort tag, ushort type, int count, int val) { struct tiff_tag *tt; int c; tt = (struct tiff_tag *)(ntag + 1) + (*ntag)++; tt->val.i = val; if (type == 1 && count <= 4) FORC(4) tt->val.c[c] = val >> (c << 3); else if (type == 2) { count = strnlen((char *)th + val, count - 1) + 1; if (count <= 4) FORC(4) tt->val.c[c] = ((char *)th)[val + c]; } else if (type == 3 && count <= 2) FORC(2) tt->val.s[c] = val >> (c << 4); tt->count = count; tt->type = type; tt->tag = tag; } #define TOFF(ptr) ((char *)(&(ptr)) - (char *)th) void CLASS tiff_head(struct tiff_hdr *th, int full) { int c, psize = 0; struct tm *t; memset(th, 0, sizeof *th); th->t_order = htonl(0x4d4d4949) >> 16; th->magic = 42; th->ifd = 10; th->rat[0] = th->rat[2] = 300; th->rat[1] = th->rat[3] = 1; FORC(6) th->rat[4 + c] = 1000000; th->rat[4] *= shutter; th->rat[6] *= aperture; th->rat[8] *= focal_len; strncpy(th->t_desc, desc, 512); strncpy(th->t_make, make, 64); strncpy(th->t_model, model, 64); strcpy(th->soft, "dcraw v" DCRAW_VERSION); t = localtime(&timestamp); sprintf(th->date, "%04d:%02d:%02d %02d:%02d:%02d", t->tm_year + 1900, t->tm_mon + 1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); strncpy(th->t_artist, artist, 64); if (full) { tiff_set(th, &th->ntag, 254, 4, 1, 0); tiff_set(th, &th->ntag, 256, 4, 1, width); tiff_set(th, &th->ntag, 257, 4, 1, height); tiff_set(th, &th->ntag, 258, 3, colors, output_bps); if (colors > 2) th->tag[th->ntag - 1].val.i = TOFF(th->bps); FORC4 th->bps[c] = output_bps; tiff_set(th, &th->ntag, 259, 3, 1, 1); tiff_set(th, &th->ntag, 262, 3, 1, 1 + (colors > 1)); } tiff_set(th, &th->ntag, 270, 2, 512, TOFF(th->t_desc)); tiff_set(th, &th->ntag, 271, 2, 64, TOFF(th->t_make)); tiff_set(th, &th->ntag, 272, 2, 64, TOFF(th->t_model)); if (full) { if (oprof) psize = ntohl(oprof[0]); tiff_set(th, &th->ntag, 273, 4, 1, sizeof *th + psize); tiff_set(th, &th->ntag, 277, 3, 1, colors); tiff_set(th, &th->ntag, 278, 4, 1, height); tiff_set(th, &th->ntag, 279, 4, 1, height * width * colors * output_bps / 8); } else tiff_set(th, &th->ntag, 274, 3, 1, "12435867"[flip] - '0'); tiff_set(th, &th->ntag, 282, 5, 1, TOFF(th->rat[0])); tiff_set(th, &th->ntag, 283, 5, 1, TOFF(th->rat[2])); tiff_set(th, &th->ntag, 284, 3, 1, 1); tiff_set(th, &th->ntag, 296, 3, 1, 2); tiff_set(th, &th->ntag, 305, 2, 32, TOFF(th->soft)); tiff_set(th, &th->ntag, 306, 2, 20, TOFF(th->date)); tiff_set(th, &th->ntag, 315, 2, 64, TOFF(th->t_artist)); tiff_set(th, &th->ntag, 34665, 4, 1, TOFF(th->nexif)); if (psize) tiff_set(th, &th->ntag, 34675, 7, psize, sizeof *th); tiff_set(th, &th->nexif, 33434, 5, 1, TOFF(th->rat[4])); tiff_set(th, &th->nexif, 33437, 5, 1, TOFF(th->rat[6])); tiff_set(th, &th->nexif, 34855, 3, 1, iso_speed); tiff_set(th, &th->nexif, 37386, 5, 1, TOFF(th->rat[8])); if (gpsdata[1]) { tiff_set(th, &th->ntag, 34853, 4, 1, TOFF(th->ngps)); tiff_set(th, &th->ngps, 0, 1, 4, 0x202); tiff_set(th, &th->ngps, 1, 2, 2, gpsdata[29]); tiff_set(th, &th->ngps, 2, 5, 3, TOFF(th->gps[0])); tiff_set(th, &th->ngps, 3, 2, 2, gpsdata[30]); tiff_set(th, &th->ngps, 4, 5, 3, TOFF(th->gps[6])); tiff_set(th, &th->ngps, 5, 1, 1, gpsdata[31]); tiff_set(th, &th->ngps, 6, 5, 1, TOFF(th->gps[18])); tiff_set(th, &th->ngps, 7, 5, 3, TOFF(th->gps[12])); tiff_set(th, &th->ngps, 18, 2, 12, TOFF(th->gps[20])); tiff_set(th, &th->ngps, 29, 2, 12, TOFF(th->gps[23])); memcpy(th->gps, gpsdata, sizeof th->gps); } } #ifdef LIBRAW_LIBRARY_BUILD void CLASS jpeg_thumb_writer(FILE *tfp, char *t_humb, int t_humb_length) { ushort exif[5]; struct tiff_hdr th; fputc(0xff, tfp); fputc(0xd8, tfp); if (strcmp(t_humb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, tfp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, tfp); } fwrite(t_humb + 2, 1, t_humb_length - 2, tfp); } void CLASS jpeg_thumb() { char *thumb; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); jpeg_thumb_writer(ofp, thumb, thumb_length); free(thumb); } #else void CLASS jpeg_thumb() { char *thumb; ushort exif[5]; struct tiff_hdr th; thumb = (char *)malloc(thumb_length); merror(thumb, "jpeg_thumb()"); fread(thumb, 1, thumb_length, ifp); fputc(0xff, ofp); fputc(0xd8, ofp); if (strcmp(thumb + 6, "Exif")) { memcpy(exif, "\xff\xe1 Exif\0\0", 10); exif[1] = htons(8 + sizeof th); fwrite(exif, 1, sizeof exif, ofp); tiff_head(&th, 0); fwrite(&th, 1, sizeof th, ofp); } fwrite(thumb + 2, 1, thumb_length - 2, ofp); free(thumb); } #endif void CLASS write_ppm_tiff() { struct tiff_hdr th; uchar *ppm; ushort *ppm2; int c, row, col, soff, rstep, cstep; int perc, val, total, t_white = 0x2000; #ifdef LIBRAW_LIBRARY_BUILD perc = width * height * auto_bright_thr; #else perc = width * height * 0.01; /* 99th percentile white level */ #endif if (fuji_width) perc /= 2; if (!((highlight & ~2) || no_auto_bright)) for (t_white = c = 0; c < colors; c++) { for (val = 0x2000, total = 0; --val > 32;) if ((total += histogram[c][val]) > perc) break; if (t_white < val) t_white = val; } gamma_curve(gamm[0], gamm[1], 2, (t_white << 3) / bright); iheight = height; iwidth = width; if (flip & 4) SWAP(height, width); ppm = (uchar *)calloc(width, colors * output_bps / 8); ppm2 = (ushort *)ppm; merror(ppm, "write_ppm_tiff()"); if (output_tiff) { tiff_head(&th, 1); fwrite(&th, sizeof th, 1, ofp); if (oprof) fwrite(oprof, ntohl(oprof[0]), 1, ofp); } else if (colors > 3) fprintf(ofp, "P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE %s\nENDHDR\n", width, height, colors, (1 << output_bps) - 1, cdesc); else fprintf(ofp, "P%d\n%d %d\n%d\n", colors / 2 + 5, width, height, (1 << output_bps) - 1); soff = flip_index(0, 0); cstep = flip_index(0, 1) - soff; rstep = flip_index(1, 0) - flip_index(0, width); for (row = 0; row < height; row++, soff += rstep) { for (col = 0; col < width; col++, soff += cstep) if (output_bps == 8) FORCC ppm[col * colors + c] = curve[image[soff][c]] >> 8; else FORCC ppm2[col * colors + c] = curve[image[soff][c]]; if (output_bps == 16 && !output_tiff && htons(0x55aa) != 0x55aa) swab((char *)ppm2, (char *)ppm2, width * colors * 2); fwrite(ppm, colors * output_bps / 8, width, ofp); } free(ppm); }
./CrossVul/dataset_final_sorted/CWE-125/cpp/good_2946_1